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

function myo_h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
$user = current_user();
$storeId = (int)($user['store_id'] ?? 0);
$pdo = db();
$statusId = (int)($_GET['status_id'] ?? 0);
$q = trim((string)($_GET['q'] ?? ''));
$statuses = $pdo->query("SELECT * FROM production_statuses WHERE is_active=1 ORDER BY sort_order, id")->fetchAll();
$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 '.implode(' AND ', $where);
$stmt = $pdo->prepare("\n    SELECT oi.*, 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 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 300\n");
$stmt->execute($params);
$rows = $stmt->fetchAll();

$page_title = 'Siparişlerim';
$active_menu = 'my_orders';
include __DIR__ . '/includes/layout.php';
?>

<div class="ph">
  <div><h1>Siparişlerim</h1><p>Mağazanızdan admin onayıyla üretime giren siparişler.</p></div>
  <a href="csv_upload.php" class="btn btn-secondary">CSV Yükle</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">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':'' ?>><?= myo_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="<?= myo_h($q) ?>" class="form-control" placeholder="SKU, müşteri, order..."></div>
      <button class="btn btn-primary" type="submit">Filtrele</button>
      <a href="my_orders.php" class="btn btn-secondary">Sıfırla</a>
    </form>
  </div>
</div>

<?php if (!$rows): ?>
  <div class="card"><div class="empty"><div class="empty-ico">∅</div><div class="empty-title">Üretime alınmış sipariş yok</div><div class="empty-text">CSV yükleyip admin onayından geçtikten sonra siparişler burada görünecek.</div></div></div>
<?php else: ?>
  <?php foreach($rows as $r): $img=csv_mod_image_url($r['image_path'] ?? ''); ?>
    <div class="csv-card">
      <div class="csv-head">
        <span class="badge bg-mt"><?= myo_h($r['status_name']) ?></span>
        <?php if((int)($r['product_card_missing'] ?? 0)===1): ?><span class="badge bg-yl">Ürün 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 <?= myo_h(csv_mod_quantity_label($r)) ?></span><?php endif; ?>
        <span class="mn c-mt" style="margin-left:auto">TID: <?= myo_h($r['transaction_id']) ?></span>
      </div>
      <div class="csv-body">
        <div class="csv-photo"><?php if($img): ?><img src="<?= myo_h($img) ?>" alt="" loading="lazy"><?php else: ?><div class="p-thumb-empty">◻</div><?php endif; ?></div>
        <div class="csv-col">
          <div class="csv-field"><div class="csv-fl">SKU</div><div class="csv-fv gld"><?= myo_h($r['sku'] ?: '-') ?></div></div>
          <div class="csv-field"><div class="csv-fl">Ürün</div><div class="csv-fv"><?= myo_h($r['product_name'] ?: $r['listing_title'] ?: '-') ?></div></div>
          <div class="csv-field"><div class="csv-fl">Order</div><div class="csv-fv mn"><?= myo_h($r['etsy_order_id'] ?: '-') ?></div></div>
        </div>
        <div class="csv-col">
          <div class="csv-field"><div class="csv-fl">Müşteri</div><div class="csv-fv"><?= myo_h($r['ship_name'] ?: $r['buyer_name'] ?: '-') ?></div></div>
          <div class="csv-field"><div class="csv-fl">Karat / Renk / Ölçü</div><div class="csv-fv"><?= myo_h(($r['parsed_karat'] ?: '-').' / '.($r['parsed_color'] ?: '-').' / '.($r['parsed_size'] ?: '-')) ?></div></div>
          <div class="csv-field"><div class="csv-fl">Kişiselleştirme</div><div class="csv-fv" style="white-space:pre-wrap"><?= myo_h($r['personalization'] ?: '-') ?></div></div>
        </div>
        <div class="csv-col">
          <div class="csv-field"><div class="csv-fl">Satış Tarihi</div><div class="csv-fv"><?= myo_h(substr((string)$r['sale_date'],0,10) ?: '-') ?></div></div>
          <div class="csv-field"><div class="csv-fl">Not</div><div class="csv-fv mt"><?= myo_h($r['store_note'] ?: '-') ?></div></div>
          <div class="csv-field"><div class="csv-fl">Detay</div><div class="csv-fv"><a href="order_detail.php?id=<?= (int)$r['id'] ?>">Sipariş detayını aç</a></div></div>
        </div>
      </div>
    </div>
  <?php endforeach; ?>
<?php endif; ?>

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