<?php
declare(strict_types=1);
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

/**
 * seller/dashboard.php
 * - TASARIM DOKUNULMADI ✅
 * - Veriler DB'den çekilir ✅ (app/db.php -> PDO)
 * - Satıcı giriş kontrolü ✅ (require_role('seller'))
 */

require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/auth.php';

start_app_session();

/* ✅ satıcı giriş kontrol */
$u = require_role('seller');
$sellerId = (int)$u['id'];

/* ✅ Ekranda firma adı */
$firmaAdi = (string)($_SESSION['firma_adi'] ?? ($u['name'] ?? 'Satıcı'));
$_SESSION['firma_adi'] = $firmaAdi;

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

/* ✅ Ticker */
$ticker_items = [];
try {
  $st = db()->prepare("
    SELECT message
    FROM seller_ticker
    WHERE seller_id = ? AND is_active = 1
    ORDER BY sort_order ASC, id DESC
    LIMIT 20
  ");
  $st->execute([$sellerId]);
  $ticker_items = array_map(fn($r)=> (string)$r['message'], $st->fetchAll());
} catch (Throwable $e) {}

if (empty($ticker_items)) {
  $ticker_items = [
    "⚡ Yeni Özellik : Kişiselleştirilmiş Siparişler Aktif ⚡",
    "📦 Kargo Fiyatlarında Güncelleme Sağlandı📦 ",
    "Bugün bekleyen sipariş: 0",
    "Yeni kampanya: %10 Komisyon İndirimi (Sınırlı Süre)",
  ];
}

/* ✅ KPI */
$urun_toplam = 0;
$siparis_toplam = 0;
$bekleyen_toplam = 0;
$bakiye = 0.0;

try {
  $st = db()->prepare("SELECT COUNT(*) c FROM products WHERE seller_id=? AND is_deleted=0");
  $st->execute([$sellerId]);
  $urun_toplam = (int)($st->fetch()['c'] ?? 0);

  $st = db()->prepare("SELECT COUNT(*) c FROM orders WHERE seller_id=?");
  $st->execute([$sellerId]);
  $siparis_toplam = (int)($st->fetch()['c'] ?? 0);

  $st = db()->prepare("SELECT COUNT(*) c FROM orders WHERE seller_id=? AND status IN ('beklemede','hazırlanıyor')");
  $st->execute([$sellerId]);
  $bekleyen_toplam = (int)($st->fetch()['c'] ?? 0);

  $st = db()->prepare("SELECT COALESCE(SUM(total_amount),0) s FROM orders WHERE seller_id=? AND payment_status='paid'");
  $st->execute([$sellerId]);
  $bakiye = (float)($st->fetch()['s'] ?? 0);
} catch (Throwable $e) {}

/* ✅ Durumlar */
$durumlar = [];
try {
  $st = db()->prepare("
    SELECT status AS durum, COUNT(*) AS sayi
    FROM orders
    WHERE seller_id=?
    GROUP BY status
    ORDER BY sayi DESC
  ");
  $st->execute([$sellerId]);
  foreach ($st->fetchAll() as $r) {
    $durumlar[] = ['durum'=>(string)$r['durum'], 'sayi'=>(int)$r['sayi']];
  }
} catch (Throwable $e) {}

if (empty($durumlar)) {
  $durumlar = [
    ['durum' => 'hazırlanıyor', 'sayi' => 0],
    ['durum' => 'teslim',       'sayi' => 0],
  ];
}

/* ✅ Son siparişler */
$liste = [];
try {
  $st = db()->prepare("
    SELECT
      o.id,
      COALESCE(p.name, 'Silinmiş Ürün') AS urun_adi,
      COALESCE(SUM(oi.quantity), 0)     AS adet,
      o.total_amount                    AS toplam_tutar,
      o.status                          AS durum,
      o.created_at
    FROM orders o
    LEFT JOIN order_items oi ON oi.order_id = o.id
    LEFT JOIN products p ON p.id = oi.product_id
    WHERE o.seller_id = ?
    GROUP BY o.id
    ORDER BY o.created_at DESC
    LIMIT 10
  ");
  $st->execute([$sellerId]);
  foreach ($st->fetchAll() as $r) {
    $liste[] = [
      'urun_adi'     => (string)$r['urun_adi'],
      'adet'         => (int)$r['adet'],
      'toplam_tutar' => (float)$r['toplam_tutar'],
      'durum'        => (string)$r['durum'],
      'created_at'   => (string)$r['created_at'],
      'id'           => (int)$r['id'],
    ];
  }
} catch (Throwable $e) {}

/* ✅ Son 7 gün grafik */
$tarihler = [];
$siparis_sayilari = [];

try {
  $days = [];
  for ($i = 6; $i >= 0; $i--) {
    $d = (new DateTime('today'))->modify("-{$i} day");
    $key = $d->format('Y-m-d');
    $days[$key] = 0;
  }

  $st = db()->prepare("
    SELECT DATE(created_at) d, COUNT(*) c
    FROM orders
    WHERE seller_id = ?
      AND created_at >= (CURDATE() - INTERVAL 6 DAY)
    GROUP BY DATE(created_at)
  ");
  $st->execute([$sellerId]);
  foreach ($st->fetchAll() as $r) {
    $k = (string)$r['d'];
    if (isset($days[$k])) $days[$k] = (int)$r['c'];
  }

  foreach ($days as $k => $v) {
    $dt = DateTime::createFromFormat('Y-m-d', $k);
    $tarihler[] = $dt ? $dt->format('d M') : $k;
    $siparis_sayilari[] = (int)$v;
  }
} catch (Throwable $e) {
  $tarihler = ['14 Jan', '15 Jan', '16 Jan', '17 Jan', '18 Jan', '19 Jan', '20 Jan'];
  $siparis_sayilari = [4, 3, 5, 6, 3, 4, 2];
}

/* ✅ Sidebar include */
include __DIR__ . '/../app/sidebar.php';
?>
<!DOCTYPE html>
<!-- BURADAN SONRASI: SENİN TASARIMIN - DOKUNMADIM ✅ -->
<html lang="tr">
<head>
  <meta charset="UTF-8" />
  <title>Satıcı Paneli — Dashboard</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

  <style>
    :root{
      --primary: #111827;
      --primary2:#0b1220;
      --muted:   #6b7280;
      --line:    rgba(17,24,39,.14);
      --line2:   rgba(17,24,39,.10);
      --card:    #ffffff;
      --bg:      #f6f7f9;
      --soft:    rgba(17,24,39,.06);
      --radius:  14px;
      --tickerSpeed: 90;
    }
    *{ font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
    html, body { height:100%; }
    body{
      background: var(--bg);
      color:#0f172a;
      overflow-x:hidden;
      max-width:100%;
      touch-action: manipulation;
      -webkit-text-size-adjust: 100%;
    }
    .no-x{ overflow-x:hidden; max-width:100vw; }
    .content-with-sidebar{ width:100%; min-height:100dvh; }
    .dash-wrap{
      width: 100%;
      max-width: 1360px;
      margin-left: 0;
      margin-right: auto;
      padding-left: 12px;
      padding-right: 16px;
    }
    @media (min-width: 640px){
      .dash-wrap{ padding-left: 16px; padding-right: 18px; max-width: 1380px; }
    }
    @media (min-width: 1024px){
      .dash-wrap{ padding-left: 18px; padding-right: 22px; max-width: 1400px; }
    }
    @media (min-width: 1536px){
      .dash-wrap{ max-width: 1440px; }
    }
    .ticker-zone{ width:100%; overflow:hidden; position: relative; border: 0; background: transparent; box-shadow: none; border-radius: 0; padding: 0; margin: 0 0 14px 0; }
    .ticker-row{ display:flex; align-items:center; gap: 12px; white-space: nowrap; will-change: transform; transform: translate3d(0,0,0); user-select:none; }
    .ticker-item{ display:inline-flex; align-items:center; gap:10px; padding: 10px 14px; border-radius: 10px; border: 1px solid rgba(17,24,39,.12); background: rgba(255,255,255,.92); color: #111827; font-weight: 800; font-size: 13px; line-height: 1; box-shadow: 0 1px 0 rgba(0,0,0,0.02); flex: 0 0 auto; }
    .ticker-item i{ opacity:.9; }
    .ticker-h{ min-height: 56px; display:flex; align-items:center; }
    @media (min-width: 640px){ .ticker-h{ min-height: 62px; } }
    @media (min-width: 1024px){ .ticker-h{ min-height: 66px; } }
    @media (hover:hover){ .ticker-zone:hover .ticker-row{ animation-play-state: paused; } }

    .card{ background: var(--card); border-radius: var(--radius); border: 1px solid var(--line2); box-shadow: 0 2px 10px rgba(0,0,0,0.035); transition: box-shadow .2s ease, transform .2s ease, border-color .2s ease; }
    .card:hover{ box-shadow: 0 10px 26px rgba(0,0,0,0.06); border-color: var(--line); }
    .quick-action{ border: 1px solid var(--line2); background: #fff; transition: transform .2s ease, box-shadow .2s ease, border-color .2s ease; }
    .quick-action:hover{ transform: translateY(-2px); box-shadow: 0 10px 26px rgba(0,0,0,0.06); border-color: var(--primary); }
    .table-row:hover{ background:#f3f4f6; }
    .chart-wrap{ height: 280px; }
    @media (max-width: 480px){ .chart-wrap{ height: 220px; } }
    @media (max-width: 768px){ .desktop-table{ display:none !important; } .mobile-cards{ display:block !important; } }
    @media (min-width: 769px){ .desktop-table{ display:block !important; } .mobile-cards{ display:none !important; } }
    ::-webkit-scrollbar{ width:6px; height:6px; }
    ::-webkit-scrollbar-track{ background:#ececec; border-radius:10px; }
    ::-webkit-scrollbar-thumb{ background:#bdbdbd; border-radius:10px; }
    ::-webkit-scrollbar-thumb:hover{ background:#9e9e9e; }
  </style>

  <script>
    tailwind.config = {
      theme: { extend: { colors: { primary: { DEFAULT: '#111827', dark:'#0b1220' } } } }
    }
  </script>
</head>

<body class="min-h-screen no-x">
  <main class="content-with-sidebar w-full no-x">
    <div class="dash-wrap w-full py-5 sm:py-6">

      <?php $items = array_values(array_filter($ticker_items, fn($x)=>trim((string)$x)!=='')); ?>
      <?php if (!empty($items)): ?>
        <section class="ticker-zone ticker-h" aria-label="Duyurular">
          <div class="ticker-row" id="tickerRow">
            <?php foreach ($items as $txt): ?>
              <span class="ticker-item">
                <i class="fa fa-info-circle" aria-hidden="true"></i>
                <?= h($txt) ?>
              </span>
            <?php endforeach; ?>
          </div>
        </section>
      <?php endif; ?>

      <div class="mb-5 sm:mb-6">
        <h1 class="text-xl sm:text-2xl font-extrabold text-gray-900">
          Hoş geldiniz, <?= h($firmaAdi) ?>
        </h1>
        <p class="text-gray-600 mt-1 text-sm sm:text-base">Bugünkü performans ve istatistikler</p>
      </div>

      <!-- (Aşağısı senin aynı tasarımın) -->

      <!-- KPI -->
      <section class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-6 sm:mb-8">
        <?php
          $kpis = [
            ['label'=>'Toplam Ürün','val'=>(int)$urun_toplam,'icon'=>'fa-box'],
            ['label'=>'Toplam Sipariş','val'=>(int)$siparis_toplam,'icon'=>'fa-shopping-cart'],
            ['label'=>'Bekleyen','val'=>(int)$bekleyen_toplam,'icon'=>'fa-clock'],
            ['label'=>'Toplam Gelir','val'=>number_format((float)$bakiye,2,',','.').' ₺','icon'=>'fa-wallet'],
          ];
        ?>
        <?php foreach($kpis as $k): ?>
          <div class="card p-4 sm:p-5">
            <div class="flex items-center gap-4">
              <div class="w-11 h-11 sm:w-12 sm:h-12 rounded-xl"
                   style="background: rgba(17,24,39,.06); color: var(--primary); display:flex; align-items:center; justify-content:center;">
                <i class="fas <?= h($k['icon']) ?> text-lg"></i>
              </div>
              <div class="min-w-0">
                <div class="text-xs sm:text-sm text-gray-600 truncate"><?= h($k['label']) ?></div>
                <div class="text-xl sm:text-2xl font-extrabold text-gray-900 leading-tight"><?= h((string)$k['val']) ?></div>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </section>

      <!-- Grafik + hızlı erişim -->
      <section class="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6 mb-6 sm:mb-8">
        <div class="lg:col-span-2 card p-4 sm:p-6">
          <div class="flex items-start sm:items-center justify-between gap-3 mb-4 sm:mb-6">
            <div>
              <h2 class="text-base sm:text-lg font-extrabold text-gray-900">Son 7 Gün Sipariş Dağılımı</h2>
              <p class="text-xs sm:text-sm text-gray-500 mt-1">Günlük sipariş adedi</p>
            </div>
            <a href="#" class="text-sm font-semibold flex items-center whitespace-nowrap" style="color: var(--primary);">
              Detaylı Rapor <i class="fa-solid fa-arrow-right ml-1 text-xs"></i>
            </a>
          </div>

          <div class="chart-wrap">
            <canvas id="siparisChart"></canvas>
          </div>
        </div>

        <div class="card p-4 sm:p-6">
          <h2 class="text-base sm:text-lg font-extrabold text-gray-900 mb-4 sm:mb-6">Hızlı Erişim</h2>
          <div class="grid grid-cols-2 gap-3 sm:gap-4">
            <a href="../satıcı/urun-ekle.php" class="quick-action p-3 sm:p-4 rounded-xl flex flex-col items-center text-center">
              <div class="w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center mb-2 sm:mb-3"
                   style="background: rgba(17,24,39,.06); color: var(--primary);">
                <i class="fas fa-plus text-lg"></i>
              </div>
              <span class="text-xs sm:text-sm font-semibold text-gray-900">Ürün Ekle</span>
            </a>

            <a href="../satıcı/efatura-ayar.php" class="quick-action p-3 sm:p-4 rounded-xl flex flex-col items-center text-center">
              <div class="w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center mb-2 sm:mb-3"
                   style="background: rgba(17,24,39,.06); color: var(--primary);">
                <i class="fas fa-file-invoice-dollar text-lg"></i>
              </div>
              <span class="text-xs sm:text-sm font-semibold text-gray-900">Fatura</span>
            </a>

            <a href="../satıcı/kargo.php" class="quick-action p-3 sm:p-4 rounded-xl flex flex-col items-center text-center">
              <div class="w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center mb-2 sm:mb-3"
                   style="background: rgba(17,24,39,.06); color: var(--primary);">
                <i class="fas fa-truck-loading text-lg"></i>
              </div>
              <span class="text-xs sm:text-sm font-semibold text-gray-900">Kargo</span>
            </a>

            <a href="../satıcı/finans.php" class="quick-action p-3 sm:p-4 rounded-xl flex flex-col items-center text-center">
              <div class="w-11 h-11 sm:w-12 sm:h-12 rounded-full flex items-center justify-center mb-2 sm:mb-3"
                   style="background: rgba(17,24,39,.06); color: var(--primary);">
                <i class="fas fa-chart-bar text-lg"></i>
              </div>
              <span class="text-xs sm:text-sm font-semibold text-gray-900">Rapor</span>
            </a>
          </div>
        </div>
      </section>

      <!-- Durum + Son Siparişler -->
      <section class="grid grid-cols-1 lg:grid-cols-3 gap-4 lg:gap-6 mb-8">
        <div class="card p-4 sm:p-6">
          <h2 class="text-base sm:text-lg font-extrabold text-gray-900 mb-4 sm:mb-6">Sipariş Durumları</h2>

          <div class="space-y-4 sm:space-y-5">
            <?php foreach ($durumlar as $durum): ?>
              <?php
                $clrBox = match($durum['durum']) {
                  'hazırlanıyor' => 'background: rgba(17,24,39,.06); color: var(--primary); border: 1px solid rgba(17,24,39,.10);',
                  'teslim'       => 'background: rgba(34,197,94,.08); color: #166534; border: 1px solid rgba(34,197,94,.14);',
                  default        => 'background: rgba(148,163,184,.12); color: #334155; border: 1px solid rgba(148,163,184,.18);',
                };
                $icon = match($durum['durum']) {
                  'hazırlanıyor' => 'fa-cogs',
                  'teslim'       => 'fa-check-circle',
                  default        => 'fa-question',
                };
              ?>
              <div class="flex items-center justify-between gap-3">
                <div class="flex items-center min-w-0">
                  <div class="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style="<?= $clrBox ?>">
                    <i class="fa-solid <?= h($icon) ?>"></i>
                  </div>
                  <span class="ml-4 font-semibold text-gray-900 truncate"><?= h(ucfirst($durum['durum'])) ?></span>
                </div>
                <span class="text-lg sm:text-xl font-extrabold text-gray-900"><?= (int)$durum['sayi'] ?></span>
              </div>
            <?php endforeach; ?>
          </div>
        </div>

        <div class="lg:col-span-2">
          <div class="card overflow-hidden">
            <div class="px-4 sm:px-6 py-4 sm:py-5 border-b border-gray-200 flex items-start sm:items-center justify-between gap-3">
              <div>
                <h2 class="text-base sm:text-lg font-extrabold text-gray-900">Son Siparişler</h2>
                <p class="text-xs sm:text-sm text-gray-500 mt-1">En güncel siparişler listesi</p>
              </div>
              <a href="../satıcı/siparisler.php" class="text-sm font-semibold flex items-center whitespace-nowrap" style="color: var(--primary);">
                Tümünü Gör <i class="fa-solid fa-arrow-right ml-1 text-xs"></i>
              </a>
            </div>

            <div class="desktop-table">
              <div class="overflow-x-auto">
                <table class="min-w-full">
                  <thead class="bg-gray-50">
                    <tr>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Ürün</th>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Adet</th>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Toplam</th>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Durum</th>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">Tarih</th>
                      <th class="py-3 px-6 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">İşlem</th>
                    </tr>
                  </thead>

                  <tbody class="divide-y divide-gray-200">
                    <?php foreach ($liste as $siparis): ?>
                      <?php
                        $badge = match($siparis['durum']) {
                          'hazırlanıyor' => 'background: rgba(17,24,39,.06); color: var(--primary); border: 1px solid rgba(17,24,39,.10);',
                          'teslim'       => 'background: rgba(34,197,94,.08); color: #166534; border: 1px solid rgba(34,197,94,.14);',
                          default        => 'background: rgba(148,163,184,.12); color: #334155; border: 1px solid rgba(148,163,184,.18);',
                        };
                      ?>
                      <tr class="table-row">
                        <td class="py-4 px-6 text-sm font-semibold text-gray-900"><?= h($siparis['urun_adi'] ?? 'Silinmiş Ürün') ?></td>
                        <td class="py-4 px-6 text-sm text-gray-900"><?= (int)$siparis['adet'] ?></td>
                        <td class="py-4 px-6 text-sm font-semibold text-gray-900"><?= number_format((float)$siparis['toplam_tutar'], 2, ',', '.') ?> ₺</td>
                        <td class="py-4 px-6">
                          <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold" style="<?= $badge ?>">
                            <?= h(ucfirst($siparis['durum'])) ?>
                          </span>
                        </td>
                        <td class="py-4 px-6 text-sm text-gray-600"><?= date('d.m.Y', strtotime($siparis['created_at'])) ?></td>
                        <td class="py-4 px-6 text-sm">
                          <a href="siparis-detay.php?id=<?= (int)$siparis['id'] ?>" style="color: var(--primary);" class="hover:opacity-80">
                            <i class="fa-solid fa-eye"></i>
                          </a>
                        </td>
                      </tr>
                    <?php endforeach; ?>

                    <?php if (empty($liste)): ?>
                      <tr>
                        <td colspan="6" class="py-12 text-center text-gray-500">
                          <div class="flex flex-col items-center gap-3">
                            <i class="fa-solid fa-inbox text-3xl text-gray-300"></i>
                            <p class="text-gray-600">Henüz sipariş alınmamış.</p>
                          </div>
                        </td>
                      </tr>
                    <?php endif; ?>
                  </tbody>
                </table>
              </div>
            </div>

            <div class="mobile-cards p-3 sm:p-4">
              <?php if (empty($liste)): ?>
                <div class="py-10 text-center text-gray-500">
                  <i class="fa-solid fa-inbox text-3xl text-gray-300"></i>
                  <p class="text-gray-600 mt-3">Henüz sipariş alınmamış.</p>
                </div>
              <?php else: ?>
                <div class="grid grid-cols-1 gap-3">
                  <?php foreach ($liste as $siparis): ?>
                    <?php
                      $badge = match($siparis['durum']) {
                        'hazırlanıyor' => 'background: rgba(17,24,39,.06); color: var(--primary); border: 1px solid rgba(17,24,39,.10);',
                        'teslim'       => 'background: rgba(34,197,94,.08); color: #166534; border: 1px solid rgba(34,197,94,.14);',
                        default        => 'background: rgba(148,163,184,.12); color: #334155; border: 1px solid rgba(148,163,184,.18);',
                      };
                    ?>
                    <div class="card p-4">
                      <div class="flex items-start justify-between gap-3">
                        <div class="min-w-0">
                          <div class="text-sm font-extrabold text-gray-900 truncate"><?= h($siparis['urun_adi'] ?? 'Silinmiş Ürün') ?></div>
                          <div class="text-xs text-gray-500 mt-1">
                            <?= date('d.m.Y', strtotime($siparis['created_at'])) ?> • <?= (int)$siparis['adet'] ?> adet
                          </div>
                        </div>
                        <a href="siparis-detay.php?id=<?= (int)$siparis['id'] ?>" class="shrink-0" style="color: var(--primary);">
                          <i class="fa-solid fa-eye text-lg"></i>
                        </a>
                      </div>

                      <div class="mt-3 flex items-center justify-between">
                        <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold" style="<?= $badge ?>">
                          <?= h(ucfirst($siparis['durum'])) ?>
                        </span>
                        <div class="text-sm font-extrabold text-gray-900">
                          <?= number_format((float)$siparis['toplam_tutar'], 2, ',', '.') ?> ₺
                        </div>
                      </div>
                    </div>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
            </div>

          </div>
        </div>
      </section>

    </div>
  </main>

  <script>
    (function(){
      const row = document.getElementById('tickerRow');
      if(!row) return;

      const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      if(reduce) return;

      const zone = row.parentElement;
      const zoneW = zone ? zone.getBoundingClientRect().width : 0;

      let safety = 0;
      while(row.scrollWidth < zoneW * 2 && safety < 10){
        row.innerHTML += row.innerHTML;
        safety++;
      }

      let x = 0;
      let last = performance.now();
      const speed = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--tickerSpeed')) || 90;

      function loop(t){
        const dt = (t - last) / 1000;
        last = t;

        x -= speed * dt;

        const w = row.scrollWidth / 2;
        if(w > 0 && (-x) >= w) x += w;

        row.style.transform = `translate3d(${x}px,0,0)`;
        requestAnimationFrame(loop);
      }

      let paused = false;
      if(window.matchMedia && window.matchMedia('(hover:hover)').matches){
        zone.addEventListener('mouseenter', ()=> paused = true);
        zone.addEventListener('mouseleave', ()=> { paused = false; last = performance.now(); });
      }

      const raf = (t)=>{
        if(paused){ requestAnimationFrame(raf); return; }
        loop(t);
      };

      requestAnimationFrame(raf);
    })();

    (function(){
      const el = document.getElementById('siparisChart');
      if(!el) return;
      const ctx = el.getContext('2d');

      new Chart(ctx, {
        type: 'bar',
        data: {
          labels: <?= json_encode($tarihler, JSON_UNESCAPED_UNICODE) ?>,
          datasets: [{
            label: 'Sipariş',
            data: <?= json_encode(array_values($siparis_sayilari)) ?>,
            backgroundColor: 'rgba(17, 24, 39, 0.85)',
            borderColor: 'rgba(17, 24, 39, 1)',
            borderWidth: 1,
            borderRadius: 10,
            borderSkipped: false
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { display: false },
            tooltip: {
              backgroundColor: 'rgba(255,255,255,0.96)',
              titleColor: '#111827',
              bodyColor: '#111827',
              borderColor: 'rgba(17,24,39,.14)',
              borderWidth: 1
            }
          },
          scales: {
            y: { beginAtZero: true, grid: { color: 'rgba(17,24,39,0.06)' }, ticks: { color: '#6b7280' } },
            x: { grid: { display:false }, ticks: { color: '#6b7280' } }
          }
        }
      });
    })();
  </script>
</body>
</html>
