<?php
// admin_import_review.php — Patch V5: Order-card grouped admin approval
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/csv_module_common.php';
require_login();
require_role(['admin', 'production_manager']);

/* ── Helpers ── */
function air_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function air_date($v): string { $v = trim((string)$v); return ($v===''||$v==='0000-00-00') ? '-' : substr($v,0,10); }
function air_url(array $extra=[]): string {
    $q = array_merge($_GET, $extra);
    foreach ($q as $k=>$v) if ($v===null||$v===''||$v==='all') unset($q[$k]);
    return 'admin_import_review.php'.($q?'?'.http_build_query($q):'');
}
function air_ship_urgency(string $date): string {
    if (!$date||$date==='0000-00-00'||$date==='-') return '';
    try {
        $today  = new DateTime('today');
        $shipBy = new DateTime($date);
        $diff   = (int)$today->diff($shipBy)->format('%r%a');
        if ($diff < 0) return 'overdue';
        if ($diff === 0) return 'today';
        if ($diff === 1) return 'tomorrow';
        if ($diff <= 3) return 'soon';
    } catch (Throwable $e) {}
    return '';
}
function air_ship_label(string $t): string { return match($t){'express'=>'⚡ EXPRESS','international'=>"🌍 INT'L",default=>'EKO'}; }
function air_ship_badge(string $t): string { return match($t){'express'=>'op-badge-express','international'=>'op-badge-intl',default=>'op-badge-muted'}; }
function air_truncate(string $s, int $max=55): string { return mb_strlen($s,'UTF-8')>$max?mb_substr($s,0,$max,'UTF-8').'…':$s; }

/* ── Next production no ── */
function air_next_production_no(PDO $pdo): int {
    $pdo->exec("INSERT IGNORE INTO erp_counters (counter_key,next_value,updated_at) VALUES ('production_no',10001,NOW())");
    $stmt = $pdo->prepare("SELECT next_value FROM erp_counters WHERE counter_key='production_no' FOR UPDATE");
    $stmt->execute();
    $next = (int)$stmt->fetchColumn();
    if ($next <= 0) $next = 10001;
    $upd = $pdo->prepare("UPDATE erp_counters SET next_value=:v,updated_at=NOW() WHERE counter_key='production_no'");
    $upd->execute(['v' => $next + 1]);
    return $next;
}

$user   = current_user();
$userId = (int)$user['id'];

