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

/* ── Helpers ──────────────────────────────────────────── */
function cp_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function cp_url(array $extra = []): string {
    $q = array_merge($_GET, $extra);
    foreach ($q as $k => $v) { if ($v === null || $v === '' || $v === 'all') unset($q[$k]); }
    return 'csv_preview.php' . ($q ? ('?' . http_build_query($q)) : '');
}
function cp_date($v): string {
    $v = trim((string)$v);
    return ($v === '' || $v === '0000-00-00' || $v === '0000-00-00 00:00:00') ? '-' : substr($v, 0, 10);
}
/** Returns urgency class based on days until ship_by */
function cp_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'); // negative = overdue
        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 cp_ship_label(string $type): string {
    return match($type) {
        'express'       => '⚡ EXPRESS',
        'international' => '🌍 INT\'L',
        default         => 'EKO',
    };
}
function cp_ship_badge(string $type): string {
    return match($type) {
        'express'       => 'op-badge-express',
        'international' => 'op-badge-intl',
        default         => 'op-badge-muted',
    };
}
function cp_truncate(string $s, int $max = 55): string {
    return mb_strlen($s, 'UTF-8') > $max ? mb_substr($s, 0, $max, 'UTF-8') . '…' : $s;
}

/* ── Auth / Log lookup ────────────────────────────────── */
$user        = current_user();
$role        = $user['role'];
$userStoreId = $user['store_id'] ?? null;
$logId       = (int)($_GET['log_id'] ?? 0);

if ($logId <= 0) {
    if ($role === 'store_user') {
        $stmt = db()->prepare("
            SELECT cil.id FROM csv_import_logs cil
            JOIN csv_import_rows r ON r.last_seen_import_log_id = cil.id AND r.row_status = 'store_pending'
            WHERE cil.store_id = :sid GROUP BY cil.id ORDER BY cil.created_at DESC LIMIT 1
        ");
        $stmt->execute(['sid' => $userStoreId]);
    } else {
        $stmt = db()->query("
            SELECT cil.id FROM csv_import_logs cil
            JOIN csv_import_rows r ON r.last_seen_import_log_id = cil.id AND r.row_status = 'store_pending'
            GROUP BY cil.id ORDER BY cil.created_at DESC LIMIT 1
        ");
    }
    $logId = (int)$stmt->fetchColumn();
}

if ($logId <= 0) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Devam eden CSV önizlemesi bulunamadı. Dosyayı tekrar yükleyin.'];
    redirect('csv_upload.php');
}

$stmt = db()->prepare("
    SELECT cil.*, s.store_code, s.store_name
    FROM csv_import_logs cil
    JOIN stores s ON s.id = cil.store_id
    WHERE cil.id = :id LIMIT 1
");
$stmt->execute(['id' => $logId]);
$log = $stmt->fetch();

if (!$log) {
    $_SESSION['flash'] = ['type' => 'error', 'msg' => 'CSV kaydı bulunamadı.'];
    redirect('csv_upload.php');
}
if ($role === 'store_user' && (int)$log['store_id'] !== (int)$userStoreId) {
    http_response_code(403); exit('Yetki hatası.');
}

/* ── Fetch rows ───────────────────────────────────────── */
[$imageSelect, $imageJoin] = csv_mod_product_image_sql('p', 'product_img');
$stmt = db()->prepare("
    SELECT
        r.*,
        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
    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.last_seen_import_log_id = :lid
      AND r.row_status = 'store_pending'
    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->execute(['lid' => $logId]);
$allRows = $stmt->fetchAll();

/* ── Customer multi-order map ─────────────────────────── */
$customerOrders = [];
foreach ($allRows 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;
}

/* ── Decorate rows ────────────────────────────────────── */
$decorated = [];
foreach ($allRows 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;
    // Best display name: short_name > product_name > truncated Etsy title
    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'] = cp_truncate($r['listing_title'] ?? '-', 55);
        $r['_name_source']  = 'etsy';
    }
    // Net amount
    $r['_net'] = $r['net_item_total'] ?? csv_mod_net_item_total($r['price'] ?? null, $r['discount_amount'] ?? null);
    $decorated[] = $r;
}

/* ── Group by order ───────────────────────────────────── */
$groups = [];
foreach ($decorated as $r) {
    $key = $r['_og'] ?: ('row:' . $r['id']);
    if (!isset($groups[$key])) {
        $shipType = $r['shipping_type'] ?: 'standard';
        $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'   => $log['store_code'],
            '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' => $shipType,
            'rows'         => [],
            'warnings'     => [],
            'unit_count'   => 0,
        ];
    }
    $groups[$key]['rows'][] = $r;
}

/* ── Build per-group warnings + unit count ─────────────── */
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);

