<?php
// admin/index.php — bosh dashboard
declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth_stub.php';

// Agar keyin require_login() yoki require_permission() yozgan bo'lsang, shu yerda chaqirgin:
// if (function_exists('require_login')) { require_login(); }

$userName = function_exists('current_user_name') ? current_user_name() : 'Foydalanuvchi';

// Kichik helper: bitta qiymat olish
function scalar(PDO $pdo, string $sql, array $params = [], $default = 0) {
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $val = $st->fetchColumn();
    return $val === false ? $default : (float)$val;
}

$today = date('Y-m-d');

// === Bugungi statistikalar ===
$todayCodes      = scalar($pdo, "SELECT COUNT(*) FROM codes     WHERE DATE(created_at) = :d", [':d' => $today]);
$todayBlocks     = scalar($pdo, "SELECT COUNT(*) FROM blocks    WHERE DATE(created_at) = :d", [':d' => $today]);
$todaySales      = scalar($pdo, "SELECT COUNT(*) FROM sales     WHERE DATE(created_at) = :d", [':d' => $today]);
$todayCustomers  = scalar($pdo, "SELECT COUNT(*) FROM customers WHERE DATE(created_at) = :d", [':d' => $today]);

// === Umumiy statistikalar ===
$totalProducts   = scalar($pdo, "SELECT COUNT(*) FROM products WHERE is_active = 1");
$totalCategories = scalar($pdo, "SELECT COUNT(*) FROM categories WHERE is_active = 1");
$totalCustomers  = scalar($pdo, "SELECT COUNT(*) FROM customers WHERE is_active = 1");
$totalBlocks     = scalar($pdo, "SELECT COUNT(*) FROM blocks");
$totalSales      = scalar($pdo, "SELECT COUNT(*) FROM sales");
$totalCodes      = scalar($pdo, "SELECT COUNT(*) FROM codes");
$soldCodes       = scalar($pdo, "SELECT COUNT(*) FROM codes WHERE is_sold = 1");
$unsoldCodes     = max(0, $totalCodes - $soldCodes);

// Blocklar sotilgan / sotilmagan
$soldBlocks      = scalar($pdo, "SELECT COUNT(*) FROM blocks WHERE is_sale = 1");
$unsoldBlocks    = max(0, $totalBlocks - $soldBlocks);

