<?php
// production.php — Patch V6: Compact table-hybrid production list
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/csv_module_common.php';
require_login();
require_role(['admin', 'production_manager', 'workshop_staff']);

$user   = current_user();
$userId = (int)($user['id'] ?? 0);
$role   = (string)($user['role'] ?? '');
$pdo    = db();

/* ── Safe escape ── */
function prod_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function prod_date($v): string {
    $v = trim((string)$v);
    return ($v === '' || str_starts_with($v, '0000')) ? '-' : substr($v, 0, 10);
}

/* ── Business day calculation ── */
function prod_biz_days(string $from, ?string $to = null): int {
    if (!$from || str_starts_with($from, '0000')) return -1;
    try {
        $start = new DateTime($from); $start->setTime(0, 0, 0);
        $end   = $to ? new DateTime($to) : new DateTime('today');
        $end->setTime(0, 0, 0);
        if ($start >= $end) return 0;
        $days = 0; $cur = clone $start;
        while ($cur < $end) { $cur->modify('+1 day'); if ((int)$cur->format('N') <= 5) $days++; }
        return $days;
    } catch (Throwable $e) { return -1; }
}

/* ── Display name: short_name > product_name > truncated title ── */
function prod_display_name(array $row, int $max = 48): array {
    if (!empty($row['short_name']))   return [$row['short_name'],   'card'];
    if (!empty($row['product_name'])) return [$row['product_name'], 'card'];
    $t = trim((string)($row['listing_title'] ?? ''));
    if ($t === '') return ['-', 'none'];
    return [mb_strlen($t, 'UTF-8') > $max ? mb_substr($t, 0, $max, 'UTF-8').'…' : $t, 'etsy'];
}

/* ── Days display HTML ── */
function prod_days_html(array $row): string {
    if ((int)($row['is_cancelled'] ?? 0) === 1)
        return '<span class="prd-day-chip cancel">İPTAL</span>';

    $isFinal = (int)($row['is_final'] ?? 0) === 1;
    if ($isFinal) {
        $shipped = trim((string)($row['shipped_date'] ?? ''));
        if ($shipped && !str_starts_with($shipped, '0000')) {
            $taken = prod_biz_days((string)($row['created_at'] ?? ''), $shipped);
            if ($taken < 0) return '<span class="prd-day-chip muted">✓</span>';
            if ($taken < 5) return '<span class="prd-day-chip green">✓ '.$taken.'g</span>';
            if ($taken === 5) return '<span class="prd-day-chip yellow">✓ 5g</span>';
            return '<span class="prd-day-chip red">+'.(($taken-5)).'g</span>';
        }
        return '<span class="prd-day-chip green">✓</span>';
    }

    $elapsed = prod_biz_days((string)($row['created_at'] ?? ''));
    if ($elapsed < 0) return '<span class="prd-day-chip muted">-</span>';
    $left = 5 - $elapsed;
    if ($left > 2)  return '<span class="prd-day-chip green">'.prod_h($left).' gün</span>';
    if ($left > 0)  return '<span class="prd-day-chip yellow">'.prod_h($left).' gün</span>';
    if ($left === 0) return '<span class="prd-day-chip yellow">Son gün</span>';
    return '<span class="prd-day-chip red">'.prod_h(abs($left)).'g geç</span>';
}

/* ── Shipping badge ── */
function prod_ship_badge(string $type): string {
    return match ($type) {
        'express'       => '<span class="prd-ship-badge prd-ship-express">⚡ EXPRESS</span>',
        'international' => '<span class="prd-ship-badge prd-ship-intl">🌍 INT\'L</span>',
        default         => '<span class="prd-ship-badge prd-ship-eko">EKO</span>',
    };
}

/* ── Check if tracking audit columns exist (graceful fallback) ── */
$hasTrackAudit = csv_mod_db_column_exists('order_items', 'tracking_entered_by');

