<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_login();

$user = current_user();
$role = $user['role'];
$storeId = $user['store_id'] ?? null;

$page_title = 'Dashboard';
$active_menu = 'dashboard';

try {
    if (in_array($role, ['admin', 'production_manager'], true)) {
        $active = db()->query("
            SELECT COUNT(*)
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE ps.is_final = 0 AND ps.is_cancelled = 0
        ")->fetchColumn();

        $pendingAdmin = db()->query("SELECT COUNT(*) FROM csv_import_rows WHERE row_status = 'admin_pending'")->fetchColumn();

        $missingCard = db()->query("
            SELECT COUNT(*)
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE oi.product_card_missing = 1 AND ps.is_final = 0 AND ps.is_cancelled = 0
        ")->fetchColumn();

        $flaggedOrders = db()->query("
            SELECT COUNT(*)
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE oi.flagged_customer_id IS NOT NULL AND ps.is_final = 0 AND ps.is_cancelled = 0
        ")->fetchColumn();

        $storeOrders = db()->query("
            SELECT s.store_code, s.store_name, COUNT(oi.id) AS cnt
            FROM stores s
            LEFT JOIN order_items oi ON oi.store_id = s.id
            LEFT JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE s.is_active = 1
              AND (oi.id IS NULL OR (ps.is_final = 0 AND ps.is_cancelled = 0))
            GROUP BY s.id
            ORDER BY s.store_code
        ")->fetchAll();

        $stageCounts = db()->query("
            SELECT ps.status_name, ps.status_code, COUNT(oi.id) AS cnt
            FROM production_statuses ps
            LEFT JOIN order_items oi ON oi.current_status_id = ps.id
            WHERE ps.is_active = 1 AND ps.is_final = 0 AND ps.is_cancelled = 0
            GROUP BY ps.id
            ORDER BY ps.sort_order
        ")->fetchAll();

        $recentImports = db()->query("
            SELECT ci.*, s.store_code, u.full_name AS uploader
            FROM csv_import_logs ci
            JOIN stores s ON s.id = ci.store_id
            LEFT JOIN users u ON u.id = ci.uploaded_by
            ORDER BY ci.created_at DESC
            LIMIT 8
        ")->fetchAll();
    } elseif ($role === 'store_user' && $storeId) {
        $q = db()->prepare("
            SELECT COUNT(*)
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE oi.store_id = ? AND ps.is_final = 0 AND ps.is_cancelled = 0
        ");
        $q->execute([$storeId]);
        $myActive = $q->fetchColumn();

        $q = db()->prepare("
            SELECT COUNT(*)
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE oi.store_id = ? AND ps.is_final = 1 AND ps.is_cancelled = 0
        ");
        $q->execute([$storeId]);
        $myDone = $q->fetchColumn();

        $q = db()->prepare("
            SELECT COUNT(*)
            FROM csv_import_rows
            WHERE store_id = ? AND row_status IN ('store_pending','store_skipped','admin_rejected')
        ");
        $q->execute([$storeId]);
        $needsAttention = $q->fetchColumn();

        $q = db()->prepare("
            SELECT oi.*, ps.status_name
            FROM order_items oi
            JOIN production_statuses ps ON ps.id = oi.current_status_id
            WHERE oi.store_id = ?
            ORDER BY oi.created_at DESC
            LIMIT 10
        ");
        $q->execute([$storeId]);
        $recentOrders = $q->fetchAll();
    }
} catch (Throwable $e) {
    $dbError = $e->getMessage();
}

include __DIR__ . '/includes/layout.php';
?>

<?php if (!empty($dbError)): ?>
  <div class="alert alert-danger"><span class="alert-ico">!</span><div>Veritabanı hatası: <?= htmlspecialchars($dbError) ?></div></div>
<?php endif; ?>

<?php if (in_array($role, ['admin', 'production_manager'], true)): ?>
  <div class="ph">
    <div><h1>Dashboard</h1><p>Üretim ve CSV onay durumuna genel bakış</p></div>
    <?php if (!empty($pendingAdmin)): ?>
      <a href="admin_import_review.php" class="btn btn-primary">✓ <?= (int)$pendingAdmin ?> CSV onayı bekliyor</a>
    <?php endif; ?>
  </div>

  <div class="stats-grid">
    <div class="stat-card"><div class="stat-label">Aktif Sipariş</div><div class="stat-val"><?= (int)($active ?? 0) ?></div><div class="stat-sub">Üretimdeki</div></div>
    <div class="stat-card"><div class="stat-label">CSV Onayı</div><div class="stat-val <?= !empty($pendingAdmin) ? 'gld' : '' ?>"><?= (int)($pendingAdmin ?? 0) ?></div><div class="stat-sub">Admin onayı bekliyor</div></div>
    <div class="stat-card"><div class="stat-label">Ürün Kartı Eksik</div><div class="stat-val <?= !empty($missingCard) ? 'yl' : '' ?>"><?= (int)($missingCard ?? 0) ?></div><div class="stat-sub">Aktif siparişlerde</div></div>
    <div class="stat-card"><div class="stat-label">Sorunlu Müşteri</div><div class="stat-val <?= !empty($flaggedOrders) ? 'red' : '' ?>"><?= (int)($flaggedOrders ?? 0) ?></div><div class="stat-sub">Uyarılı sipariş</div></div>
  </div>

  <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px">
    <div class="card">
      <div class="card-header"><span class="card-title">Mağaza Bazlı Aktif</span></div>
      <div class="table-wrap"><table>
        <thead><tr><th>Mağaza</th><th>Ad</th><th class="tr">Aktif</th></tr></thead>
        <tbody>
        <?php foreach (($storeOrders ?? []) as $s): ?>
          <tr>
            <td><span class="badge bg-gld"><?= htmlspecialchars($s['store_code']) ?></span></td>
            <td class="mt"><?= htmlspecialchars($s['store_name']) ?></td>
            <td class="tr fw6"><?= (int)$s['cnt'] ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
    </div>

    <div class="card">
      <div class="card-header"><span class="card-title">Üretim Aşamaları</span></div>
      <div class="table-wrap"><table>
        <thead><tr><th>Aşama</th><th class="tr">Adet</th></tr></thead>
        <tbody>
        <?php foreach (($stageCounts ?? []) as $s): ?>
          <tr><td><?= htmlspecialchars($s['status_name']) ?></td><td class="tr fw6"><?= (int)$s['cnt'] ?></td></tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
    </div>
  </div>

  <div class="card">
    <div class="card-header"><span class="card-title">Son CSV Importları</span></div>
    <?php if (empty($recentImports)): ?>
      <div class="empty"><div class="empty-title">Henüz CSV import yok</div></div>
    <?php else: ?>
      <div class="table-wrap"><table>
        <thead><tr><th>Tarih</th><th>Mağaza</th><th>Dosya</th><th class="tr">Satır</th><th class="tr">Admin’e Giden</th><th>Yükleyen</th></tr></thead>
        <tbody>
        <?php foreach ($recentImports as $r): ?>
          <tr>
            <td class="mn"><?= htmlspecialchars($r['created_at']) ?></td>
            <td><span class="badge bg-gld"><?= htmlspecialchars($r['store_code']) ?></span></td>
            <td><?= htmlspecialchars($r['original_filename'] ?: $r['filename']) ?></td>
            <td class="tr"><?= (int)$r['total_rows'] ?></td>
            <td class="tr"><?= (int)$r['inserted_rows'] ?></td>
            <td class="mt"><?= htmlspecialchars($r['uploader'] ?: '-') ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
    <?php endif; ?>
  </div>

<?php elseif ($role === 'store_user'): ?>
  <div class="ph">
    <div><h1>Mağaza Dashboard</h1><p><?= htmlspecialchars($user['store_name'] ?? '') ?> sipariş durumunuz</p></div>
    <a href="csv_upload.php" class="btn btn-primary">CSV Yükle</a>
  </div>

  <div class="stats-grid">
    <div class="stat-card"><div class="stat-label">Aktif Sipariş</div><div class="stat-val"><?= (int)($myActive ?? 0) ?></div></div>
    <div class="stat-card"><div class="stat-label">Tamamlanan</div><div class="stat-val grn"><?= (int)($myDone ?? 0) ?></div></div>
    <div class="stat-card"><div class="stat-label">Dikkat Gereken</div><div class="stat-val <?= !empty($needsAttention) ? 'yl' : '' ?>"><?= (int)($needsAttention ?? 0) ?></div><div class="stat-sub">Bekletilen / admin reddi</div></div>
  </div>

  <div class="card">
    <div class="card-header"><span class="card-title">Son Siparişler</span></div>
    <?php if (empty($recentOrders)): ?>
      <div class="empty"><div class="empty-title">Henüz sipariş yok</div></div>
    <?php else: ?>
      <div class="table-wrap"><table>
        <thead><tr><th>Transaction</th><th>SKU</th><th>Müşteri</th><th>Durum</th><th>Tarih</th></tr></thead>
        <tbody>
        <?php foreach ($recentOrders as $r): ?>
          <tr>
            <td class="mn"><?= htmlspecialchars($r['transaction_id']) ?></td>
            <td><?= htmlspecialchars($r['sku']) ?></td>
            <td><?= htmlspecialchars($r['ship_name'] ?: $r['buyer_name'] ?: '-') ?></td>
            <td><span class="badge bg-mt"><?= htmlspecialchars($r['status_name']) ?></span></td>
            <td class="mn"><?= htmlspecialchars($r['created_at']) ?></td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table></div>
    <?php endif; ?>
  </div>
<?php else: ?>
  <div class="card"><div class="empty"><div class="empty-title">Dashboard</div><div class="empty-text">Bu rol için özel dashboard daha sonra eklenecek.</div></div></div>
<?php endif; ?>

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