// Sotuvlar statusi bo‘yicha
$statusStmt = $pdo->query("
    SELECT status, COUNT(*) AS cnt
    FROM sales
    GROUP BY status
");
$salesByStatus = [];
while ($row = $statusStmt->fetch(PDO::FETCH_ASSOC)) {
    $salesByStatus[$row['status']] = (int)$row['cnt'];
}

// === Oxirgi 7 kun: sotuvlar soni grafika uchun ===
$daysLabels = [];
$salesPerDay = [];

// DBdan so'rov
$fromDate = date('Y-m-d', strtotime('-6 days'));
$salesDaysStmt = $pdo->prepare("
    SELECT DATE(created_at) AS d, COUNT(*) AS cnt
    FROM sales
    WHERE DATE(created_at) >= :from
    GROUP BY DATE(created_at)
    ORDER BY d
");
$salesDaysStmt->execute([':from' => $fromDate]);
$dbSalesDays = [];
while ($r = $salesDaysStmt->fetch(PDO::FETCH_ASSOC)) {
    $dbSalesDays[$r['d']] = (int)$r['cnt'];
}

// Oxirgi 7 kunni to'ldirib chiqamiz (0 bo'lsa ham)
for ($i = 6; $i >= 0; $i--) {
    $day = date('Y-m-d', strtotime("-{$i} days"));
    $label = date('d.m', strtotime($day));
    $daysLabels[] = $label;
    $salesPerDay[] = $dbSalesDays[$day] ?? 0;
}

// === Oxirgi 5 ta sotuv ===
$lastSalesStmt = $pdo->query("
    SELECT
        s.id,
        s.created_at,
        s.status,
        s.sscc20,
        c.name AS customer_name,
        c.city,
        c.region
    FROM sales s
    JOIN customers c ON c.id = s.customer_id
    ORDER BY s.created_at DESC
    LIMIT 5
");
$lastSales = $lastSalesStmt->fetchAll(PDO::FETCH_ASSOC);

// === Oxirgi 5 ta blok ===
$lastBlocksStmt = $pdo->query("
    SELECT
        b.id,
        b.created_at,
        b.is_sale,
        b.gtin2_number,
        p.name AS product_name,
        cat.name AS category_name
    FROM blocks b
    JOIN products p   ON p.id   = b.product_id
    JOIN categories cat ON cat.id = b.category_id
    ORDER BY b.created_at DESC
    LIMIT 5
");
$lastBlocks = $lastBlocksStmt->fetchAll(PDO::FETCH_ASSOC);

// PHP -> JS uchun ma'lumotlar
$jsDaysLabels   = json_encode($daysLabels, JSON_UNESCAPED_UNICODE);
$jsSalesPerDay  = json_encode($salesPerDay, JSON_UNESCAPED_UNICODE);
$jsSoldCodes    = (int)$soldCodes;
$jsUnsoldCodes  = (int)$unsoldCodes;
$jsSoldBlocks   = (int)$soldBlocks;
$jsUnsoldBlocks = (int)$unsoldBlocks;

?>
<!DOCTYPE html>
<html lang="uz">
<head>
    <meta charset="UTF-8">
    <title>Dashboard – Markirovka tizimi</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap 5, FontAwesome, Toastr, Chart.js -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

    <style>
        body {
            background: #f3f4f6;
        }
        
        .navbar {
      background: rgba(13,71,161,0.96);
      backdrop-filter: blur(10px);
      box-shadow: 0 10px 25px rgba(15,23,42,0.35);
    }
        
         .navbar-brand, .navbar-nav .nav-link, .navbar-text {
      color: #fff !important;
    }
    .navbar-nav .nav-link {
      font-size: 0.92rem;
      opacity: 0.9;
    }
    .navbar-nav .nav-link.active {
      opacity: 1;
      font-weight: 600;
      border-bottom: 2px solid #fff;
    }

    .user-chip {
      display: inline-flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.15rem 0.75rem;
      background: rgba(15,23,42,0.2);
      border-radius: 999px;
      color: #e5edff;
      font-size: 0.85rem;
    }
    .user-avatar {
      width: 26px;
      height: 26px;
      border-radius: 999px;
      background: linear-gradient(135deg,#22c55e,#0ea5e9);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 0.9rem;
      color: #fff;
      font-weight: 700;
    }
    .user-role-badge {
      padding: 0.05rem 0.5rem;
      border-radius: 999px;
      background: rgba(15,23,42,0.35);
      font-size: 0.7rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
    }



        .page-wrapper {
            max-width: 1400px;
            margin: 15px auto 30px;
            padding: 0 10px;
        }
        .navbar-custom {
            background: linear-gradient(90deg, #0d6efd, #0b5ed7);
        }
        .stat-card {
            border-radius: 16px;
            box-shadow: 0 4px 12px rgba(15, 23, 42, 0.08);
            border: none;
        }
        .stat-card .card-body {
            padding: 16px 18px;
        }
        .stat-label {
            font-size: 0.85rem;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: .04em;
        }
        .stat-value {
            font-size: 1.6rem;
            font-weight: 700;
            color: #111827;
        }
        .stat-icon {
            font-size: 1.8rem;
            opacity: .85;
        }
        .chart-card {
            border-radius: 18px;
            box-shadow: 0 4px 14px rgba(15, 23, 42, 0.08);
        }
        .chart-wrapper {
            height: 320px;
        }
        .table-wrapper {
            max-height: 320px;
            overflow-y: auto;
        }
        .badge-status {
            text-transform: capitalize;
        }
        .badge-status.tasdiqlangan {
            background: #16a34a;
        }
        .badge-status.yangi {
            background: #0ea5e9;
        }
        .badge-status.qoralama {
            background: #facc15;
            color: #000;
        }
        .badge-status.bekor {
            background: #ef4444;
        }
        .small-muted {
            font-size: 0.8rem;
            color: #6b7280;
        }
    </style>
</head>
<body>
<?php
  $active = 'dashboard';
  require __DIR__ . '/navbar.php';
?>
<div class="page-wrapper">
    <!-- Bugungi statistika -->
    <div class="mb-3">
        <h5 class="mb-2">Bugungi ko‘rsatkichlar (<?= htmlspecialchars($today); ?>)</h5>
        <div class="row g-3">
            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <div class="stat-label">Bugun yaratilgan KM</div>
                            <div class="stat-value"><?= (int)$todayCodes; ?></div>
                        </div>
                        <div class="stat-icon text-primary">
                            <i class="fa-solid fa-barcode"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <div class="stat-label">Bugun bloklar</div>
                            <div class="stat-value"><?= (int)$todayBlocks; ?></div>
                        </div>
                        <div class="stat-icon text-success">
                            <i class="fa-solid fa-boxes-stacked"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <div class="stat-label">Bugun sotuvlar</div>
                            <div class="stat-value"><?= (int)$todaySales; ?></div>
                        </div>
                        <div class="stat-icon text-warning">
                            <i class="fa-solid fa-cart-shopping"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <div class="stat-label">Bugun yangi mijozlar</div>
                            <div class="stat-value"><?= (int)$todayCustomers; ?></div>
                        </div>
                        <div class="stat-icon text-danger">
                            <i class="fa-solid fa-user-plus"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Umumiy ko'rsatkichlar -->
    <div class="mb-3">
        <h5 class="mb-2">Umumiy ko‘rsatkichlar</h5>
        <div class="row g-3">
            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-label">Umumiy KM</div>
                        <div class="d-flex justify-content-between align-items-end">
                            <div class="stat-value"><?= (int)$totalCodes; ?></div>
                            <div class="small-muted text-end">
                                Sotilgan: <?= (int)$soldCodes; ?><br>
                                Qolgan: <?= (int)$unsoldCodes; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-label">Bloklar</div>
                        <div class="d-flex justify-content-between align-items-end">
                            <div class="stat-value"><?= (int)$totalBlocks; ?></div>
                            <div class="small-muted text-end">
                                Sotilgan: <?= (int)$soldBlocks; ?><br>
                                Qolgan: <?= (int)$unsoldBlocks; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-label">Mahsulot va kategoriya</div>
                        <div class="d-flex justify-content-between align-items-end">
                            <div class="stat-value"><?= (int)$totalProducts; ?></div>
                            <div class="small-muted text-end">
                                Kategoriyalar: <?= (int)$totalCategories; ?><br>
                                Mijozlar: <?= (int)$totalCustomers; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-6 col-md-3">
                <div class="card stat-card">
                    <div class="card-body">
                        <div class="stat-label">Sotuvlar</div>
                        <div class="d-flex justify-content-between align-items-end">
                            <div class="stat-value"><?= (int)$totalSales; ?></div>
                            <div class="small-muted text-end">
                                Yangi: <?= (int)($salesByStatus['yangi'] ?? 0); ?><br>
                                Tasdiqlangan: <?= (int)($salesByStatus['tasdiqlangan'] ?? 0); ?><br>
                                Qoralama: <?= (int)($salesByStatus['qoralama'] ?? 0); ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Grafikalar + oxirgi sotuv/bloklar -->
    <div class="row g-3 mb-3">
        <div class="col-md-6">
            <div class="card chart-card">
                <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Oxirgi 7 kun – sotuvlar soni</span>
                    <span class="small-muted">Har kun bo‘yicha</span>
                </div>
                <div class="card-body">
                    <div class="chart-wrapper">
                        <canvas id="salesPerDayChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card chart-card">
                <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Kodlar statistikasi</span>
                    <span class="small-muted">Sotilgan / sotilmagan</span>
                </div>
                <div class="card-body">
                    <div class="chart-wrapper">
                        <canvas id="codesPieChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Oxirgi sotuvlar va bloklar -->
    <div class="row g-3">
        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Oxirgi 5 ta sotuv</span>
                    <a href="../transport.php" class="small text-decoration-none">
                        Barcha sotuvlar <i class="fa-solid fa-chevron-right fa-xs ms-1"></i>
                    </a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive table-wrapper">
                        <table class="table table-sm align-middle mb-0">
                            <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Mijoz</th>
                                <th>Manzil</th>
                                <th>Status</th>
                                <th>Sana</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (!$lastSales): ?>
                                <tr><td colspan="5" class="text-center text-muted py-3">Sotuvlar topilmadi</td></tr>
                            <?php else: ?>
                                <?php foreach ($lastSales as $s): ?>
                                    <tr>
                                        <td>#<?= (int)$s['id']; ?></td>
                                        <td><?= htmlspecialchars($s['customer_name']); ?></td>
                                        <td class="small">
                                            <?= htmlspecialchars($s['region'] ?? ''); ?>,
                                            <?= htmlspecialchars($s['city'] ?? ''); ?>
                                        </td>
                                        <td>
                                            <?php
                                            $st = $s['status'];
                                            $badgeClass = 'secondary';
                                            if ($st === 'tasdiqlangan') $badgeClass = 'success';
                                            elseif ($st === 'yangi')   $badgeClass = 'info';
                                            elseif ($st === 'qoralama')$badgeClass = 'warning';
                                            elseif ($st === 'bekor')   $badgeClass = 'danger';
                                            ?>
                                            <span class="badge badge-status <?= htmlspecialchars($st); ?> bg-<?= $badgeClass; ?>">
                                                <?= htmlspecialchars($st); ?>
                                            </span>
                                        </td>
                                        <td class="small">
                                            <?= htmlspecialchars($s['created_at']); ?><br>
                                            <?php if (!empty($s['sscc20'])): ?>
                                                <span class="text-muted">SSCC: <?= htmlspecialchars($s['sscc20']); ?></span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card shadow-sm">
                <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                    <span class="fw-semibold">Oxirgi 5 ta blok</span>
                    <a href="../reports.php" class="small text-decoration-none">
                        Barcha bloklar <i class="fa-solid fa-chevron-right fa-xs ms-1"></i>
                    </a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive table-wrapper">
                        <table class="table table-sm align-middle mb-0">
                            <thead class="table-light">
                            <tr>
                                <th>ID</th>
                                <th>Mahsulot</th>
                                <th>Kategoriya</th>
                                <th>GTIN2</th>
                                <th>Status</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php if (!$lastBlocks): ?>
                                <tr><td colspan="5" class="text-center text-muted py-3">Bloklar topilmadi</td></tr>
                            <?php else: ?>
                                <?php foreach ($lastBlocks as $b): ?>
                                    <tr>
                                        <td>#<?= (int)$b['id']; ?></td>
                                        <td><?= htmlspecialchars($b['product_name']); ?></td>
                                        <td class="small"><?= htmlspecialchars($b['category_name']); ?></td>
                                        <td class="small"><?= htmlspecialchars($b['gtin2_number']); ?></td>
                                        <td>
                                            <?php if ((int)$b['is_sale'] === 1): ?>
                                                <span class="badge bg-success">Sotilgan</span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">Ochiq</span>
                                            <?php endif; ?>
                                            <div class="small text-muted">
                                                <?= htmlspecialchars($b['created_at']); ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div> <!-- row -->

    <div class="mt-3 small-muted">
        <i class="fa-regular fa-circle-question me-1"></i>
        Menyular: <code>km.php</code>, <code>products.php</code>, <code>categories.php</code>, <code>clients.php</code>, <code>reports.php</code>, <code>agg.php</code> ga havolalarni navbarda yoki yon panelda o‘zing qo‘shib chiqishing mumkin.
    </div>
</div>

<script>
    // PHP dan kelgan ma'lumotlar
    const daysLabels   = <?= $jsDaysLabels; ?>;
    const salesPerDay  = <?= $jsSalesPerDay; ?>;
    const soldCodes    = <?= $jsSoldCodes; ?>;
    const unsoldCodes  = <?= $jsUnsoldCodes; ?>;

    document.addEventListener('DOMContentLoaded', function () {
        // 1) Oxirgi 7 kunlik sotuvlar
        const ctx1 = document.getElementById('salesPerDayChart').getContext('2d');
        new Chart(ctx1, {
            type: 'line',
            data: {
                labels: daysLabels,
                datasets: [{
                    label: 'Sotuvlar soni',
                    data: salesPerDay,
                    tension: 0.3,
                    fill: false,
                    borderWidth: 2,
                    pointRadius: 4,
                }]
            },
            options: {
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { stepSize: 1 }
                    }
                }
            }
        });

        // 2) Kodlar: sotilgan / sotilmagan
        const ctx2 = document.getElementById('codesPieChart').getContext('2d');
        new Chart(ctx2, {
            type: 'doughnut',
            data: {
                labels: ['Sotilgan', 'Qolgan'],
                datasets: [{
                    data: [soldCodes, unsoldCodes],
                    borderWidth: 1,
                }]
            },
            options: {
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                cutout: '65%',
            }
        });
    });
</script>
</body>
</html>
