<?php
declare(strict_types=1);

/**
 * seller/siparisler.php
 * - İlk ekran: Siparişler (tablo + ürün görseli + kargonomi + mavi "Sipariş Detayları")
 * - Detay ekranı: SADECE sipariş detayı (liste görünmez)
 * - Tasarım: kurumsal / modern / tablo ağırlıklı
 */

$base   = $base ?? (function_exists('app_base') ? app_base('seller/') : '/seller/');
$active = 'siparisler';

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

/* Sidebar */
include __DIR__ . '/../app/sidebar.php';

/* =========================
   ✅ AYARLAR (URL'leri sen gireceksin)
========================= */
/** Ürün görseli boşsa fallback */
$defaultProductImg = 'https://m.media-amazon.com/images/I/612WoRmgb6L.jpg';
/** Kargonomi butonu ikon/görsel URL (paraşüt yerine) */
$kargonomiIconUrl  = 'https://sanatcidan.wanyweb.com/seller/img/krg.png';
/** Kargonomi yönlendirme linki (genel) */
$kargonomiBaseUrl  = '#';

/* =========================
   DEMO DATA
========================= */
$orders = [
  [
    'id'=>423923222683,
    'order_no'=>'#423923222683',
    'customer'=>'tuğba erdoğan',
    'pay_method'=>'Kredi Kartı',
    'total'=>3195.00,
    'currency'=>'TRY',
    'date'=>'2026-01-12 15:51',
    'status'=>'kargoya_verildi',
    'product_img'=>'',
    'kargonomi_url'=>'',
    'detail'=>[
      'ip'=>'2a02:f0c:610:e7ef:35b0:3fbe:5d48:364f',
      'channel'=>'Mobil',
      'payment'=>'Kredi Kartı (PayTR)',
      'invoice_download_url'=>'#',
      'addresses'=>[
        'delivery'=>[
          'name'=>'tuğba erdoğan',
          'tc'=>'25823474364',
          'phone'=>'(530) 391-9664',
          'email'=>'tugbaerdogan3534@gmail.com',
          'zip'=>'35400',
          'address'=>"adatepe mahallesi 3 sokak no:40 kat:2 daire:5\nBuca / İzmir / Türkiye"
        ],
        'invoice'=>[
          'name'=>'tuğba erdoğan',
          'tc'=>'25823474364',
          'phone'=>'(530) 391-9664',
          'email'=>'tugbaerdogan3534@gmail.com',
          'zip'=>'35400',
          'address'=>"adatepe mahallesi 3 sokak no:40 kat:2 daire:5\nBuca / İzmir / Türkiye"
        ],
      ],
      'customer_note'=>'',
      'items'=>[
        [
          'name'=>'Demo Ürün 738392758237972.',
          'variant'=>'Renk: Yeşil (+25.00 TRY)',
          'qty'=>2,
          'unit'=>1479.17,
          'vat'=>295.83,
          'line_total'=>3550.00,
          'shipping'=>0.00,
          'status'=>'Kargolandı',
          'img'=>$defaultProductImg,
        ]
      ],
    ],
  ],
  [
    'id'=>891216552591,
    'order_no'=>'#891216552591',
    'customer'=>'Pınar Bülbül Kocaman',
    'pay_method'=>'Kredi Kartı',
    'total'=>1225.00,
    'currency'=>'TRY',
    'date'=>'2026-01-11 22:41',
    'status'=>'kargoya_verildi',
    'product_img'=>$defaultProductImg,
    'kargonomi_url'=>'',
    'detail'=>[
      'ip'=>'—',
      'channel'=>'Web',
      'payment'=>'Kredi Kartı',
      'invoice_download_url'=>'#',
      'addresses'=>[
        'delivery'=>['name'=>'Pınar Bülbül Kocaman','tc'=>'—','phone'=>'—','email'=>'—','zip'=>'—','address'=>"—"],
        'invoice'=>['name'=>'Pınar Bülbül Kocaman','tc'=>'—','phone'=>'—','email'=>'—','zip'=>'—','address'=>"—"],
      ],
      'customer_note'=>'',
      'items'=>[
        ['name'=>'Ürün adı demo','variant'=>'—','qty'=>1,'unit'=>1225,'vat'=>0,'line_total'=>1225,'shipping'=>0,'status'=>'Kargolandı','img'=>$defaultProductImg]
      ],
    ],
  ],
];