/* ── Filter + search + pagination ─────────────────────── */
$filter  = $_GET['filter']   ?? 'all';
$q       = trim((string)($_GET['q'] ?? ''));
$perPage = (int)($_GET['per_page'] ?? 50);
$perPage = in_array($perPage, [25, 50, 100], true) ? $perPage : 50;
$page    = max(1, (int)($_GET['page'] ?? 1));

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

$totalGroups = count($filtered);
$totalPages  = max(1, (int)ceil($totalGroups / $perPage));
$page        = min($page, $totalPages);
$groupsPage  = array_slice($filtered, ($page - 1) * $perPage, $perPage);

/* ── Stats ─────────────────────────────────────────────── */
$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']));
$skippedHidden    = (int)($log['duplicate_rows'] ?? 0);

$page_title  = 'CSV Önizleme';
$active_menu = 'csv';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>CSV Önizleme</h1>
    <p>
      <span class="badge bg-gld"><?= cp_h($log['store_code']) ?></span>
      <?= cp_h($log['original_filename'] ?: $log['filename']) ?>
      <span class="c-mt">#<?= (int)$log['id'] ?></span>
    </p>
  </div>
  <a href="csv_upload.php" class="btn btn-secondary">← Geri</a>
</div>

<?php if ($countTotal === 0): ?>
  <div class="card">
    <div class="empty">
      <div class="empty-ico">✓</div>
      <div class="empty-title">Bu CSV'de bekleyen satır yok</div>
      <div class="empty-text">Tüm satırlar onaylandı veya zaten sistemde.</div>
      <a href="csv_upload.php" class="btn btn-primary" style="margin-top:14px">Yeni CSV Yükle</a>
    </div>
  </div>
<?php else: ?>

<!-- ── Stat filter pills ── -->
<div class="op-stat-grid">
  <a class="op-stat <?= $filter==='all'?'active':'' ?>"           href="<?= cp_h(cp_url(['filter'=>'all','page'=>1])) ?>">
    <span>Toplam Satır</span><strong><?= $countTotal ?></strong><em>CSV satırı</em>
  </a>
  <a class="op-stat <?= $filter==='missing'?'active':'' ?>"       href="<?= cp_h(cp_url(['filter'=>'missing','page'=>1])) ?>">
    <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="<?= cp_h(cp_url(['filter'=>'risk','page'=>1])) ?>">
    <span>Risk Uyarısı</span><strong class="red"><?= $countRisk ?></strong><em>şüpheli/yasaklı</em>
  </a>
  <a class="op-stat <?= $filter==='custom'?'active':'' ?>"         href="<?= cp_h(cp_url(['filter'=>'custom','page'=>1])) ?>">
    <span>CUSTOM / Upgrade</span><strong class="yl"><?= $countCustom ?></strong><em>kontrol gerekli</em>
  </a>
  <a class="op-stat <?= $filter==='multi_qty'?'active':'' ?>"      href="<?= cp_h(cp_url(['filter'=>'multi_qty','page'=>1])) ?>">
    <span>Çoklu Adet</span><strong class="yl"><?= $countQtyMulti ?></strong><em>üretimde parçalanacak</em>
  </a>
  <a class="op-stat <?= $filter==='same_customer'?'active':'' ?>"  href="<?= cp_h(cp_url(['filter'=>'same_customer','page'=>1])) ?>">
    <span>Aynı Müşteri</span><strong class="yl"><?= $countSameCustomer ?></strong><em>birden fazla sipariş</em>
  </a>
  <a class="op-stat <?= $filter==='express'?'active':'' ?>"        href="<?= cp_h(cp_url(['filter'=>'express','page'=>1])) ?>">
    <span>Express</span><strong class="red"><?= $countExpress ?></strong><em>öncelikli gönderim</em>
  </a>
  <div class="op-stat">
    <span>Gizlenen</span><strong><?= $skippedHidden ?></strong><em>duplicate / işlemde</em>
  </div>
