<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/csv_module_common.php';
require_login();
require_role(['admin','production_manager']);

function ord_h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
$pdo = db();
$storeId = (int)($_GET['store_id'] ?? 0);
$statusId = (int)($_GET['status_id'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));
$stores = $pdo->query("SELECT * FROM stores WHERE is_active=1 ORDER BY store_code")->fetchAll();
[$imageSelect, $imageJoin] = csv_mod_order_image_sql('oi', 'p', 'image_path');
$statuses = $pdo->query("SELECT * FROM production_statuses WHERE is_active=1 ORDER BY sort_order, id")->fetchAll();
$where = [];
$params = [];
if ($storeId > 0) { $where[] = 'oi.store_id=:store_id'; $params['store_id']=$storeId; }
if ($statusId > 0) { $where[] = 'oi.current_status_id=:status_id'; $params['status_id']=$statusId; }
if ($q !== '') {
    $where[] = "(oi.transaction_id LIKE :q OR oi.source_transaction_id LIKE :q OR oi.etsy_order_id LIKE :q OR oi.sku LIKE :q OR oi.ship_name LIKE :q OR oi.buyer_name LIKE :q OR oi.listing_title LIKE :q OR p.master_code LIKE :q OR p.product_name LIKE :q)";
    $params['q'] = '%'.$q.'%';
}
$whereSql = $where ? 'WHERE '.implode(' AND ', $where) : '';
$stmt = $pdo->prepare("\n    SELECT oi.*, s.store_code, ps.status_name, ps.status_code, p.master_code, p.product_name, COALESCE(pi.file_path, oi.product_image_path) AS image_path\n    FROM order_items oi\n    JOIN stores s ON s.id=oi.store_id\n    JOIN production_statuses ps ON ps.id=oi.current_status_id\n    LEFT JOIN products p ON p.id=oi.product_id\n    LEFT JOIN product_images pi ON pi.product_id=p.id AND pi.is_primary=1\n    $whereSql\n    ORDER BY oi.sale_date DESC, oi.id DESC\n    LIMIT 500\n");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$page_title = 'Tüm Siparişler';
$active_menu = 'orders';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div><h1>Tüm Siparişler</h1><p>Admin onayından geçmiş CSV siparişlerinin genel listesi.</p></div>
  <a href="production.php" class="btn btn-secondary">Üretim Listesi</a>
</div>

<div class="card mb16">
  <div class="card-body" style="padding:12px 16px">
    <form method="get" class="fc gap8" style="flex-wrap:wrap;align-items:end">
      <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 $s): ?><option value="<?= (int)$s['id'] ?>" <?= $storeId===(int)$s['id']?'selected':'' ?>><?= ord_h($s['store_code']) ?></option><?php endforeach; ?></select></div>
      <div><label class="form-label">Durum</label><select name="status_id" class="form-control"><option value="0">Tümü</option><?php foreach($statuses as $s): ?><option value="<?= (int)$s['id'] ?>" <?= $statusId===(int)$s['id']?'selected':'' ?>><?= ord_h($s['status_name']) ?></option><?php endforeach; ?></select></div>
      <div style="flex:1;min-width:220px"><label class="form-label">Ara</label><input name="q" value="<?= ord_h($q) ?>" class="form-control" placeholder="SKU, müşteri, order..."></div>
      <button class="btn btn-primary" type="submit">Filtrele</button>
      <a href="orders.php" class="btn btn-secondary">Sıfırla</a>
    </form>
  </div>
</div>

<div class="card">
<?php if (!$rows): ?>
  <div class="empty"><div class="empty-ico">∅</div><div class="empty-title">Sipariş bulunamadı</div></div>
<?php else: ?>
  <div class="table-wrap">
    <table>
      <thead><tr><th></th><th>Mağaza</th><th>SKU</th><th>Ürün / Müşteri</th><th>Durum</th><th>Tarih</th><th></th></tr></thead>
      <tbody>
      <?php foreach($rows as $r): $img=csv_mod_image_url($r['image_path'] ?? ''); ?>
        <tr>
          <td style="width:62px"><?php if($img): ?><img src="<?= ord_h($img) ?>" style="width:48px;height:48px;object-fit:cover;border-radius:8px" loading="lazy"><?php else: ?>□<?php endif; ?></td>
          <td><span class="badge bg-gld"><?= ord_h($r['store_code']) ?></span></td>
          <td class="mn"><?= ord_h($r['sku'] ?: '-') ?></td>
          <td><strong><?= ord_h($r['product_name'] ?: $r['listing_title'] ?: '-') ?></strong><br><span class="c-mt"><?= ord_h($r['ship_name'] ?: $r['buyer_name'] ?: '-') ?> · <?= ord_h($r['etsy_order_id'] ?: '-') ?></span></td>
          <td><span class="badge bg-mt"><?= ord_h($r['status_name']) ?></span><?php if((int)($r['product_card_missing'] ?? 0)===1): ?> <span class="badge bg-yl">Kart yok</span><?php endif; ?><?php if((int)($r['is_custom'] ?? 0)===1): ?> <span class="badge bg-yl">CUSTOM</span><?php endif; ?><?php if(csv_mod_quantity_label($r)): ?> <span class="badge bg-yl">Adet <?= ord_h(csv_mod_quantity_label($r)) ?></span><?php endif; ?></td>
          <td class="mn"><?= ord_h(substr((string)$r['sale_date'],0,10) ?: '-') ?></td>
          <td class="tr"><a class="btn btn-secondary btn-sm" href="order_detail.php?id=<?= (int)$r['id'] ?>">Detay</a></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php endif; ?>
</div>

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