/* =========================
   Helpers
========================= */
function money_tr(float $n): string { return number_format($n, 2, ',', '.'); }
function dt_tr(string $s): string { $ts = strtotime($s); return $ts ? date('d M Y, H:i', $ts) : $s; }
function status_text(string $s): string {
  return match($s){
    'kargoya_verildi' => 'Ürünler Kargoya Verildi',
    'hazirlaniyor'    => 'Hazırlanıyor',
    'beklemede'       => 'Beklemede',
    'tamamlandi'      => 'Tamamlandı',
    'iptal'           => 'İptal',
    default           => '—',
  };
}
function status_style(string $s): array {
  return match($s){
    'kargoya_verildi' => ['#F59E0B', '#FFFFFF', '#D97706'],
    'hazirlaniyor'    => ['#2563EB', '#FFFFFF', '#1D4ED8'],
    'beklemede'       => ['#F97316', '#FFFFFF', '#EA580C'],
    'tamamlandi'      => ['#10B981', '#FFFFFF', '#059669'],
    'iptal'           => ['#EF4444', '#FFFFFF', '#DC2626'],
    default           => ['#64748B', '#FFFFFF', '#475569'],
  };
}

/* =========================
   Mode
========================= */
$mode = (string)($_GET['view'] ?? 'list'); // list | detail
$id   = (int)($_GET['id'] ?? 0);

$selected = null;
if ($id > 0) {
  foreach ($orders as $o) { if ((int)$o['id'] === $id) { $selected = $o; break; } }
}
if (!$selected) $selected = $orders[0] ?? null;

$flash = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = (string)($_POST['action'] ?? '');
  $flash  = match($action){
    'save_status' => 'Sipariş durumu güncellendi (demo).',
    'notify'      => 'Müşteriye bildirim gönderildi (demo).',
    'print'       => 'Yazdırma başlatıldı (demo).',
    'delete'      => 'Sipariş silindi (demo).',
    default       => '',
  };
  $mode = 'detail';
}