/* ══════════════════════════════════════════════════════════════
   POST HANDLER
══════════════════════════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = $_POST['action'] ?? '';

    /* ── Bulk status update ── */
    if ($action === 'bulk_status') {
        $ids        = array_values(array_unique(array_map('intval', $_POST['order_ids'] ?? [])));
        $toStatusId = (int)($_POST['to_status_id'] ?? 0);
        $note       = trim((string)($_POST['production_note'] ?? ''));

        if (!$ids || $toStatusId <= 0) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Sipariş ve yeni durum seçmelisin.'];
            redirect('production.php');
        }
        $stSel = $pdo->prepare("SELECT * FROM production_statuses WHERE id = ? AND is_active = 1 LIMIT 1");
        $stSel->execute([$toStatusId]);
        $toStatus = $stSel->fetch();
        if (!$toStatus) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Seçilen üretim durumu bulunamadı.'];
            redirect('production.php');
        }
        $pdo->beginTransaction();
        try {
            $sel = $pdo->prepare("SELECT id, current_status_id FROM order_items WHERE id = ? FOR UPDATE");
            $upd = $pdo->prepare("UPDATE order_items SET current_status_id = ?, updated_at = NOW() WHERE id = ?");
            $log = $pdo->prepare("INSERT INTO production_logs (order_item_id, from_status_id, to_status_id, changed_by, changed_at, note) VALUES (?,?,?,?,NOW(),?)");
            $done = 0;
            foreach ($ids as $id) {
                $sel->execute([$id]); $row = $sel->fetch();
                if (!$row) continue;
                $from = (int)$row['current_status_id'];
                if ($from === $toStatusId) continue;
                $upd->execute([$toStatusId, $id]);
                $log->execute([$id, $from ?: null, $toStatusId, $userId ?: null,
                    $note ?: ('Durum güncellendi: '.$toStatus['status_name'])]);
                $done++;
            }
            $pdo->commit();
            $_SESSION['flash'] = ['type' => 'success', 'msg' => $done.' siparişin durumu güncellendi.'];
        } catch (Throwable $e) {
            $pdo->rollBack();
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Hata: '.prod_h($e->getMessage())];
        }
        $qs = $_GET ? ('?'.http_build_query($_GET)) : '';
        redirect('production.php'.$qs);
    }

    /* ── Tracking update (order-level: all rows with same etsy_order_id) ── */
    if ($action === 'tracking_update') {
        $etsyOrderId = trim((string)($_POST['etsy_order_id'] ?? ''));
        $trackingNo  = trim((string)($_POST['tracking_number'] ?? ''));
        $carrier     = trim((string)($_POST['tracking_carrier'] ?? ''));
        $trackNote   = trim((string)($_POST['tracking_note'] ?? ''));
        $shippedDate = trim((string)($_POST['shipped_date'] ?? ''));

        if (!$etsyOrderId || !$trackingNo) {
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Order ID ve tracking numarası zorunlu.'];
            $qs = $_GET ? ('?'.http_build_query($_GET)) : '';
            redirect('production.php'.$qs);
        }
        $shippedDate = $shippedDate ?: date('Y-m-d');

        $pdo->beginTransaction();
        try {
            // Fetch all production rows for this etsy_order_id (only rows with production_no)
            $fetcher = $pdo->prepare("
                SELECT id, current_status_id
                FROM   order_items
                WHERE  etsy_order_id   = :oid
                  AND  production_no   IS NOT NULL
                FOR UPDATE
            ");
            $fetcher->execute(['oid' => $etsyOrderId]);
            $items = $fetcher->fetchAll();

            if (!$items) throw new RuntimeException('Bu Order ID için üretim satırı bulunamadı.');

            // Build UPDATE depending on whether audit cols exist
            if ($hasTrackAudit) {
                $updTr = $pdo->prepare("
                    UPDATE order_items
                    SET    tracking_number     = :tn,
                           carrier             = :cr,
                           shipped_date        = :sd,
                           tracking_note       = :nte,
                           tracking_entered_by = :eb,
                           tracking_entered_at = NOW(),
                           updated_at          = NOW()
                    WHERE  id = :id
                ");
            } else {
                $updTr = $pdo->prepare("
                    UPDATE order_items
                    SET    tracking_number = :tn,
                           carrier         = :cr,
                           shipped_date    = :sd,
                           updated_at      = NOW()
                    WHERE  id = :id
                ");
            }

            $logTr = $pdo->prepare("
                INSERT INTO production_logs
                    (order_item_id, from_status_id, to_status_id, changed_by, changed_at, note)
                VALUES (:oi, :fs, :ts, :cb, NOW(), :note)
            ");

            foreach ($items as $item) {
                $params = [
                    'tn' => $trackingNo,
                    'cr' => $carrier ?: null,
                    'sd' => $shippedDate,
                    'id' => $item['id'],
                ];
                if ($hasTrackAudit) {
                    $params['nte'] = $trackNote ?: null;
                    $params['eb']  = $userId ?: null;
                }
                $updTr->execute($params);

                $logNote = 'Tracking girildi: '
                    .($carrier ? $carrier.' ' : '').$trackingNo
                    .($trackNote ? ' | '.$trackNote : '')
                    .' | Kargo tarihi: '.$shippedDate;
                $logTr->execute([
                    'oi'   => $item['id'],
                    'fs'   => $item['current_status_id'],
                    'ts'   => $item['current_status_id'],  // status unchanged by tracking entry
                    'cb'   => $userId ?: null,
                    'note' => $logNote,
                ]);
            }
            $pdo->commit();
            $_SESSION['flash'] = ['type' => 'success', 'msg' => count($items).' satıra tracking kaydedildi.'];
        } catch (Throwable $e) {
            $pdo->rollBack();
            $_SESSION['flash'] = ['type' => 'error', 'msg' => 'Tracking kaydedilemedi: '.prod_h($e->getMessage())];
        }
        $qs = $_GET ? ('?'.http_build_query($_GET)) : '';
        redirect('production.php'.$qs);
    }
}

/* ══════════════════════════════════════════════════════════════
   GET: Statuses, stores, filters
══════════════════════════════════════════════════════════════ */
try {
    $stores = $pdo->query("SELECT * FROM stores WHERE is_active = 1 ORDER BY store_code")->fetchAll();
} catch (Throwable $e) { $stores = []; }
$statuses = $pdo->query("SELECT * FROM production_statuses WHERE is_active = 1 ORDER BY sort_order, id")->fetchAll();
$statusById = [];
foreach ($statuses as $s) $statusById[(int)$s['id']] = $s;

/* ── GET filters ── */
$view           = $_GET['view']       ?? 'active';
$statusId       = (int)($_GET['status_id']    ?? 0);
$storeId        = (int)($_GET['store_id']     ?? 0);
$q              = trim((string)($_GET['q']    ?? ''));
$missing        = (int)($_GET['missing']      ?? 0);
$filterExpress  = (int)($_GET['express']      ?? 0);
$filterNoTrack  = (int)($_GET['no_tracking']  ?? 0);
$page           = max(1, (int)($_GET['page']  ?? 1));
$perPage        = 100;

/* ── WHERE builder ── */
$where = []; $params = [];

if ($view === 'active')    { $where[] = 'ps.is_final = 0 AND ps.is_cancelled = 0'; }
elseif ($view === 'completed') { $where[] = 'ps.is_final = 1 AND ps.is_cancelled = 0'; }
elseif ($view === 'cancelled') { $where[] = 'ps.is_cancelled = 1'; }

if ($statusId > 0)   { $where[] = 'oi.current_status_id = :status_id';  $params['status_id'] = $statusId; }
if ($storeId > 0)    { $where[] = 'oi.store_id = :store_id';             $params['store_id']  = $storeId; }
if ($missing === 1)  { $where[] = 'oi.product_card_missing = 1'; }
if ($filterExpress)  { $where[] = "oi.shipping_type = 'express'"; }
if ($filterNoTrack)  { $where[] = "(oi.tracking_number IS NULL OR oi.tracking_number = '')"; }
if ($q !== '') {
    $where[] = "(CAST(oi.production_no AS CHAR) LIKE :q
              OR oi.etsy_order_id         LIKE :q
              OR oi.transaction_id        LIKE :q
              OR oi.source_transaction_id LIKE :q
              OR oi.sku                   LIKE :q
              OR oi.ship_name             LIKE :q
              OR oi.buyer_name            LIKE :q
              OR p.master_code            LIKE :q
              OR p.product_name           LIKE :q
              OR specs.short_name         LIKE :q)";
    $params['q'] = '%'.$q.'%';
}
$whereSql = $where ? ('WHERE '.implode(' AND ', $where)) : '';

/* ── Stats (global, no view filter) ── */
try {
    $counts = $pdo->query("
        SELECT
          SUM(CASE WHEN ps.is_final=0  AND ps.is_cancelled=0 THEN 1 ELSE 0 END)  AS active_count,
          SUM(CASE WHEN ps.is_final=1  AND ps.is_cancelled=0 THEN 1 ELSE 0 END)  AS completed_count,
          SUM(CASE WHEN ps.is_cancelled=1                    THEN 1 ELSE 0 END)  AS cancelled_count,
          SUM(CASE WHEN oi.product_card_missing=1             THEN 1 ELSE 0 END)  AS missing_count,
          SUM(CASE WHEN oi.shipping_type='express' AND ps.is_final=0 AND ps.is_cancelled=0 THEN 1 ELSE 0 END) AS express_count,
          SUM(CASE WHEN (oi.tracking_number IS NULL OR oi.tracking_number='') AND ps.is_final=0 AND ps.is_cancelled=0 THEN 1 ELSE 0 END) AS no_track_count,
          SUM(CASE WHEN ps.is_final=0 AND ps.is_cancelled=0 AND DATEDIFF(NOW(), oi.created_at) > 7 THEN 1 ELSE 0 END) AS overdue_count
        FROM order_items oi
        JOIN production_statuses ps ON ps.id = oi.current_status_id
    ")->fetch();
} catch (Throwable $e) {
    $counts = array_fill_keys(['active_count','completed_count','cancelled_count','missing_count','express_count','no_track_count','overdue_count'], 0);
}

/* ── Count for pagination ── */
$countStmt = $pdo->prepare("
    SELECT COUNT(*) FROM order_items oi
    JOIN production_statuses ps ON ps.id = oi.current_status_id
    LEFT JOIN products p        ON p.id  = oi.product_id
    LEFT JOIN product_core_specs specs ON specs.product_id = p.id
    $whereSql
");
$countStmt->execute($params);
$totalRows  = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));
$page       = min($page, $totalPages);
$offset     = ($page - 1) * $perPage;

/* ── Main query ── */
$mainSql = "
    SELECT
        oi.*,
        s.store_code, s.store_name,
        ps.status_code, ps.status_name, ps.sort_order AS status_sort_order, ps.is_final, ps.is_cancelled,
        p.master_code, p.product_name, p.stone_info AS product_stone_info,
        specs.short_name, specs.gram_10k, specs.gram_14k, specs.gram_18k,
        COALESCE(pi.file_path, oi.product_image_path) AS image_path
    FROM order_items oi
    JOIN stores s ON s.id = oi.store_id
    JOIN production_statuses ps ON ps.id = oi.current_status_id
    LEFT JOIN products p ON p.id = oi.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
    $whereSql
    ORDER BY
        (oi.production_no IS NULL) ASC,
        oi.production_no DESC,
        (oi.ship_by_date IS NULL) ASC,
        oi.ship_by_date ASC,
        ps.sort_order ASC,
        oi.id ASC
    LIMIT $perPage OFFSET $offset
";
$stmt = $pdo->prepare($mainSql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

/* ── Multi-order detection (same etsy_order_id across ALL active rows) ── */
$multiOrderIds = [];
try {
    $moStmt = $pdo->query("
        SELECT etsy_order_id FROM order_items
        WHERE  etsy_order_id IS NOT NULL AND etsy_order_id <> ''
        GROUP  BY etsy_order_id HAVING COUNT(*) > 1
    ");
    foreach ($moStmt->fetchAll() as $mo) $multiOrderIds[$mo['etsy_order_id']] = true;
} catch (Throwable $e) {}

/* ── URL helper (preserve filters) ── */
function prod_url(array $extra = []): string {
    $q = array_merge($_GET, $extra);
    foreach ($q as $k => $v) if ($v === null || $v === '' || $v === '0' || $v === 0) unset($q[$k]);
    return 'production.php'.($q ? '?'.http_build_query($q) : '');
}

$page_title  = 'Üretim Listesi';
$active_menu = 'production';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div>
    <h1>Üretim Listesi</h1>
    <p>Admin onaylı siparişlerin üretim takibi. Barkod okuyucu ile Order ID arayabilirsin.</p>
  </div>
  <div class="fc gap8">
    <a href="admin_import_review.php" class="btn btn-secondary">CSV Onayları</a>
    <a href="csv_upload.php" class="btn btn-secondary">CSV Yükle</a>
  </div>
</div>

<!-- ── Stats pills ── -->
<div class="op-stat-grid" style="margin-bottom:10px">
  <a class="op-stat <?= $view==='active' && !$statusId && !$missing && !$filterExpress && !$filterNoTrack ? 'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'active','page'=>1,'status_id'=>'','express'=>'','missing'=>'','no_tracking'=>''])) ?>">
    <span>Açık Üretim</span><strong><?= (int)$counts['active_count'] ?></strong><em>devam eden</em>
  </a>
  <a class="op-stat <?= $view==='completed'?'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'completed','page'=>1,'status_id'=>'','express'=>'','missing'=>'','no_tracking'=>''])) ?>">
    <span>Tamamlanan</span><strong class="grn"><?= (int)$counts['completed_count'] ?></strong><em>final</em>
  </a>
  <a class="op-stat <?= $view==='cancelled'?'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'cancelled','page'=>1])) ?>">
    <span>İptal</span><strong class="red"><?= (int)$counts['cancelled_count'] ?></strong><em>kapalı</em>
  </a>
  <a class="op-stat <?= $missing===1?'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'active','missing'=>$missing?0:1,'page'=>1])) ?>">
    <span>Kart Eksik</span><strong class="yl"><?= (int)$counts['missing_count'] ?></strong><em>SKU eşleşmedi</em>
  </a>
  <a class="op-stat <?= $filterExpress?'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'active','express'=>$filterExpress?0:1,'page'=>1])) ?>">
    <span>Express</span><strong class="<?= (int)$counts['express_count']>0?'red':'' ?>"><?= (int)$counts['express_count'] ?></strong><em>öncelikli</em>
  </a>
  <a class="op-stat <?= $filterNoTrack?'active':'' ?>"
     href="<?= prod_h(prod_url(['view'=>'active','no_tracking'=>$filterNoTrack?0:1,'page'=>1])) ?>">
    <span>Tracking Yok</span><strong class="yl"><?= (int)$counts['no_track_count'] ?></strong><em>kargo girilmemiş</em>
  </a>
  <div class="op-stat">
    <span>Geciken</span><strong class="<?= (int)$counts['overdue_count']>0?'red':'' ?>"><?= (int)$counts['overdue_count'] ?></strong><em>~5 iş günü+</em>
  </div>
</div>

<!-- ── Barkod / Arama büyük alan ── -->
<div class="prd-barcode-zone">
  <form method="get" action="production.php" id="barcodeForm">
    <input type="hidden" name="view"       value="<?= prod_h($view) ?>">
    <input type="hidden" name="status_id"  value="<?= (int)$statusId ?>">
    <input type="hidden" name="store_id"   value="<?= (int)$storeId ?>">
    <input type="hidden" name="express"    value="<?= (int)$filterExpress ?>">
    <input type="hidden" name="missing"    value="<?= (int)$missing ?>">
    <input type="hidden" name="no_tracking" value="<?= (int)$filterNoTrack ?>">
    <div class="prd-barcode-row">
      <div class="prd-barcode-wrap">
        <span class="prd-barcode-ico">🔍</span>
        <input type="search" name="q" id="barcodeInput"
               value="<?= prod_h($q) ?>"
               class="prd-barcode-input"
               placeholder="Sıra no · Order ID (barkod) · Transaction ID · SKU · Müşteri adı..."
               autocomplete="off"
               autofocus>
        <?php if ($q): ?>
          <a href="<?= prod_h(prod_url(['q'=>'','page'=>1])) ?>" class="prd-barcode-clear" title="Temizle">✕</a>
        <?php endif; ?>
      </div>
      <button type="submit" class="btn btn-primary">Ara</button>
      <?php if ($q): ?>
        <a href="<?= prod_h(prod_url(['q'=>'','page'=>1])) ?>" class="btn btn-secondary">Temizle</a>
      <?php endif; ?>
    </div>
    <div class="prd-search-hint">
      <span>Üretim sıra no (#10001)</span>
      <span>Etsy Order ID / barkod</span>
      <span>Transaction ID</span>
      <span>SKU (BR003611)</span>
      <span>Müşteri adı</span>
    </div>
  </form>
</div>

<!-- ── Filter bar ── -->
<div class="card mb16">
  <div class="card-body op-filterbar">
    <form method="get" action="production.php" class="op-filter-form">
      <input type="hidden" name="q"          value="<?= prod_h($q) ?>">
      <input type="hidden" name="express"    value="<?= (int)$filterExpress ?>">
      <input type="hidden" name="missing"    value="<?= (int)$missing ?>">
      <input type="hidden" name="no_tracking" value="<?= (int)$filterNoTrack ?>">
      <div>
        <label class="form-label">Görünüm</label>
        <select name="view" class="form-control">
          <option value="active"    <?= $view==='active'   ?'selected':'' ?>>Açık Üretim</option>
          <option value="all"       <?= $view==='all'      ?'selected':'' ?>>Tümü</option>
          <option value="completed" <?= $view==='completed'?'selected':'' ?>>Tamamlanan</option>
          <option value="cancelled" <?= $view==='cancelled'?'selected':'' ?>>İptal</option>
        </select>
      </div>
      <div>
        <label class="form-label">Durum</label>
        <select name="status_id" class="form-control">
          <option value="0">Tüm durumlar</option>
          <?php foreach ($statuses as $s): ?>
            <option value="<?= (int)$s['id'] ?>" <?= $statusId===(int)$s['id']?'selected':'' ?>><?= prod_h($s['status_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="form-label">Mağaza</label>
        <select name="store_id" class="form-control">
          <option value="0">Tüm mağazalar</option>
          <?php foreach ($stores as $st): ?>
            <option value="<?= (int)$st['id'] ?>" <?= $storeId===(int)$st['id']?'selected':'' ?>><?= prod_h($st['store_code']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <button class="btn btn-primary" type="submit">Filtrele</button>
      <a href="production.php" class="btn btn-secondary">Sıfırla</a>
    </form>
  </div>
</div>

<?php if (!$rows): ?>
  <div class="prd-empty">
    <div class="empty-ico">∅</div>
    <div class="empty-title">Kayıt bulunamadı</div>
    <div class="empty-text" style="max-width:320px;margin:0 auto">
      <?= $q ? 'Arama için sonuç yok: <strong>'.prod_h($q).'</strong>' : 'Bu filtreye uygun üretim satırı yok.' ?>
    </div>
    <?php if ($q || $statusId || $missing || $filterExpress || $filterNoTrack): ?>
      <a href="production.php" class="btn btn-secondary" style="margin-top:14px">Tüm Filtreleri Temizle</a>
    <?php endif; ?>
  </div>
<?php else: ?>

<!-- ── Standalone bulk form — ONLY wraps the sticky bar.
     Row checkboxes outside use form="bulkForm" (HTML5 form attr).
     Tracking expand forms are fully separate; no nested forms. ── -->
<form method="post" action="production.php<?= $_GET ? '?'.prod_h(http_build_query($_GET)) : '' ?>" id="bulkForm">
  <?= csrf_field() ?>
  <input type="hidden" name="action" value="bulk_status">

  <!-- ── Sticky bulk bar ── -->
  <div class="card mb8 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>
      <span class="c-mt" style="font-size:12px">
        Toplam: <strong><?= (int)$totalRows ?></strong> satır &nbsp;·&nbsp;
        Sayfa <strong><?= (int)$page ?></strong> / <strong><?= (int)$totalPages ?></strong>
      </span>
      <div class="fc gap8" style="margin-left:auto;flex-wrap:wrap">
        <div class="fc gap8">
          <select name="to_status_id" class="form-control" style="min-width:180px">
            <option value="">Durum seç…</option>
            <?php foreach ($statuses as $s): ?>
              <option value="<?= (int)$s['id'] ?>"><?= prod_h($s['status_name']) ?></option>
            <?php endforeach; ?>
          </select>
          <input name="production_note" class="form-control" placeholder="Not (opsiyonel)" style="min-width:180px">
        </div>
        <button type="submit" class="btn btn-success" id="bulkBtn" disabled>Güncelle</button>
      </div>
    </div>
  </div>
</form><!-- /bulkForm — sticky bar only, closed here -->

  <!-- ── Production list ── -->
  <div class="prd-list">
    <!-- Header -->
    <div class="prd-header">
      <span></span>
      <span>#No / Durum</span>
      <span>Ürün</span>
      <span>Müşteri / Order</span>
      <span>Karat · Renk · Ölçü</span>
      <span>Kişiselleştirme</span>
      <span>Net</span>
      <span>Tracking</span>
      <span>Süre</span>
      <span></span>
    </div>

    <?php foreach ($rows as $row):
      $isCancelled = (int)($row['is_cancelled'] ?? 0) === 1;
      $isFinal     = (int)($row['is_final']     ?? 0) === 1;
      $isMissing   = (int)($row['product_card_missing'] ?? 0) === 1;
      $isExpress   = ($row['shipping_type'] ?? '') === 'express';
      $isMulti     = isset($multiOrderIds[$row['etsy_order_id'] ?? '']);
      $isRisk      = !empty($row['flagged_customer_id']);
      $isCustom    = (int)($row['is_custom'] ?? 0) === 1;
      $qtyIdx      = (int)($row['quantity_unit_index'] ?? 1);
      $qtyTot      = (int)($row['quantity_unit_total']  ?? 1);
      $isPiece     = $qtyTot > 1;
      $rowId       = (int)$row['id'];

      [$displayName, $nameSource] = prod_display_name($row);
      $imgUrl = csv_mod_image_url($row['image_path'] ?? '');

      $rowClass = 'prd-row';
      if ($isCancelled) $rowClass .= ' prd-cancelled';
      elseif ($isExpress) $rowClass .= ' prd-express-row';

      $netAmt   = $row['net_item_total'] ?? csv_mod_net_item_total($row['price'] ?? null, $row['discount_amount'] ?? null);
      $netFmt   = $netAmt !== null ? number_format((float)$netAmt, 2, '.', ',').' '.($row['currency'] ?? 'USD') : '-';

      $hasTracking = !empty(trim((string)($row['tracking_number'] ?? '')));
      $statusCode  = $row['status_code'] ?? '';
      $statusClass = $isCancelled ? 'cancel' : ($isFinal ? 'done' : 'active');
    ?>

    <!-- Main row -->
    <div class="<?= $rowClass ?>" id="prow-<?= $rowId ?>">

      <!-- Checkbox — form="bulkForm" associates this with the standalone bulk form above (HTML5) -->
      <div class="prd-cell-cb">
        <input type="checkbox" name="order_ids[]" value="<?= $rowId ?>"
               class="rowCheck" data-i="<?= $rowId ?>" form="bulkForm">
      </div>

      <!-- #No + Status -->
      <div class="prd-cell">
        <?php if ($row['production_no']): ?>
          <span class="prd-no-badge">#<?= prod_h($row['production_no']) ?></span>
        <?php else: ?>
          <span class="prd-no-badge no-num">#<?= $rowId ?></span>
        <?php endif; ?>
        <div><span class="prd-status <?= $statusClass ?>"><?= prod_h($row['status_name'] ?? '-') ?></span></div>
        <div class="prd-warn-badges">
          <?php if ($isExpress):   ?><span class="prd-wbadge express">⚡ EXP</span><?php endif; ?>
          <?php if ($isMissing):   ?><span class="prd-wbadge miss">EKSİK</span><?php endif; ?>
          <?php if ($isMulti):     ?><span class="prd-wbadge multi">ÇOKLU</span><?php endif; ?>
          <?php if ($isRisk):      ?><span class="prd-wbadge risk">RİSK</span><?php endif; ?>
          <?php if ($isCustom):    ?><span class="prd-wbadge custom">CUSTOM</span><?php endif; ?>
          <?php if ($isPiece):     ?><span class="prd-wbadge piece"><?= $qtyIdx ?>/<?= $qtyTot ?></span><?php endif; ?>
        </div>
      </div>

      <!-- Product -->
      <div class="prd-cell">
        <div class="prd-product-cell">
          <div class="prd-img-wrap">
            <?php if ($imgUrl): ?><img src="<?= prod_h($imgUrl) ?>" alt="" loading="lazy">
            <?php else: ?>◻<?php endif; ?>
          </div>
          <div class="prd-product-info">
            <div class="prd-sku-line">
              <span class="prd-sku"><?= prod_h($row['sku'] ?: '—') ?></span>
              <?php if ($isMissing): ?><span class="prd-pname-miss">kart yok</span><?php endif; ?>
            </div>
            <span class="prd-pname <?= $nameSource === 'etsy' ? 'fallback' : '' ?>" title="<?= prod_h($displayName) ?>">
              <?= prod_h($displayName) ?>
            </span>
          </div>
        </div>
      </div>

      <!-- Customer + Order ID -->
      <div class="prd-cell">
        <div class="prd-customer-name" title="<?= prod_h($row['ship_name'] ?: $row['buyer_name'] ?: '') ?>">
          <?= prod_h(mb_substr($row['ship_name'] ?: $row['buyer_name'] ?: '-', 0, 30, 'UTF-8')) ?>
        </div>
        <div class="prd-order-id"><?= prod_h($row['etsy_order_id'] ?: '-') ?></div>
        <div class="prd-location"><?= prod_h(trim(($row['ship_city']??'').', '.($row['ship_state']??'').' '.($row['ship_country']??''))) ?></div>
      </div>

      <!-- Specs -->
      <div class="prd-cell">
        <div class="prd-specs">
          <?php if ($row['parsed_karat']): ?><span class="prd-spec-chip karat"><?= prod_h($row['parsed_karat']) ?></span><?php endif; ?>
          <?php if ($row['parsed_color']): ?><span class="prd-spec-chip"><?= prod_h($row['parsed_color']) ?></span><?php endif; ?>
          <?php if ($row['parsed_size']): ?><span class="prd-spec-chip">⌀ <?= prod_h($row['parsed_size']) ?></span><?php endif; ?>
          <?php if (!empty($row['parsed_chain_length']) && $row['parsed_chain_length'] !== $row['parsed_size']): ?>
            <span class="prd-spec-chip">⊢ <?= prod_h($row['parsed_chain_length']) ?></span>
          <?php endif; ?>
        </div>
      </div>

      <!-- Personalization + stone -->
      <div class="prd-cell">
        <?php if (!empty($row['personalization'])): ?>
          <div class="prd-personal-short"><?= prod_h($row['personalization']) ?></div>
        <?php endif; ?>
        <?php if (!empty($row['product_stone_info'])): ?>
          <div class="prd-stone-info">💎 <?= prod_h(mb_substr($row['product_stone_info'], 0, 60, 'UTF-8')) ?></div>
        <?php endif; ?>
      </div>

      <!-- Net / Kargo -->
      <div class="prd-cell">
        <span class="prd-net"><?= prod_h($netFmt) ?></span>
        <div><?= prod_ship_badge($row['shipping_type'] ?? '') ?></div>
      </div>

      <!-- Tracking -->
      <div class="prd-cell">
        <?php if ($hasTracking): ?>
          <span class="prd-track-has">✓ <?= prod_h($row['carrier'] ?? '') ?></span>
          <span class="prd-track-no-text" title="<?= prod_h($row['tracking_number']) ?>">
            <?= prod_h($row['tracking_number']) ?>
          </span>
        <?php endif; ?>
        <button type="button" class="prd-track-btn" onclick="toggleTracking(<?= $rowId ?>)">
          <?= $hasTracking ? '✎ Düzenle' : '+ Tracking gir' ?>
        </button>
      </div>

      <!-- Days -->
      <div class="prd-cell"><?= prod_days_html($row) ?></div>

      <!-- Action -->
      <div class="prd-cell">
        <a class="prd-detail-btn" href="order_detail.php?id=<?= $rowId ?>" title="Detay / Geçmiş">→</a>
      </div>

    </div><!-- .prd-row -->

    <!-- Tracking expand row -->
    <div class="prd-track-expand" id="ptrack-<?= $rowId ?>">
      <form method="post" action="production.php<?= $_GET ? '?'.prod_h(http_build_query($_GET)) : '' ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="action"        value="tracking_update">
        <input type="hidden" name="etsy_order_id" value="<?= prod_h($row['etsy_order_id'] ?? '') ?>">
        <?php if ($isMulti): ?>
          <p class="prd-track-order-note">⚠ Bu Order ID'de birden fazla üretim satırı var — hepsine aynı tracking kaydedilecek.</p>
        <?php endif; ?>
        <div class="prd-track-expand-inner">
          <div class="form-group" style="flex:2;min-width:180px">
            <label class="form-label">Tracking No <span class="c-red">*</span></label>
            <input name="tracking_number" class="form-control" required
                   value="<?= prod_h($row['tracking_number'] ?? '') ?>"
                   placeholder="9400 1234 5678...">
          </div>
          <div class="form-group" style="min-width:130px">
            <label class="form-label">Kargo Firması</label>
            <select name="tracking_carrier" class="form-control">
              <option value="">Seç…</option>
              <?php foreach (['USPS','UPS','FedEx','DHL','Other'] as $c): ?>
                <option value="<?= $c ?>" <?= ($row['carrier']??'') === $c ? 'selected' : '' ?>><?= $c ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group" style="min-width:130px">
            <label class="form-label">Kargo Tarihi</label>
            <input type="date" name="shipped_date" class="form-control"
                   value="<?= prod_h(!empty($row['shipped_date']) ? prod_date($row['shipped_date']) : date('Y-m-d')) ?>">
          </div>
          <div class="form-group" style="flex:2;min-width:160px">
            <label class="form-label">Not (opsiyonel)</label>
            <input name="tracking_note" class="form-control"
                   value="<?= prod_h($row['tracking_note'] ?? '') ?>"
                   placeholder="UPS NextDay, expedited...">
          </div>
          <div class="fc gap8" style="padding-bottom:1px">
            <button type="submit" class="btn btn-success btn-sm">Kaydet</button>
            <button type="button" class="btn btn-secondary btn-sm" onclick="toggleTracking(<?= $rowId ?>)">İptal</button>
          </div>
        </div>
      </form>
    </div><!-- .prd-track-expand -->

    <?php endforeach; ?>
  </div><!-- .prd-list -->

<!-- ── Pagination ── -->
<?php if ($totalPages > 1): ?>
<div class="prd-pagination">
  <?php if ($page > 1): ?>
    <a class="btn btn-secondary btn-sm" href="<?= prod_h(prod_url(['page'=>$page-1])) ?>">← Önceki</a>
  <?php endif; ?>
  <span>Sayfa <?= (int)$page ?> / <?= (int)$totalPages ?> &nbsp;·&nbsp; <?= (int)$totalRows ?> satır</span>
  <?php if ($page < $totalPages): ?>
    <a class="btn btn-secondary btn-sm" href="<?= prod_h(prod_url(['page'=>$page+1])) ?>">Sonraki →</a>
  <?php endif; ?>
</div>
<?php endif; ?>

<?php endif; // rows exist ?>

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

function getChecks() { return Array.from(document.querySelectorAll('.rowCheck')); }

function updateSel() {
  const n = getChecks().filter(c => c.checked).length;
  countEl.textContent = n + ' seçili';
  bulkBtn.disabled = n === 0;
  getChecks().forEach(c => document.getElementById('prow-' + c.dataset.i)?.classList.toggle('sel', c.checked));
}

selAll?.addEventListener('change', () => { getChecks().forEach(c => c.checked = selAll.checked); updateSel(); });
document.addEventListener('change', e => { if (e.target.classList.contains('rowCheck')) updateSel(); });
updateSel();

/* ── Tracking row toggle ── */
function toggleTracking(rowId) {
  const el = document.getElementById('ptrack-' + rowId);
  if (!el) return;
  el.classList.toggle('open');
  if (el.classList.contains('open')) {
    el.querySelector('input[name="tracking_number"]')?.focus();
  }
}

/* ── Barcode scanner: form submits on Enter naturally ──
   Adding autofocus ensures scanner can shoot directly    ── */
document.getElementById('barcodeInput')?.addEventListener('search', function() {
  if (!this.value.trim()) {
    window.location.href = <?= json_encode(prod_url(['q'=>'','page'=>1])) ?>;
  }
});
</script>

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