</div>

<!-- ── Filter + search bar ── -->
<div class="card mb16">
  <div class="card-body op-filterbar">
    <form method="get" class="op-filter-form">
      <input type="hidden" name="log_id"  value="<?= (int)$logId ?>">
      <input type="hidden" name="filter"  value="<?= cp_h($filter) ?>">
      <div class="op-search">
        <label class="form-label">Ara (SKU, müşteri, order, personalization…)</label>
        <input name="q" value="<?= cp_h($q) ?>" class="form-control" placeholder="Arama…">
      </div>
      <div>
        <label class="form-label">Sayfa başı</label>
        <select name="per_page" class="form-control">
          <option value="25"  <?= $perPage===25 ?'selected':'' ?>>25 grup</option>
          <option value="50"  <?= $perPage===50 ?'selected':'' ?>>50 grup</option>
          <option value="100" <?= $perPage===100?'selected':'' ?>>100 grup</option>
        </select>
      </div>
      <button class="btn btn-primary">Filtrele</button>
      <a class="btn btn-secondary" href="csv_preview.php?log_id=<?= (int)$logId ?>">Temizle</a>
    </form>
  </div>
</div>

<!-- ── Main form ── -->
<form method="post" action="csv_confirm.php" id="previewForm">
  <?= csrf_field() ?>
  <input type="hidden" name="log_id" value="<?= (int)$logId ?>">

  <!-- ── Sticky action 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)">Bu sayfadakileri seç</span>
      </label>
      <span class="c-mt" id="selectedCount" style="font-size:13px">0 seçili</span>
      <span class="c-mt" style="font-size:12px">
        Gösterilen: <strong><?= (int)$totalGroups ?></strong> grup &nbsp;·&nbsp;
        Sayfa <strong><?= (int)$page ?></strong> / <strong><?= (int)$totalPages ?></strong>
      </span>
      <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap">
        <button type="submit" name="action" value="approve" class="btn btn-success" id="approveBtn" disabled>
          ✓ Seçilenleri Admin Onayına Gönder
        </button>
        <button type="submit" name="action" value="skip" class="btn btn-secondary" id="skipBtn" disabled>
          Şimdilik Beklet
        </button>
      </div>
    </div>
  </div>

  <!-- ── Order cards ── -->
  <?php foreach ($groupsPage as $g):
    $hasBlockedWarn  = (bool)array_filter($g['rows'], fn($r) => $r['_is_blocked']);
    $hasOtherWarning = !$hasBlockedWarn && !empty($g['warnings']);
    $cardClass       = $hasBlockedWarn ? 'danger' : ($hasOtherWarning ? 'warn' : '');
    $shipUrgency     = cp_ship_urgency($g['ship_by']);
    $firstRowIds     = array_column($g['rows'], 'id');
    $firstRowId      = $firstRowIds[0];
  ?>
  <div class="op-order-card <?= cp_h($cardClass) ?>" id="card_<?= cp_h($g['key']) ?>">

    <!-- ── Card header ── -->
    <div class="op-order-head">
      <label class="op-group-check" title="Gruptaki tüm kalemleri seç">
        <input type="checkbox" class="groupCheck"> <span>Grup</span>
      </label>

      <div class="fc gap8">
        <span class="op-order-id">#<?= cp_h($g['order_id']) ?></span>
        <span class="op-order-customer"><?= cp_h($g['customer']) ?></span>
      </div>

      <div class="op-order-meta">
        <span class="op-badge op-badge-store"><?= cp_h($g['store_code']) ?></span>
        <span class="op-badge <?= cp_h(cp_ship_badge($g['shipping_type'])) ?>">
          <?= cp_h(cp_ship_label($g['shipping_type'])) ?>
        </span>
        <?php if ($g['ship_by'] && $g['ship_by'] !== '-'): ?>
          <span class="op-shipby <?= cp_h($shipUrgency) ?>">
            Ship by <?= cp_h(cp_date($g['ship_by'])) ?>
            <?php if ($shipUrgency === 'overdue'): ?> ⚠<?php endif; ?>
          </span>
        <?php endif; ?>
        <span class="c-mt" style="font-size:12px"><?= cp_h($g['city']) ?></span>
        <span class="badge bg-mt" style="font-size:11px">
          <?= count($g['rows']) ?> ürün &nbsp;/&nbsp; <?= (int)$g['unit_count'] ?> poşet
        </span>
      </div>
    </div>

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

    <!-- ── Address (collapsed by default) ── -->
    <details class="op-address">
      <summary>▸ Ship to / Adres</summary>
      <div class="op-address-detail" style="white-space:pre-line"><?= cp_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'];
        $nameSource = $row['_name_source'];
        $netAmt     = $row['_net'];
        $netFmt     = csv_mod_format_money($netAmt, $row['currency'] ?? 'USD');
      ?>
      <div class="op-item" id="row<?= (int)$row['id'] ?>">

        <!-- Checkbox -->
        <label class="op-item-check">
          <input type="checkbox" name="selected_rows[]" value="<?= (int)$row['id'] ?>"
                 class="rowCheck" data-i="<?= (int)$row['id'] ?>"
                 data-order="<?= cp_h($g['key']) ?>">
        </label>

        <!-- Thumbnail -->
        <div class="op-thumb">
          <?php if ($imageUrl): ?>
            <img src="<?= cp_h($imageUrl) ?>" alt="" loading="lazy">
          <?php else: ?>
            <span style="font-size:20px;color:var(--border-strong)">◻</span>
          <?php endif; ?>
        </div>

        <!-- Item body -->
        <div class="op-item-body">
          <div class="op-name-row">
            <span class="op-sku"><?= cp_h($row['sku'] ?: '—') ?></span>
            <span class="op-pname <?= $nameSource === 'etsy' ? 'fallback' : '' ?>">
              <?= cp_h($row['_display_name']) ?>
            </span>
            <?php if ($isMissing): ?>
              <span class="op-missing-tag">ürün kartı yok</span>
            <?php endif; ?>
          </div>

          <!-- Attribute chips -->
          <div class="op-chips">
            <?php if ($row['parsed_karat']): ?>
              <span class="op-chip karat"><?= cp_h($row['parsed_karat']) ?></span>
            <?php endif; ?>
            <?php if ($row['parsed_color']): ?>
              <span class="op-chip"><?= cp_h($row['parsed_color']) ?></span>
            <?php endif; ?>
            <?php if ($row['parsed_size']): ?>
              <span class="op-chip size">⌀ <?= cp_h($row['parsed_size']) ?></span>
            <?php endif; ?>
            <?php if (!empty($row['parsed_chain_length']) && $row['parsed_chain_length'] !== $row['parsed_size']): ?>
              <span class="op-chip">⊢ <?= cp_h($row['parsed_chain_length']) ?></span>
            <?php endif; ?>
          </div>

          <!-- Personalization -->
          <?php if (!empty($row['personalization'])): ?>
            <div class="op-personal">
              <span class="op-personal-label">Kişisel:</span><?= nl2br(cp_h($row['personalization'])) ?>
            </div>
          <?php endif; ?>

          <!-- Row-level flags -->
          <?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 ($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 ?> — üretimde <?= $qty ?> ayrı poşete parçalanacak</div>
          <?php endif; ?>
        </div>

        <!-- Price block -->
        <div class="op-price-block">
          <span class="op-net-amount"><?= cp_h($netFmt) ?></span>
          <?php if ($qty > 1): ?>
            <span class="op-qty-pill">× <?= $qty ?></span>
          <?php endif; ?>
          <span class="op-tid"><?= cp_h($row['transaction_id']) ?></span>
        </div>

      </div>
      <?php endforeach; ?>
    </div>

    <!-- ── Per-order note (collapsed, one textarea shared for all rows) ── -->
    <div class="op-note-section">
      <?php $existingNote = trim((string)($g['rows'][0]['store_note'] ?? '')); ?>
      <button type="button" class="op-note-toggle <?= $existingNote ? 'has-note' : '' ?>"
              onclick="toggleNote(this)">
        <?= $existingNote ? '📝 Mağaza Notu var — düzenle' : '+ Mağaza Notu ekle' ?>
      </button>
      <div class="op-note-body <?= $existingNote ? 'open' : '' ?>">
        <!-- Visible textarea (first row id as key) -->
        <textarea class="op-order-note-ta"
                  data-row-ids="<?= cp_h(implode(',', array_column($g['rows'], 'id'))) ?>"
                  placeholder="Bu siparişe ait not (tüm kalemler için geçerli olacak)…"
                  rows="2"><?= cp_h($existingNote) ?></textarea>
        <!-- Hidden inputs for all rows in this order (populated by JS on submit) -->
        <?php foreach ($g['rows'] as $r): ?>
          <input type="hidden" name="store_notes[<?= (int)$r['id'] ?>]"
                 class="note-hidden-<?= (int)$r['id'] ?>" value="<?= cp_h($existingNote) ?>">
        <?php endforeach; ?>
      </div>
    </div>

  </div>
  <?php endforeach; ?>

</form>

<!-- ── Pagination ── -->
<div class="op-pagination">
  <?php if ($page > 1): ?>
    <a class="btn btn-secondary" href="<?= cp_h(cp_url(['page'=>$page-1])) ?>">← Önceki</a>
  <?php endif; ?>
  <span>Sayfa <?= (int)$page ?> / <?= (int)$totalPages ?> &nbsp;·&nbsp; <?= (int)$totalGroups ?> grup</span>
  <?php if ($page < $totalPages): ?>
    <a class="btn btn-secondary" href="<?= cp_h(cp_url(['page'=>$page+1])) ?>">Sonraki →</a>
  <?php endif; ?>
</div>

<?php endif; ?>

<script>
/* ── Selection management ── */
const rowChecks   = () => Array.from(document.querySelectorAll('.rowCheck'));
const groupChecks = () => Array.from(document.querySelectorAll('.groupCheck'));
const selectAll   = document.getElementById('selectAll');
const countEl     = document.getElementById('selectedCount');
const approveBtn  = document.getElementById('approveBtn');
const skipBtn     = document.getElementById('skipBtn');

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

selectAll?.addEventListener('change', () => {
  rowChecks().forEach(cb => cb.checked = selectAll.checked);
  groupChecks().forEach(cb => cb.checked = selectAll.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();
});

/* ── Note toggle ── */
function toggleNote(btn) {
  const body = btn.nextElementSibling;
  body.classList.toggle('open');
}

/* ── On submit: propagate order note to all row hidden inputs ── */
document.getElementById('previewForm')?.addEventListener('submit', () => {
  document.querySelectorAll('.op-order-note-ta').forEach(ta => {
    const val = ta.value;
    ta.dataset.rowIds.split(',').forEach(id => {
      const h = document.querySelector('.note-hidden-' + id.trim());
      if (h) h.value = val;
    });
  });
});

updateSelection();
</script>

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