/* Filter (list) */
$q = trim((string)($_GET['q'] ?? ''));
$filtered = $orders;
if ($mode === 'list' && $q !== '') {
  $filtered = array_values(array_filter($filtered, function($o) use ($q){
    return (mb_stripos((string)$o['order_no'], $q) !== false)
        || (mb_stripos((string)$o['customer'], $q) !== false);
  }));
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8" />
  <title>Siparişler</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <script defer src="https://unpkg.com/lucide@latest"></script>

  <style>
   :root{
  --bg:#F3F4F6;
  --card:#FFFFFF;

  /* ✅ Siyah yerine koyu gri */
  --text:#3d3e40;      /* ana metin */
  --muted:#6B7280;     /* ikincil metin */
  --line:rgba(31,41,55,.14);
  --soft:#F8FAFC;

  --radius:10px;
  --radius2:8px;
  --blue:#2563EB;
  --red:#EF4444;

  /* ✅ Sidebar boşluğu (JS set ediyor) */
  --sbw:0px;
}
html,body{height:100%;}
body{
  margin:0;
  background:var(--bg);
  font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
  color:var(--text);
  overflow-x:hidden;
}

/* ✅ Sayfa sidebar'a dokunmasın */
.mainWrap{
  margin-left: var(--sbw);
  width: calc(100vw - var(--sbw));
  max-width: calc(100vw - var(--sbw));
  overflow-x: hidden;
}

.wrap{padding:14px;}
.panel{
  background:var(--card);
  border:1px solid var(--line);
  border-radius:var(--radius);
  overflow:hidden;
}
.topbar{
  padding:14px 14px;
  border-bottom:1px solid var(--line);
  display:flex;align-items:center;justify-content:space-between;gap:12px;
}

/* ✅ Başlıklar hariç siyah yok (başlıklar koyu kalabilir) */
.title{font-weight:900;letter-spacing:-.02em;font-size:16px;color:#0F172A;}
.subtle{color:var(--muted);font-weight:800;font-size:12px;}

.search{
  display:flex;align-items:center;gap:10px;
  height:42px;padding:0 12px;
  border:1px solid var(--line);
  border-radius:var(--radius2);
  background:var(--soft);
  min-width:260px;
}
.search input{
  border:0;outline:0;background:transparent;width:100%;
  font-weight:900;font-size:13px;color:var(--text);
}

/* Buttons */
.btn{
  height:40px;padding:0 12px;
  border:1px solid var(--line);
  border-radius:var(--radius2);
  background:#fff;
  font-weight:900;font-size:13px;
  display:inline-flex;align-items:center;gap:8px;
  cursor:pointer;
  color:var(--text);
}
.btn.blue{background:var(--blue);border-color:var(--blue);color:#fff;}
.btn.red{background:var(--red);border-color:var(--red);color:#fff;}
/* ✅ Siyah yok → koyu gri */
.btn.gray{background:#374151;border-color:#374151;color:#fff;}

.iconbtn{
  width:40px;height:40px;
  border:1px solid var(--line);
  border-radius:var(--radius2);
  background:#fff;
  display:flex;align-items:center;justify-content:center;
  cursor:pointer;
  color:var(--text);
}

/* ✅ MODERN CHECKBOX (rounded) */
input[type="checkbox"]{
  appearance:none;
  -webkit-appearance:none;
  width:18px;height:18px;
  border-radius:6px;                 /* köşeler yuvarlak */
  border:1.5px solid rgba(31,41,55,.28);
  background:#fff;
  display:inline-grid;
  place-content:center;
  cursor:pointer;
  transition:all .15s ease;
  box-shadow:0 1px 0 rgba(31,41,55,.05);
}
input[type="checkbox"]:hover{
  border-color: rgba(37,99,235,.55);
}
input[type="checkbox"]:checked{
  background:var(--blue);
  border-color:var(--blue);
}
input[type="checkbox"]:checked::after{
  content:"";
  width:10px;height:10px;
  border-radius:3px;
  background:#fff;
}
input[type="checkbox"]:focus{
  outline:none;
  box-shadow:0 0 0 3px rgba(37,99,235,.18);
}

/* TABLE */
.tableWrap{width:100%;overflow:auto;}
table{width:100%;border-collapse:separate;border-spacing:0;min-width:980px;}
thead th{
  text-align:left;
  padding:12px 12px;
  font-size:12px;
  color:#0F172A;         /* başlıklar koyu kalabilir */
  font-weight:900;
  background:#F1F5F9;
  border-bottom:1px solid var(--line);
  white-space:nowrap;
}
tbody td{
  padding:12px 12px;
  border-bottom:1px solid var(--line);
  font-weight:800;
  font-size:13px;
  vertical-align:middle;
  white-space:nowrap;
  color:var(--text);
}
tbody tr:hover{background:var(--soft);}
.chk{width:44px;}
.orderNo{font-weight:950;}
.avatarName{display:flex;align-items:center;gap:8px;min-width:220px;}
.avatarDot{
  width:18px;height:18px;border-radius:999px;background:#E2E8F0;
  display:inline-flex;align-items:center;justify-content:center;
}
.productCell{display:flex;align-items:center;gap:10px;min-width:220px;}
.pimg{
  width:44px;height:44px;border-radius:10px;border:1px solid var(--line);
  object-fit:cover;background:#fff;
}
.statusBadge{
  display:inline-flex;align-items:center;justify-content:center;
  height:28px;padding:0 12px;border-radius:8px;
  font-weight:950;font-size:12px;
  border:1px solid transparent;
}
.actions{display:flex;gap:8px;justify-content:flex-end;}

.act{
  width:38px;height:38px;border-radius:8px;border:1px solid var(--line);
  display:flex;align-items:center;justify-content:center;
  cursor:pointer;background:#fff;
  color:var(--text);
}
.act.blue{background:#3B82F6;border-color:#3B82F6;color:#fff;}
.act.red{background:#EF4444;border-color:#EF4444;color:#fff;}
/* ✅ Siyah yok → koyu gri */
.act.dark{background:#374151;border-color:#374151;color:#fff;}
.act.soft{background:#F8FAFC;}

/* ✅ KARGONOMI: sarılık yok + görsel kutuyu tamamen kaplar */
.act.kargonomi{
  padding:0;
  overflow:hidden;
  background:#fff;
  border-color:var(--line);
}
.act.kargonomi img{
  width:100%;
  height:100%;
  display:block;
  object-fit:cover;
}

.price{font-weight:950;}
.muted{color:var(--muted);font-weight:800;font-size:12px;}

/* DETAIL */
.detailGrid{display:grid;grid-template-columns:1.1fr .9fr;gap:12px;padding:14px;}
.card{
  border:1px solid var(--line);
  border-radius:var(--radius2);
  background:#fff;
  overflow:hidden;
}
.cardHead{
  padding:12px 12px;border-bottom:1px solid var(--line);
  font-weight:950;font-size:13px;
  display:flex;align-items:center;justify-content:space-between;gap:10px;
  background:#F8FAFC;
  color:#0F172A;          /* başlıklar koyu kalabilir */
}
.cardBody{padding:12px 12px;}
.kvRow{
  display:grid;grid-template-columns:160px 1fr;gap:10px;
  padding:8px 0;border-bottom:1px dashed rgba(31,41,55,.18);
}
.kvRow:last-child{border-bottom:0;}
.k{color:var(--muted);font-weight:900;font-size:12px;}
.v{font-weight:950;font-size:13px;color:var(--text);white-space:pre-line;}
.miniBtns{display:flex;gap:8px;flex-wrap:wrap;}
.pill{
  display:inline-flex;align-items:center;justify-content:center;
  height:30px;padding:0 12px;border-radius:8px;
  border:1px solid var(--line);
  background:#fff;font-weight:950;font-size:12px;
  cursor:pointer;
  gap:8px;
  color:var(--text);
}
.pill.blue{background:#3B82F6;border-color:#3B82F6;color:#fff;}
.pill.red{background:#EF4444;border-color:#EF4444;color:#fff;}
/* ✅ Siyah yok → koyu gri */
.pill.gray{background:#374151;border-color:#374151;color:#fff;}

/* ✅ Detay sayfasında kargonomi logo aşırı büyük olmasın */
.pill img{
  width:18px;height:18px;
  object-fit:contain;
  display:block;
}

.select{
  width:100%;
  height:42px;
  border:1px solid var(--line);
  border-radius:8px;
  background:#fff;
  font-weight:900;
  padding:0 12px;
  outline:0;
  color:var(--text);
}
.checkline{
  display:flex;align-items:center;gap:10px;margin-top:10px;
  color:var(--text);            /* ✅ siyah yok */
  font-weight:900;font-size:12px;
}
.noteBox{
  margin-top:12px;border:1px solid var(--line);
  border-radius:8px;background:#F8FAFC;padding:12px;
}
.itemsTable{width:100%;border-collapse:separate;border-spacing:0;}
.itemsTable th{
  text-align:left;padding:10px 10px;background:#F1F5F9;border-bottom:1px solid var(--line);
  font-weight:950;font-size:12px;color:#0F172A; /* başlık */
}
.itemsTable td{
  padding:10px 10px;border-bottom:1px solid var(--line);
  font-weight:900;font-size:13px;vertical-align:top;color:var(--text);
}
.itemLine{display:flex;gap:10px;}
.itemImg{width:56px;height:56px;border-radius:10px;border:1px solid var(--line);object-fit:cover;}
.sumRow{
  display:flex;justify-content:space-between;gap:10px;
  padding:12px;background:#F8FAFC;font-weight:950;border-top:1px solid var(--line);
  color:var(--text);
}

.flash{
  margin:14px;border:1px solid var(--line);
  border-radius:10px;background:#F8FAFC;padding:12px;font-weight:900;
  color:var(--text);
}

@media (max-width: 1024px){
  .wrap{padding:10px;}
  .search{min-width:0;width:100%;}
  .topbar{flex-direction:column;align-items:stretch;}
  .detailGrid{grid-template-columns:1fr;}
  table{min-width:920px;}
  .mainWrap{ margin-left:0; width:100vw; max-width:100vw; }
}

  </style>
</head>
<body>

<main class="mainWrap" id="mainWrap">
  <div class="wrap">
    <?php if ($mode === 'detail' && $selected): ?>
      <!-- ✅ DETAY: sadece detay ekranı -->
      <div class="panel">
        <div class="topbar">
          <div class="flex flex-col gap-1">
            <div class="title"><?= h($selected['order_no']) ?> Nolu Sipariş Detayı</div>
            <div class="subtle">Sipariş sahibinin tüm bilgileri ve ürün detayları</div>
          </div>

          <div class="flex items-center gap-2">
            <a class="btn" href="?view=list<?= $q!=='' ? '&q='.urlencode($q) : '' ?>">
              <i data-lucide="arrow-left" class="w-4 h-4"></i> Siparişlere Dön
            </a>

            <form method="post" class="m-0">
              <input type="hidden" name="action" value="print">
              <button class="btn gray" type="submit">
                <i data-lucide="printer" class="w-4 h-4"></i> Yazdır
              </button>
            </form>
          </div>
        </div>

        <?php if ($flash): ?>
          <div class="flash"><?= h($flash) ?></div>
        <?php endif; ?>

        <?php
          [$sbg,$stx,$sbd] = status_style((string)$selected['status']);
          $d = $selected['detail'] ?? [];
        ?>

        <div class="detailGrid">
          <!-- SOL: DURUM / İŞLEM -->
          <div class="card">
            <div class="cardHead">
              <span>Sipariş Durumu</span>
              <form method="post" class="m-0">
                <input type="hidden" name="action" value="delete">
                <button class="pill red" type="submit" onclick="return confirm('Silinsin mi? (demo)')">
                  <i data-lucide="trash-2" class="w-4 h-4"></i> Sil
                </button>
              </form>
            </div>
            <div class="cardBody">
              <div class="mb-2">
                <span class="statusBadge" style="background:<?=h($sbg)?>;color:<?=h($stx)?>;border-color:<?=h($sbd)?>;">
                  <?= h(status_text((string)$selected['status'])) ?>
                </span>
              </div>

              <form method="post">
                <input type="hidden" name="action" value="save_status">

                <select class="select" name="status">
                  <option value="kargoya_verildi" <?= $selected['status']==='kargoya_verildi'?'selected':'' ?>>Ürünler Kargoya Verildi</option>
                  <option value="hazirlaniyor" <?= $selected['status']==='hazirlaniyor'?'selected':'' ?>>Hazırlanıyor</option>
                  <option value="beklemede" <?= $selected['status']==='beklemede'?'selected':'' ?>>Beklemede</option>
                  <option value="tamamlandi" <?= $selected['status']==='tamamlandi'?'selected':'' ?>>Tamamlandı</option>
                  <option value="iptal" <?= $selected['status']==='iptal'?'selected':'' ?>>İptal</option>
                </select>

                <div class="checkline">
                  <input type="checkbox" id="sms" name="notify_sms" />
                  <label for="sms">SMS</label>

                  <input type="checkbox" id="mail" name="notify_mail" class="ml-3" />
                  <label for="mail">E-Posta</label>

                  <input type="checkbox" id="site" name="notify_site" class="ml-3" />
                  <label for="site">Site içi Bildirim</label>
                </div>

                <div class="mt-3 miniBtns">
                  <button class="pill blue" type="submit">
                    <i data-lucide="save" class="w-4 h-4"></i> Kaydet
                  </button>

                  <!-- ✅ Detayda logo küçük (18px) -->
                  <button class="pill gray" type="button"
                          onclick="window.open('<?= h(($selected['kargonomi_url'] ?: $kargonomiBaseUrl)) ?>','_blank')">
                    <img src="<?= h($kargonomiIconUrl) ?>" alt="kargonomi" />
                    Kargonomi
                  </button>

                  <button class="pill" type="button" onclick="location.href='mesajlar.php?user=<?= urlencode($selected['customer']) ?>'">
                    <i data-lucide="message-circle" class="w-4 h-4"></i> Müşteriye Yaz
                  </button>
                </div>
              </form>

              <div class="noteBox">
                <div class="k">Not</div>
                <div class="v">Üyeler siparişlerini dilerse iptal edebilir. (demo metin)</div>
                <div class="checkline">
                  <input type="checkbox" id="cant_cancel" />
                  <label for="cant_cancel">Üye, Bu Siparişi İptal Edemesin</label>
                </div>
              </div>
            </div>
          </div>

          <!-- SAĞ: SİPARİŞ BİLGİLERİ -->
          <div class="card">
            <div class="cardHead">
              <span>Sipariş Bilgileri</span>
              <div class="miniBtns">
                <button class="pill blue" type="button" onclick="window.open('<?= h((string)($d['invoice_download_url'] ?? '#')) ?>','_blank')">
                  <i data-lucide="file-down" class="w-4 h-4"></i> E-Faturayı İndir
                </button>
                <button class="pill red" type="button" onclick="alert('Kaldır (demo)')">
                  <i data-lucide="x" class="w-4 h-4"></i> Kaldır
                </button>
              </div>
            </div>
            <div class="cardBody">
              <div class="kvRow"><div class="k">Sipariş No</div><div class="v"><?= h($selected['order_no']) ?></div></div>
              <div class="kvRow"><div class="k">Sipariş Tarihi</div><div class="v"><?= h(dt_tr((string)$selected['date'])) ?></div></div>
              <div class="kvRow"><div class="k">Sipariş Sahibi</div><div class="v"><?= h((string)$selected['customer']) ?></div></div>
              <div class="kvRow"><div class="k">Ödeme Yöntemi</div><div class="v"><?= h((string)($d['payment'] ?? $selected['pay_method'])) ?></div></div>
              <div class="kvRow"><div class="k">İşlem IP Adresi</div><div class="v"><?= h((string)($d['ip'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Sipariş Kanalı</div><div class="v"><?= h((string)($d['channel'] ?? '—')) ?></div></div>
            </div>
          </div>

          <!-- TESLİMAT / FATURA -->
          <div class="card">
            <div class="cardHead"><span>Teslimat Adresi</span></div>
            <div class="cardBody">
              <?php $ad = $d['addresses']['delivery'] ?? []; ?>
              <div class="kvRow"><div class="k">Ad Soyad</div><div class="v"><?= h((string)($ad['name'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">TC Kimlik</div><div class="v"><?= h((string)($ad['tc'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Telefon</div><div class="v"><?= h((string)($ad['phone'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">E-Posta</div><div class="v"><?= h((string)($ad['email'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Posta Kodu</div><div class="v"><?= h((string)($ad['zip'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Adres</div><div class="v"><?= h((string)($ad['address'] ?? '—')) ?></div></div>
            </div>
          </div>

          <div class="card">
            <div class="cardHead"><span>Fatura Adresi</span></div>
            <div class="cardBody">
              <?php $af = $d['addresses']['invoice'] ?? []; ?>
              <div class="kvRow"><div class="k">Ad Soyad</div><div class="v"><?= h((string)($af['name'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">TC Kimlik</div><div class="v"><?= h((string)($af['tc'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Telefon</div><div class="v"><?= h((string)($af['phone'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">E-Posta</div><div class="v"><?= h((string)($af['email'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Posta Kodu</div><div class="v"><?= h((string)($af['zip'] ?? '—')) ?></div></div>
              <div class="kvRow"><div class="k">Adres</div><div class="v"><?= h((string)($af['address'] ?? '—')) ?></div></div>
            </div>
          </div>

          <!-- MÜŞTERİ NOTU -->
          <div class="card" style="grid-column:1 / -1;">
            <div class="cardHead"><span>Müşteri Notu</span></div>
            <div class="cardBody">
              <div class="v"><?= h((string)($d['customer_note'] ?? 'Müşteri siparişi için not yazmamış.')) ?></div>
            </div>
          </div>

          <!-- ÜRÜN LİSTESİ -->
          <div class="card" style="grid-column:1 / -1;">
            <div class="cardHead" style="background:#fff;">
              <span>Sipariş Edilen Ürün Listesi (<?= isset($d['items']) ? count((array)$d['items']) : 0 ?>)</span>
              <button class="pill" type="button" onclick="alert('Stokları geri ekle (demo)')">
                <i data-lucide="rotate-ccw" class="w-4 h-4"></i> Stokları Geri Ekle
              </button>
            </div>

            <div class="cardBody" style="padding:0;">
              <table class="itemsTable">
                <thead>
                  <tr>
                    <th>Ürün</th>
                    <th>Durum</th>
                    <th style="text-align:right;">Birim</th>
                    <th style="text-align:right;">KDV</th>
                    <th style="text-align:center;">Adet</th>
                    <th style="text-align:right;">Toplam</th>
                    <th style="text-align:right;">Kargo</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                    $sumTotal = 0.0;
                    foreach ((array)($d['items'] ?? []) as $it):
                      $sumTotal += (float)($it['line_total'] ?? 0);
                  ?>
                    <tr>
                      <td>
                        <div class="itemLine">
                          <img class="itemImg" src="<?= h((string)($it['img'] ?? $defaultProductImg)) ?>" alt="ürün">
                          <div>
                            <div style="font-weight:950;"><?= h((string)($it['name'] ?? '—')) ?></div>
                            <div class="muted" style="margin-top:4px;"><?= h((string)($it['variant'] ?? '—')) ?></div>
                          </div>
                        </div>
                      </td>
                      <td><?= h((string)($it['status'] ?? '—')) ?></td>
                      <td style="text-align:right;"><?= h(money_tr((float)($it['unit'] ?? 0))) ?> <?= h((string)$selected['currency']) ?></td>
                      <td style="text-align:right;"><?= h(money_tr((float)($it['vat'] ?? 0))) ?> <?= h((string)$selected['currency']) ?></td>
                      <td style="text-align:center;"><?= (int)($it['qty'] ?? 0) ?></td>
                      <td style="text-align:right;font-weight:950;"><?= h(money_tr((float)($it['line_total'] ?? 0))) ?> <?= h((string)$selected['currency']) ?></td>
                      <td style="text-align:right;"><?= h(money_tr((float)($it['shipping'] ?? 0))) ?> <?= h((string)$selected['currency']) ?></td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>

              <div class="sumRow">
                <span>Genel Toplam</span>
                <span><?= h(money_tr((float)$sumTotal)) ?> <?= h((string)$selected['currency']) ?></span>
              </div>
            </div>
          </div>

        </div>
      </div>

    <?php else: ?>
      <!-- ✅ LİSTE: sadece siparişler -->
      <div class="panel">
        <div class="topbar">
          <div class="flex flex-col gap-1">
            <div class="title">Siparişler</div>
            <div class="subtle">Ürün görseliyle beraber sipariş listesi</div>
          </div>

          <form method="get" class="flex items-center gap-2">
            <input type="hidden" name="view" value="list">
            <div class="search">
              <i data-lucide="search" class="w-4 h-4" style="color:var(--muted)"></i>
              <input name="q" value="<?= h($q) ?>" placeholder="Sipariş No / Müşteri" />
            </div>
            <button class="btn" type="submit">
              <i data-lucide="filter" class="w-4 h-4"></i> Ara
            </button>
          </form>
        </div>

        <div class="tableWrap">
          <table>
            <thead>
              <tr>
                <th class="chk"><input type="checkbox" onclick="toggleAll(this)"></th>
                <th>Ürün</th>
                <th>Sipariş No</th>
                <th>Sipariş Sahibi</th>
                <th>Ödeme Yöntemi</th>
                <th>Toplam Tutar</th>
                <th>Sip.Tarihi</th>
                <th>Sipariş Durumu</th>
                <th style="text-align:right;">İşlem</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($filtered)): ?>
                <tr>
                  <td colspan="9" style="padding:16px;color:var(--muted);font-weight:900;">Sonuç bulunamadı.</td>
                </tr>
              <?php else: ?>
                <?php foreach ($filtered as $o): ?>
                  <?php
                    [$bg,$tx,$bd] = status_style((string)$o['status']);
                    $img = (string)($o['product_img'] ?? '');
                    if ($img === '') $img = $defaultProductImg;
                    $detailHref = '?view=detail&id='.(int)$o['id'].($q!==''?'&q='.urlencode($q):'');
                    $kargoUrl = (string)($o['kargonomi_url'] ?? '');
                    if ($kargoUrl === '') $kargoUrl = $kargonomiBaseUrl;
                  ?>
                  <tr>
                    <td class="chk"><input type="checkbox" class="rowchk"></td>

                    <td>
                      <div class="productCell">
                        <img class="pimg" src="<?= h($img) ?>" alt="ürün">
                        <div>
                          <div class="muted">Görsel URL’sini sen gir</div>
                          <div style="font-weight:950; font-size:12px; color:#0f172a;">Ürün görseli</div>
                        </div>
                      </div>
                    </td>

                    <td class="orderNo"><?= h((string)$o['order_no']) ?></td>

                    <td>
                      <div class="avatarName">
                        <span class="avatarDot"><i data-lucide="user" class="w-4 h-4" style="color:#64748B"></i></span>
                        <span style="font-weight:950;"><?= h((string)$o['customer']) ?></span>
                      </div>
                    </td>

                    <td><?= h((string)$o['pay_method']) ?></td>

                    <td class="price"><?= h(money_tr((float)$o['total'])) ?> <?= h((string)$o['currency']) ?></td>

                    <td><?= h(dt_tr((string)$o['date'])) ?></td>

                    <td>
                      <span class="statusBadge" style="background:<?=h($bg)?>;color:<?=h($tx)?>;border-color:<?=h($bd)?>;">
                        <?= h(status_text((string)$o['status'])) ?>
                      </span>
                    </td>

                    <td>
                      <div class="actions">
                        <!-- ✅ KARGONOMI: sarı yok + görsel kutuyu kaplar -->
                        <button class="act kargonomi" type="button"
                                title="Kargonomi"
                                onclick="window.open('<?= h($kargoUrl) ?>','_blank')">
                          <img src="<?= h($kargonomiIconUrl) ?>" alt="kargonomi">
                        </button>

                        <button class="act soft" type="button" title="Yenile (demo)" onclick="alert('Yenile (demo)')">
                          <i data-lucide="refresh-ccw" class="w-5 h-5"></i>
                        </button>

                        <form method="post" class="m-0">
                          <input type="hidden" name="action" value="print">
                          <button class="act dark" type="submit" title="Yazdır (demo)">
                            <i data-lucide="printer" class="w-5 h-5"></i>
                          </button>
                        </form>

                        <button class="act blue" type="button"
                                title="Sipariş Detayları"
                                onclick="location.href='<?= h($detailHref) ?>'">
                          <i data-lucide="eye" class="w-5 h-5"></i>
                        </button>

                        <form method="post" class="m-0">
                          <input type="hidden" name="action" value="delete">
                          <button class="act red" type="submit" title="Sil (demo)" onclick="return confirm('Silinsin mi? (demo)')">
                            <i data-lucide="trash-2" class="w-5 h-5"></i>
                          </button>
                        </form>
                      </div>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    <?php endif; ?>
  </div>
</main>

<script>
  function applySidebarGap(){
    // Sidebar'ı olabildiğince sağlam yakala
    const pick = (sels) => {
      for (const s of sels){
        const el = document.querySelector(s);
        if (el) return el;
      }
      return null;
    };

    // Muhtemel sidebar selector'ları
    const sidebar = pick(['#sidebar', '.sidebar', 'aside.sidebar', 'nav.sidebar', 'aside', 'nav']);

    let w = 0;
    if (sidebar && window.innerWidth >= 1025) {
      const r = sidebar.getBoundingClientRect();
      const st = getComputedStyle(sidebar);
      // görünür ve solda duran bir şeyse
      const visible = st.display !== 'none' && st.visibility !== 'hidden' && r.width > 56 && r.height > 200 && r.left <= 12;
      if (visible) w = Math.round(r.width);
    }
    document.documentElement.style.setProperty('--sbw', w + 'px');
  }

  window.addEventListener('DOMContentLoaded', () => {
    if (window.lucide) window.lucide.createIcons();
    applySidebarGap();
    window.addEventListener('resize', applySidebarGap);

    // Sidebar aç/kapa gibi durumlarda da toparlasın
    document.addEventListener('click', () => setTimeout(applySidebarGap, 220));
  });

  function toggleAll(master){
    document.querySelectorAll('.rowchk').forEach(ch => ch.checked = master.checked);
  }
</script>

</body>
</html>