/* ──────────────────────────────────────────────────────────────
   POST handler — approve / reject (bulk OR per-group)
────────────────────────────────────────────────────────────── */
if (is_post()) {
    verify_csrf();

    $action       = $_POST['action']            ?? '';
    $groupKey     = trim((string)($_POST['group_approve_key'] ?? ''));
    $adminNote    = trim((string)($_POST['admin_note']        ?? ''));
    $rejectReason = trim((string)($_POST['reject_reason']     ?? ''));

    if (!in_array($action, ['approve', 'reject'], true)) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Geçersiz işlem.'];
        redirect('admin_import_review.php');
    }
    if ($action === 'reject' && $rejectReason === '') {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Red için sebep/not zorunlu.'];
        redirect('admin_import_review.php');
    }

    /* Determine which row IDs to process */
    if ($groupKey !== '') {
        // Per-group approval: auto-select all rows with this order_group_key
        $stmt = db()->prepare("SELECT id FROM csv_import_rows WHERE order_group_key = :k AND row_status = 'admin_pending'");
        $stmt->execute(['k' => $groupKey]);
        $ids = array_column($stmt->fetchAll(), 'id');
        // Also pick up any rows without a key that match this fallback
        if (empty($ids)) {
            // Fallback: try matching via row IDs passed in hidden inputs
            $ids = array_values(array_unique(array_map('intval', $_POST['group_row_ids'] ?? [])));
        }
    } else {
        $ids = array_values(array_unique(array_map('intval', $_POST['row_ids'] ?? [])));
    }

    if (!$ids) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Satır seçilmedi.'];
        redirect('admin_import_review.php');
    }

    $newStatusId = (int)db()->query("SELECT id FROM production_statuses WHERE status_code='new_order' LIMIT 1")->fetchColumn();
    if ($action === 'approve' && $newStatusId <= 0) {
        $_SESSION['flash'] = ['type'=>'error','msg'=>'Yeni Sipariş üretim durumu bulunamadı. SQL migration çalıştırılmalı.'];
        redirect('admin_import_review.php');
    }

    $pdo = db();
    $pdo->beginTransaction();
    try {
        $approvedUnits = 0;
        $rejectedRows  = 0;

        foreach ($ids as $id) {
            $stmt = $pdo->prepare("SELECT * FROM csv_import_rows WHERE id=:id AND row_status='admin_pending' FOR UPDATE");
            $stmt->execute(['id'=>$id]);
            $row = $stmt->fetch();
            if (!$row) continue;

            if ($action === 'approve') {
                $qty         = max(1, (int)($row['quantity'] ?? 1));
                $isCustom    = csv_mod_is_custom_sku($row['sku']??'', $row['listing_title']??'') ? 1 : 0;
                $rowNet      = $row['net_item_total'] !== null
                    ? (float)$row['net_item_total']
                    : (csv_mod_net_item_total($row['price']??null, $row['discount_amount']??null) ?? null);
                $unitNet     = $rowNet !== null ? round($rowNet / $qty, 2) : null;
                $unitOrderTotal = null;
                if ($row['order_total'] !== null && $qty > 0) {
                    $unitOrderTotal = round(((float)$row['order_total']) / $qty, 2);
                }

                $insert = $pdo->prepare("
                    INSERT INTO order_items (
                        production_no, transaction_id, source_transaction_id, etsy_order_id,
                        order_group_key, customer_group_key, store_id,
                        product_id, product_store_sku_id, current_status_id, csv_import_log_id,
                        sku, listing_id, listing_title, product_card_missing, product_image_path,
                        buyer_name, buyer_username,
                        ship_name, ship_address1, ship_address2, ship_city, ship_state, ship_zip, ship_country,
                        sale_date, paid_date, ship_by_date, shipped_date,
                        quantity, quantity_unit_index, quantity_unit_total,
                        price, currency, order_total,
                        coupon_code, discount_amount, net_item_total,
                        shipping_discount, order_shipping, order_sales_tax, shipping_type,
                        variations_text, personalization,
                        parsed_karat, parsed_color, parsed_size, parsed_chain_length,
                        carrier, flagged_customer_id, flagged_customer_match_text, flag_match_type,
                        is_custom, raw_csv_json, store_note, admin_note,
                        created_at
                    ) VALUES (
                        :production_no, :transaction_id, :source_transaction_id, :etsy_order_id,
                        :order_group_key, :customer_group_key, :store_id,
                        :product_id, :product_store_sku_id, :current_status_id, :csv_import_log_id,
                        :sku, :listing_id, :listing_title, :product_card_missing, :product_image_path,
                        :buyer_name, :buyer_username,
                        :ship_name, :ship_address1, :ship_address2, :ship_city, :ship_state, :ship_zip, :ship_country,
                        :sale_date, :paid_date, :ship_by_date, :shipped_date,
                        1, :quantity_unit_index, :quantity_unit_total,
                        :price, :currency, :order_total,
                        :coupon_code, :discount_amount, :net_item_total,
                        :shipping_discount, :order_shipping, :order_sales_tax, :shipping_type,
                        :variations_text, :personalization,
                        :parsed_karat, :parsed_color, :parsed_size, :parsed_chain_length,
                        :carrier, :flagged_customer_id, :flagged_customer_match_text, :flag_match_type,
                        :is_custom, :raw_csv_json, :store_note, :admin_note,
                        NOW()
                    )
                    ON DUPLICATE KEY UPDATE updated_at = NOW()
                ");

                $firstOrderItemId = null;
                for ($i = 1; $i <= $qty; $i++) {
                    $productionNo    = air_next_production_no($pdo);
                    $productionTxnId = $qty > 1 ? ($row['transaction_id'].'-'.$i) : $row['transaction_id'];
                    $rawArr = json_decode($row['raw_csv_json'] ?: '{}', true);
                    if (!is_array($rawArr)) $rawArr = [];
                    $rawArr['_erp_production_no']         = $productionNo;
                    $rawArr['_erp_quantity_unit_index']   = $i;
                    $rawArr['_erp_quantity_unit_total']   = $qty;
                    $rawArr['_erp_source_transaction_id'] = $row['transaction_id'];

                    $insert->execute([
                        'production_no'              => $productionNo,
                        'transaction_id'             => $productionTxnId,
                        'source_transaction_id'      => $row['transaction_id'],
                        'etsy_order_id'              => $row['etsy_order_id'],
                        'order_group_key'            => $row['order_group_key'] ?: csv_mod_order_group_key($row['etsy_order_id']??'', $row['ship_name']??$row['buyer_name']??'', $row['ship_by_date']??''),
                        'customer_group_key'         => $row['customer_group_key'] ?: csv_mod_customer_group_key($row['ship_name']??$row['buyer_name']??'', $row['ship_address1']??''),
                        'store_id'                   => $row['store_id'],
                        'product_id'                 => $row['product_id'],
                        'product_store_sku_id'       => $row['product_store_sku_id'],
                        'current_status_id'          => $newStatusId,
                        'csv_import_log_id'          => $row['csv_import_log_id'],
                        'sku'                        => $row['sku'],
                        'listing_id'                 => $row['listing_id'],
                        'listing_title'              => $row['listing_title'],
                        'product_card_missing'       => $row['product_card_missing'],
                        'product_image_path'         => $row['product_image_path'],
                        'buyer_name'                 => $row['buyer_name'],
                        'buyer_username'             => $row['buyer_username'],
                        'ship_name'                  => $row['ship_name'],
                        'ship_address1'              => $row['ship_address1'],
                        'ship_address2'              => $row['ship_address2'],
                        'ship_city'                  => $row['ship_city'],
                        'ship_state'                 => $row['ship_state'],
                        'ship_zip'                   => $row['ship_zip'],
                        'ship_country'               => $row['ship_country'],
                        'sale_date'                  => $row['sale_date'],
                        'paid_date'                  => $row['paid_date'],
                        'ship_by_date'               => $row['ship_by_date'],
                        'shipped_date'               => $row['shipped_date'],
                        'quantity_unit_index'        => $i,
                        'quantity_unit_total'        => $qty,
                        'price'                      => $row['price'],
                        'currency'                   => $row['currency'],
                        'order_total'                => $unitOrderTotal ?? $row['order_total'],
                        'coupon_code'                => $row['coupon_code'],
                        'discount_amount'            => $row['discount_amount'],
                        'net_item_total'             => $unitNet,
                        'shipping_discount'          => $row['shipping_discount'],
                        'order_shipping'             => $row['order_shipping'],
                        'order_sales_tax'            => $row['order_sales_tax'],
                        'shipping_type'              => $row['shipping_type'] ?: csv_mod_shipping_type_from_values($row['order_shipping']??null, $row['ship_country']??''),
                        'variations_text'            => $row['variations_text'],
                        'personalization'            => $row['personalization'],
                        'parsed_karat'               => $row['parsed_karat'],
                        'parsed_color'               => $row['parsed_color'],
                        'parsed_size'                => $row['parsed_size'],
                        'parsed_chain_length'        => $row['parsed_chain_length'],
                        'carrier'                    => $row['carrier'],
                        'flagged_customer_id'        => $row['flagged_customer_id'],
                        'flagged_customer_match_text'=> $row['flag_admin_detail'],
                        'flag_match_type'            => $row['flag_match_type'],
                        'is_custom'                  => $isCustom,
                        'raw_csv_json'               => json_encode($rawArr, JSON_UNESCAPED_UNICODE),
                        'store_note'                 => $row['store_note'],
                        'admin_note'                 => $adminNote ?: null,
                    ]);

                    $orderItemId = (int)$pdo->lastInsertId();
                    if ($orderItemId === 0) {
                        $lk = $pdo->prepare("SELECT id FROM order_items WHERE transaction_id=:tid LIMIT 1");
                        $lk->execute(['tid'=>$productionTxnId]);
                        $orderItemId = (int)$lk->fetchColumn();
                    }
                    if (!$firstOrderItemId && $orderItemId > 0) $firstOrderItemId = $orderItemId;

                    if ($orderItemId > 0) {
                        $log = $pdo->prepare("
                            INSERT INTO production_logs (order_item_id, from_status_id, to_status_id, changed_by, changed_at, note)
                            VALUES (:oi, NULL, :ts, :cb, NOW(), :note)
                        ");
                        $qtyNote = $qty > 1 ? " Parça: {$i}/{$qty}." : '';
                        $log->execute([
                            'oi'   => $orderItemId,
                            'ts'   => $newStatusId,
                            'cb'   => $userId,
                            'note' => "Admin onayından üretim kuyruğuna alındı. Sıra No: {$productionNo}.{$qtyNote}" . ($adminNote ? " Admin notu: {$adminNote}" : ''),
                        ]);

                        if (!empty($row['flagged_customer_id'])) {
                            $fm = $pdo->prepare("
                                INSERT INTO flagged_customer_matches (order_item_id, flagged_customer_id, match_type, match_value)
                                VALUES (:oi, :fc, :mt, :mv)
                            ");
                            $fm->execute([
                                'oi' => $orderItemId,
                                'fc' => $row['flagged_customer_id'],
                                'mt' => $row['flag_match_type'] ?: 'csv_import',
                                'mv' => $row['flag_admin_detail'],
                            ]);
                        }
                        $approvedUnits++;
                    }
                }

                $pdo->prepare("
                    UPDATE csv_import_rows
                    SET admin_decision='approved', admin_decided_by=:by, admin_decided_at=NOW(),
                        admin_note=:note, row_status='converted_to_order',
                        converted_order_item_id=:oi, updated_at=NOW()
                    WHERE id=:id
                ")->execute(['by'=>$userId,'note'=>$adminNote?:null,'oi'=>$firstOrderItemId?:null,'id'=>$id]);

            } else { // reject
                $pdo->prepare("
                    UPDATE csv_import_rows
                    SET admin_decision='rejected', admin_decided_by=:by, admin_decided_at=NOW(),
                        admin_note=:note, admin_rejection_reason=:reason,
                        row_status='admin_rejected', updated_at=NOW()
                    WHERE id=:id
                ")->execute(['by'=>$userId,'note'=>$adminNote?:null,'reason'=>$rejectReason,'id'=>$id]);
                $rejectedRows++;
            }
        }

        $pdo->commit();
        $_SESSION['flash'] = [
            'type' => 'success',
            'msg'  => $action === 'approve'
                ? "{$approvedUnits} üretim satırı oluşturuldu (sıra no verildi)."
                : "{$rejectedRows} satır reddedildi.",
        ];
        redirect('admin_import_review.php');
    } catch (Throwable $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo 'Admin onay işlemi sırasında hata: ' . air_h($e->getMessage());
        exit;
    }
}

/* ──────────────────────────────────────────────────────────────
   GET: Fetch + group pending rows
────────────────────────────────────────────────────────────── */
$filterStore = (int)($_GET['store_id'] ?? 0);
$filter      = $_GET['filter'] ?? 'all';
$q           = trim((string)($_GET['q'] ?? ''));

$sql    = "
    SELECT r.*, s.store_code, s.store_name, u.full_name AS store_user_name,
           p.master_code, p.product_name, specs.short_name,
           COALESCE(pi.file_path, r.product_image_path) AS product_img
    FROM csv_import_rows r
    JOIN stores s        ON s.id = r.store_id
    LEFT JOIN users u    ON u.id = r.store_decided_by
    LEFT JOIN products p ON p.id = r.product_id
    LEFT JOIN product_core_specs specs ON specs.product_id = p.id
    LEFT JOIN product_images pi ON pi.product_id = p.id AND pi.is_primary = 1
    WHERE r.row_status = 'admin_pending'
";
$params = [];
if ($filterStore > 0) { $sql .= " AND r.store_id = :store_id"; $params['store_id'] = $filterStore; }
$sql .= " ORDER BY COALESCE(r.ship_by_date, DATE(r.sale_date), DATE(r.created_at)) ASC, r.etsy_order_id ASC, r.id ASC";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

/* ── Decorate + group ── */
$customerOrders = [];
foreach ($rows as $r) {
    $ck = (string)($r['customer_group_key'] ?: csv_mod_customer_group_key($r['ship_name']??$r['buyer_name']??'', $r['ship_address1']??''));
    $og = (string)($r['order_group_key']    ?: csv_mod_order_group_key($r['etsy_order_id']??'', $r['ship_name']??$r['buyer_name']??'', $r['ship_by_date']??''));
    if ($ck!=='') $customerOrders[$ck][$og] = true;
}
$decorated = [];
foreach ($rows as $r) {
    $ck = (string)($r['customer_group_key'] ?: csv_mod_customer_group_key($r['ship_name']??$r['buyer_name']??'', $r['ship_address1']??''));
    $og = (string)($r['order_group_key']    ?: csv_mod_order_group_key($r['etsy_order_id']??'', $r['ship_name']??$r['buyer_name']??'', $r['ship_by_date']??''));
    $r['_ck']            = $ck;
    $r['_og']            = $og;
    $r['_is_custom']     = csv_mod_is_custom_sku($r['sku']??'', $r['listing_title']??'');
    $r['_qty_multi']     = (int)($r['quantity']??1) > 1;
    $r['_is_missing']    = (int)($r['product_card_missing']??0) === 1;
    $r['_is_risk']       = (int)($r['has_flag_warning']??0) === 1;
    $r['_is_blocked']    = ($r['flag_match_type']??'') === 'blocked';
    $r['_is_suspicious'] = ($r['flag_match_type']??'') === 'suspicious';
    $r['_is_express']    = ($r['shipping_type']??'') === 'express';
    $r['_multi_order']   = $ck!=='' && count($customerOrders[$ck]??[]) > 1;
    if (!$r['_is_missing'] && !empty($r['short_name'])) {
        $r['_display_name'] = $r['short_name'];
        $r['_name_source']  = 'card';
    } elseif (!$r['_is_missing'] && !empty($r['product_name'])) {
        $r['_display_name'] = $r['product_name'];
        $r['_name_source']  = 'card';
    } else {
        $r['_display_name'] = air_truncate($r['listing_title']??'-', 55);
        $r['_name_source']  = 'etsy';
    }
    $r['_net'] = $r['net_item_total'] ?? csv_mod_net_item_total($r['price']??null, $r['discount_amount']??null);
    $decorated[] = $r;
}

$filtered = [];
foreach ($decorated as $r) {
    $ok = match($filter) {
        'missing'       => $r['_is_missing'],
        'risk'          => $r['_is_risk'],
        'blocked'       => $r['_is_blocked'],
        'suspicious'    => $r['_is_suspicious'],
        'custom'        => $r['_is_custom'],
        'multi_qty'     => $r['_qty_multi'],
        'same_customer' => $r['_multi_order'],
        'express'       => $r['_is_express'],
        default         => true,
    };
    if (!$ok) continue;
    if ($q!=='') {
        $needle = mb_strtolower($q,'UTF-8');
        $hay    = mb_strtolower(json_encode($r,JSON_UNESCAPED_UNICODE),'UTF-8');
        if (!str_contains($hay,$needle)) continue;
    }
    $filtered[] = $r;
}

$groups = [];
foreach ($filtered as $r) {
    $key = $r['_og'] ?: ('row:'.$r['id']);
    if (!isset($groups[$key])) {
        $groups[$key] = [
            'key'           => $key,
            'order_id'      => $r['etsy_order_id'] ?: '-',
            'customer'      => $r['ship_name'] ?: $r['buyer_name'] ?: '-',
            'ship_by'       => $r['ship_by_date'] ?: '',
            'store_code'    => $r['store_code'],
            'store_user'    => $r['store_user_name'] ?: '-',
            'city'          => trim(($r['ship_city']??'').', '.($r['ship_state']??'').' · '.($r['ship_country']??'')),
            'address'       => trim(($r['ship_address1']??'').' '.($r['ship_address2']??'')."\n".($r['ship_city']??'').', '.($r['ship_state']??'').' '.($r['ship_zip']??'')."\n".($r['ship_country']??'')),
            'shipping_type' => $r['shipping_type'] ?: 'standard',
            'rows'          => [],
            'warnings'      => [],
            'unit_count'    => 0,
        ];
    }
    $groups[$key]['rows'][] = $r;
}
foreach ($groups as &$g) {
    $rows = $g['rows']; $sumQty = 0;
    foreach ($rows as $r) $sumQty += max(1,(int)($r['quantity']??1));
    $g['unit_count'] = $sumQty;
    $w = [];
    if (array_filter($rows,fn($r)=>$r['_is_blocked']))                              { $w[]=['YASAKLI MÜŞTERİ','danger']; }
    elseif (array_filter($rows,fn($r)=>$r['_is_suspicious']||$r['_is_risk']))       { $w[]=['ŞÜPHELİ MÜŞTERİ','danger']; }
    if (array_filter($rows,fn($r)=>$r['_multi_order']))                             { $w[]=['AYNI MÜŞTERİ — BAŞKA SİPARİŞ VAR','warn']; }
    if ($g['shipping_type']==='express')                                            { $w[]=['⚡ EXPRESS','express']; }
    if (count($rows)>1)                                                             { $w[]=['ÇOKLU ÜRÜN — '.count($rows).' KALEM','warn']; }
    if ($sumQty>count($rows))                                                       { $w[]=['ÇOKLU ADET — '.$sumQty.' POŞET','warn']; }
    if (array_filter($rows,fn($r)=>$r['_is_missing']))                              { $w[]=['ÜRÜN KARTI EKSİK','warn']; }
    if (array_filter($rows,fn($r)=>$r['_is_custom']))                               { $w[]=['CUSTOM / UPGRADE','custom']; }
    $g['warnings'] = $w;
}
unset($g);

$stores           = db()->query("SELECT * FROM stores WHERE is_active=1 ORDER BY store_code")->fetchAll();
$countTotal       = count($decorated);
$countMissing     = count(array_filter($decorated,fn($r)=>$r['_is_missing']));
$countRisk        = count(array_filter($decorated,fn($r)=>$r['_is_risk']));
$countCustom      = count(array_filter($decorated,fn($r)=>$r['_is_custom']));
$countQtyMulti    = count(array_filter($decorated,fn($r)=>$r['_qty_multi']));
$countSameCustomer= count(array_filter($decorated,fn($r)=>$r['_multi_order']));
$countExpress     = count(array_filter($decorated,fn($r)=>$r['_is_express']));

$page_title  = 'CSV Onayları';
$active_menu = 'review';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>CSV Onayları</h1>
    <p>Mağaza onaylı siparişleri order bazlı incele, üretim kuyruğuna al.</p>
  </div>
  <a href="csv_upload.php" class="btn btn-secondary">↑ CSV Yükle</a>
</div>

<!-- ── Stat pills ── -->
<div class="op-stat-grid">
  <a class="op-stat <?=$filter==='all'?'active':''?>"           href="<?=air_h(air_url(['filter'=>'all']))?>">
    <span>Onay Bekleyen</span><strong><?=$countTotal?></strong><em>satır</em></a>
  <a class="op-stat <?=$filter==='missing'?'active':''?>"       href="<?=air_h(air_url(['filter'=>'missing']))?>">
    <span>Ürün Kartı Eksik</span><strong class="yl"><?=$countMissing?></strong><em>SKU eşleşmedi</em></a>
  <a class="op-stat <?=$filter==='risk'?'active':''?>"           href="<?=air_h(air_url(['filter'=>'risk']))?>">
    <span>Risk Uyarısı</span><strong class="red"><?=$countRisk?></strong><em>şüpheli/yasaklı</em></a>
  <a class="op-stat <?=$filter==='custom'?'active':''?>"         href="<?=air_h(air_url(['filter'=>'custom']))?>">
    <span>CUSTOM</span><strong class="yl"><?=$countCustom?></strong><em>kontrol</em></a>
  <a class="op-stat <?=$filter==='multi_qty'?'active':''?>"      href="<?=air_h(air_url(['filter'=>'multi_qty']))?>">
    <span>Çoklu Adet</span><strong class="yl"><?=$countQtyMulti?></strong><em>parçalanacak</em></a>
  <a class="op-stat <?=$filter==='same_customer'?'active':''?>"  href="<?=air_h(air_url(['filter'=>'same_customer']))?>">
    <span>Aynı Müşteri</span><strong class="yl"><?=$countSameCustomer?></strong><em>birden fazla order</em></a>
  <a class="op-stat <?=$filter==='express'?'active':''?>"        href="<?=air_h(air_url(['filter'=>'express']))?>">
    <span>Express</span><strong class="red"><?=$countExpress?></strong><em>öncelikli</em></a>
</div>

<!-- ── Filter bar ── -->
<div class="card mb16">
  <div class="card-body op-filterbar">
    <form method="get" class="op-filter-form">
      <div>
        <label class="form-label">Mağaza</label>
        <select name="store_id" class="form-control">
          <option value="0">Tümü</option>
          <?php foreach ($stores as $st): ?>
            <option value="<?=(int)$st['id']?>" <?=$filterStore===(int)$st['id']?'selected':''?>>
              <?=air_h($st['store_code'])?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>
      <input type="hidden" name="filter" value="<?=air_h($filter)?>">
      <div class="op-search">
        <label class="form-label">Ara</label>
        <input name="q" value="<?=air_h($q)?>" class="form-control" placeholder="SKU, müşteri, order, transaction…">
      </div>
      <button class="btn btn-primary">Filtrele</button>
      <a class="btn btn-secondary" href="admin_import_review.php">Temizle</a>
    </form>
  </div>
</div>

<?php if (!$groups): ?>
  <div class="card">
    <div class="empty">
      <div class="empty-ico">✓</div>
      <div class="empty-title">Onay bekleyen sipariş yok</div>
      <div class="empty-text">Tüm mağaza onayları işlendi.</div>
    </div>
  </div>
<?php else: ?>

<!-- ── Main bulk form (wraps all cards + bulk action bar) ── -->
<form method="post" action="admin_import_review.php" id="adminForm">
  <?= csrf_field() ?>

  <!-- ── Bulk sticky bar ── -->
  <div class="card mb16 sticky-actions">
    <div class="card-body op-actions">
      <label class="fc gap8" style="cursor:pointer">
        <input type="checkbox" id="selectAll">
        <span style="font-size:12px;font-weight:600;color:var(--text-secondary)">Tümünü Seç</span>
      </label>
      <span id="selectedCount" class="c-mt" style="font-size:13px">0 seçili</span>
      <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap">
        <button type="submit" name="action" value="approve" class="btn btn-success">✓ Seçilenleri Üretim Kuyruğuna Al</button>
        <button type="submit" name="action" value="reject"  class="btn btn-danger">✕ Reddet</button>
      </div>
      <div style="width:100%;display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:10px">
        <div>
          <label class="form-label">Toplu Admin Notu</label>
          <textarea name="admin_note" class="form-control" rows="2" placeholder="Onay veya red için genel not…"></textarea>
        </div>
        <div>
          <label class="form-label">Red Sebebi <span class="c-red">*zorunlu</span></label>
          <textarea name="reject_reason" class="form-control" rows="2" placeholder="Reddedilen satırlar için açıklama…"></textarea>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Order cards ── -->
  <?php foreach ($groups as $g):
    $hasBlocked    = (bool)array_filter($g['rows'], fn($r) => $r['_is_blocked']);
    $hasWarn       = !$hasBlocked && !empty($g['warnings']);
    $cardClass     = $hasBlocked ? 'danger' : ($hasWarn ? 'warn' : '');
    $shipUrgency   = air_ship_urgency($g['ship_by']);
    $groupRowIds   = array_column($g['rows'], 'id');
  ?>
  <div class="op-order-card <?=air_h($cardClass)?>" id="acard_<?=air_h($g['key'])?>">

    <!-- ── Card header ── -->
    <div class="op-order-head">
      <label class="op-group-check">
        <input type="checkbox" class="groupCheck"> <span>Grup</span>
      </label>
      <div class="fc gap8">
        <span class="op-order-id">#<?=air_h($g['order_id'])?></span>
        <span class="op-order-customer"><?=air_h($g['customer'])?></span>
      </div>
      <div class="op-order-meta">
        <span class="op-badge op-badge-store"><?=air_h($g['store_code'])?></span>
        <span class="op-badge <?=air_h(air_ship_badge($g['shipping_type']))?>"><?=air_h(air_ship_label($g['shipping_type']))?></span>
        <?php if ($g['ship_by'] && $g['ship_by']!=='-'): ?>
          <span class="op-shipby <?=air_h($shipUrgency)?>">Ship by <?=air_h(air_date($g['ship_by']))?><?=$shipUrgency==='overdue'?' ⚠':''?></span>
        <?php endif; ?>
        <span class="c-mt" style="font-size:12px"><?=air_h($g['city'])?></span>
        <span class="badge bg-mt" style="font-size:11px"><?=count($g['rows'])?> ürün / <?=(int)$g['unit_count']?> poşet</span>
        <?php if ($g['store_user'] && $g['store_user']!=='-'): ?>
          <span class="c-mt" style="font-size:11px">📬 <?=air_h($g['store_user'])?></span>
        <?php endif; ?>
      </div>
    </div>

    <!-- ── Warning strip ── -->
    <?php if ($g['warnings']): ?>
      <div class="op-warning-strip">
        <?php foreach ($g['warnings'] as [$wt,$wc]): ?>
          <span class="op-warn-pill <?=air_h($wc)?>"><?=air_h($wt)?></span>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <!-- ── Address ── -->
    <details class="op-address">
      <summary>▸ Ship to / Adres</summary>
      <div class="op-address-detail" style="white-space:pre-line"><?=air_h($g['address']?:'-')?></div>
    </details>

    <!-- ── Item rows ── -->
    <div class="op-item-list">
      <?php foreach ($g['rows'] as $row):
        $qty       = max(1,(int)($row['quantity']??1));
        $imageUrl  = csv_mod_image_url($row['product_img']??$row['product_image_path']??'');
        $isMissing = $row['_is_missing'];
        $netFmt    = csv_mod_format_money($row['_net'], $row['currency']??'USD');
      ?>
      <div class="op-item" id="arow<?=(int)$row['id']?>">
        <label class="op-item-check">
          <input type="checkbox" name="row_ids[]" value="<?=(int)$row['id']?>"
                 class="rowCheck" data-i="<?=(int)$row['id']?>">
        </label>
        <div class="op-thumb">
          <?php if ($imageUrl): ?><img src="<?=air_h($imageUrl)?>" alt="" loading="lazy">
          <?php else: ?><span style="font-size:20px;color:var(--border-strong)">◻</span><?php endif; ?>
        </div>
        <div class="op-item-body">
          <div class="op-name-row">
            <span class="op-sku"><?=air_h($row['sku']?:'—')?></span>
            <span class="op-pname <?=$row['_name_source']==='etsy'?'fallback':''?>"><?=air_h($row['_display_name'])?></span>
            <?php if ($isMissing): ?><span class="op-missing-tag">ürün kartı yok</span><?php endif; ?>
          </div>
          <div class="op-chips">
            <?php if ($row['parsed_karat']): ?><span class="op-chip karat"><?=air_h($row['parsed_karat'])?></span><?php endif; ?>
            <?php if ($row['parsed_color']): ?><span class="op-chip"><?=air_h($row['parsed_color'])?></span><?php endif; ?>
            <?php if ($row['parsed_size']): ?><span class="op-chip size">⌀ <?=air_h($row['parsed_size'])?></span><?php endif; ?>
          </div>
          <?php if (!empty($row['personalization'])): ?>
            <div class="op-personal"><span class="op-personal-label">Kişisel:</span><?=nl2br(air_h($row['personalization']))?></div>
          <?php endif; ?>
          <?php if (!empty($row['store_note'])): ?>
            <div class="op-store-note">📝 Mağaza notu: <?=nl2br(air_h($row['store_note']))?></div>
          <?php endif; ?>
          <?php if ($row['_is_blocked']): ?>
            <div class="op-row-flag danger">⛔ YASAKLI MÜŞTERİ</div>
          <?php elseif ($row['_is_suspicious']||$row['_is_risk']): ?>
            <div class="op-row-flag warn">⚠ Şüpheli müşteri uyarısı</div>
          <?php endif; ?>
          <?php if (!empty($row['flag_admin_detail'])): ?>
            <details style="margin-top:5px">
              <summary style="font-size:11px;color:var(--red);cursor:pointer">⛔ Risk detayı (sadece admin)</summary>
              <div class="op-admin-risk" style="margin-top:4px"><?=air_h($row['flag_admin_detail'])?></div>
            </details>
          <?php endif; ?>
          <?php if ($row['_is_custom']): ?>
            <div class="op-row-flag info">✦ CUSTOM / upgrade — kontrol et</div>
          <?php endif; ?>
          <?php if ($qty > 1): ?>
            <div class="op-row-flag warn">◈ Qty <?=$qty?> → <?=$qty?> üretim satırı / sıra no oluşacak</div>
          <?php endif; ?>
        </div>
        <div class="op-price-block">
          <span class="op-net-amount"><?=air_h($netFmt)?></span>
          <?php if ($qty > 1): ?><span class="op-qty-pill">× <?=$qty?></span><?php endif; ?>
          <span class="op-tid"><?=air_h($row['transaction_id'])?></span>
        </div>
      </div>
      <?php endforeach; ?>
    </div>

    <!-- ── Per-group quick approve / reject / hold ── -->
    <div class="op-admin-actions">
      <!-- Quick per-group approve (separate mini-form to avoid nested forms) -->
      <button type="button" class="btn btn-success btn-sm"
              onclick="quickGroupApprove('<?=air_h($g['key'])?>', <?=air_h(json_encode($groupRowIds))?>)">
        ✓ Grubu Üretim Al
      </button>
      <button type="button" class="btn btn-warn btn-sm"
              onclick="toggleAdminNote(this)">
        📝 Grup Notu / Admin Notu
      </button>
      <span style="margin-left:auto;font-size:11px;color:var(--text-muted)">
        veya yukarıda toplu seç
      </span>
    </div>

    <!-- ── Per-group admin note (shown when "Grup Notu" is clicked) ── -->
    <div class="op-admin-note-area">
      <label>Admin Notu (bu grup için)</label>
      <textarea class="group-admin-note"
                data-group-key="<?=air_h($g['key'])?>"
                placeholder="Bu grupla ilgili admin notu…" rows="2"></textarea>
    </div>

  </div>
  <?php endforeach; ?>

</form>

<!-- ── Quick per-group approve mini form (outside main form to avoid nesting) ── -->
<form method="post" action="admin_import_review.php" id="quickGroupForm" style="display:none">
  <?= csrf_field() ?>
  <input type="hidden" name="action" value="approve">
  <input type="hidden" name="group_approve_key" id="quickGroupKey">
  <input type="hidden" name="admin_note"        id="quickGroupNote">
  <!-- Row IDs populated by JS -->
  <div id="quickGroupRowIds"></div>
</form>

<?php endif; ?>

<script>
/* ── Bulk selection ── */
const selAll = document.getElementById('selectAll');
const countEl = document.getElementById('selectedCount');

function getRowChecks()  { return Array.from(document.querySelectorAll('.rowCheck')); }
function getGroupChecks(){ return Array.from(document.querySelectorAll('.groupCheck')); }

function updateSelection() {
  const checked = getRowChecks().filter(cb => cb.checked);
  const n = checked.length;
  countEl.textContent = n + ' seçili';
  getRowChecks().forEach(cb => {
    document.getElementById('arow' + cb.dataset.i)?.classList.toggle('sel', cb.checked);
  });
}

selAll?.addEventListener('change', () => {
  getRowChecks().forEach(cb => cb.checked = selAll.checked);
  getGroupChecks().forEach(cb => cb.checked = selAll.checked);
  updateSelection();
});

document.addEventListener('change', e => {
  if (e.target.classList.contains('groupCheck')) {
    const card = e.target.closest('.op-order-card');
    card?.querySelectorAll('.rowCheck').forEach(cb => cb.checked = e.target.checked);
    updateSelection();
  }
  if (e.target.classList.contains('rowCheck')) updateSelection();
});

/* ── Admin note toggle ── */
function toggleAdminNote(btn) {
  const area = btn.closest('.op-admin-actions').nextElementSibling;
  area.classList.toggle('open');
}

/* ── Quick per-group approve ── */
function quickGroupApprove(groupKey, rowIds) {
  const noteEl = document.querySelector('[data-group-key="' + groupKey + '"]');
  const note = noteEl ? noteEl.value.trim() : '';

  document.getElementById('quickGroupKey').value  = groupKey;
  document.getElementById('quickGroupNote').value = note;

  const container = document.getElementById('quickGroupRowIds');
  container.innerHTML = '';
  rowIds.forEach(id => {
    const inp = document.createElement('input');
    inp.type = 'hidden';
    inp.name = 'group_row_ids[]';
    inp.value = id;
    container.appendChild(inp);
  });

  if (confirm('Bu gruptaki ' + rowIds.length + ' satır üretim kuyruğuna alınsın mı? (Sıra numarası verilecek)')) {
    document.getElementById('quickGroupForm').submit();
  }
}

updateSelection();
</script>

<?php include __DIR__ . '/includes/layout_end.php'; ?>
