<?php
require_once '../../includes/auth_middleware.php';
require_once '../../config/database.php';
require_once '../../includes/header.php';
checkRole(['admin']);

$days = isset($_GET['period']) ? (int)$_GET['period'] : 30;

// 1. Query Ringkasan Keuangan
$stmt = $pdo->prepare("SELECT SUM(total_omzet) as omzet, SUM(total_hpp) as hpp, SUM(total_profit) as profit, SUM(discount_amount) as diskon FROM transactions WHERE transaction_date >= DATE_SUB(NOW(), INTERVAL ? DAY)");
$stmt->execute([$days]);
$summary = $stmt->fetch();

// 2. Query Grafik Tren Profit
$labels = [];
$values = [];
$chartStmt = $pdo->prepare("SELECT DATE(transaction_date) as tgl, SUM(total_profit) as harian FROM transactions WHERE transaction_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY) GROUP BY DATE(transaction_date) ORDER BY tgl ASC");
$chartStmt->execute([$days]);
$chartRows = $chartStmt->fetchAll();
foreach ($chartRows as $row) {
    $labels[] = date('d M', strtotime($row['tgl']));
    $values[] = $row['harian'];
}

// 3. Query Kehadiran Karyawan Hari Ini (Fitur Baru)
$att_stmt = $pdo->query("
    SELECT a.*, u.username 
    FROM attendance a 
    JOIN users u ON a.user_id = u.id 
    WHERE DATE(a.attendance_time) = CURDATE() 
    ORDER BY a.attendance_time DESC
");
$attendances = $att_stmt->fetchAll();

// 4. Query Stok Kritis
$stok_stmt = $pdo->query("SELECT name, stock_qty, unit, min_stock_level FROM ingredients WHERE stock_qty <= min_stock_level ORDER BY stock_qty ASC");
$critical_stock = $stok_stmt->fetchAll();
?>

<div class="container" style="max-width: 1100px;">
    <header style="margin-bottom: 2rem; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem;">
        <div>
            <h2 style="margin:0;">DASHBOARD</h2>
            <p style="color: #6b7280; margin:0;">Pantau Keuangan & SDM Kebhav Tamvan</p>
        </div>
        <select onchange="location.href='?period='+this.value" style="padding: 10px; border-radius: 8px; border: 1px solid #ddd; font-weight: bold; cursor: pointer;">
            <option value="1" <?= $days == 1 ? 'selected' : '' ?>>Hari Ini</option>
            <option value="7" <?= $days == 7 ? 'selected' : '' ?>>7 Hari Terakhir</option>
            <option value="30" <?= $days == 30 ? 'selected' : '' ?>>30 Hari Terakhir</option>
        </select>
    </header>

    <?php if (count($critical_stock) > 0): ?>
    <div style="background: #fee2e2; border-left: 5px solid #ef4444; color: #991b1b; padding: 15px; border-radius: 10px; margin-bottom: 2rem; display: flex; align-items: center; gap: 10px;">
        <span style="font-size: 1.5rem;">ðŸš¨</span>
        <div>
            <strong style="display: block;">PERINGATAN STOK MENIPIS!</strong>
            <span style="font-size: 0.9rem;">Ada <?= count($critical_stock) ?> bahan baku yang harus segera di-restock.</span>
        </div>
    </div>
    <?php endif; ?>

    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem;">
        <div class="card" style="border-left: 5px solid #3b82f6;">
            <label style="font-size: 0.75rem; font-weight: bold; color: #6b7280;">OMZET KOTOR</label>
            <div style="font-size: 1.4rem; font-weight: 800;">Rp <?= number_format($summary['omzet'] ?? 0, 0, ',', '.') ?></div>
        </div>
        <div class="card" style="border-left: 5px solid #fbbf24;">
            <label style="font-size: 0.75rem; font-weight: bold; color: #b45309;">TOTAL DISKON</label>
            <div style="font-size: 1.4rem; font-weight: 800; color: #b45309;">Rp <?= number_format($summary['diskon'] ?? 0, 0, ',', '.') ?></div>
        </div>
        <div class="card" style="border-left: 5px solid #10b981;">
            <label style="font-size: 0.75rem; font-weight: bold; color: #065f46;">PROFIT BERSIH</label>
            <div style="font-size: 1.4rem; font-weight: 800; color: #10b981;">Rp <?= number_format($summary['profit'] ?? 0, 0, ',', '.') ?></div>
        </div>
    </div>

    <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem; align-items: start;">
        
        <div>
            <div class="card" style="margin-bottom: 1.5rem;">
                <label style="font-weight: bold; margin-bottom: 15px; display: block;">TREN KEUNTUNGAN</label>
                <div style="height: 250px;"><canvas id="profitChart"></canvas></div>
            </div>

m           <div class="card">
                <label style="font-weight: bold; margin-bottom: 15px; display: block;">📸 KEHADIRAN KARYAWAN (HARI INI)</label>
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px;">
                    <?php if(count($attendances) > 0): ?>
                        <?php foreach($attendances as $abs): ?>
                        <div style="text-align: center; background: #f9fafb; padding: 10px; border-radius: 10px; border: 1px solid #eee;">
                            <div style="width: 100%; aspect-ratio: 1/1; overflow: hidden; border-radius: 8px; margin-bottom: 8px; background: #ddd;">
                                <img src="../../assets/img/attendance/<?= $abs['photo'] ?>" style="width: 100%; height: 100%; object-fit: cover;">
                            </div>
                            <div style="font-weight: bold; font-size: 0.85rem;"><?= htmlspecialchars($abs['username']) ?></div>
                            <div style="font-size: 0.7rem; color: #6b7280; margin-bottom: 5px;">
                                <?= $abs['type'] == 'in' ? '🟢 MASUK' : '🔴 KELUAR' ?><br>
                                <?= date('H:i', strtotime($abs['attendance_time'])) ?> WIB
                            </div>
                            
                            <?php if(!empty($abs['latitude']) && !empty($abs['longitude'])): ?>
                                <a href="https://www.google.com/maps?q=<?= $abs['latitude'] ?>,<?= $abs['longitude'] ?>" target="_blank" style="display: block; background: #e5e7eb; color: #2563eb; font-size: 0.7rem; font-weight: bold; padding: 5px; border-radius: 5px; text-decoration: none;">
                                    📍 Cek Google Maps
                                </a>
                            <?php else: ?>
                                <span style="font-size: 0.65rem; color: #9ca3af;">GPS Tidak Terdeteksi</span>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="grid-column: 1/-1; padding: 20px; color: #9ca3af; font-size: 0.9rem;">Belum ada aktivitas absen hari ini.</div>
                    <?php endif; ?>
                </div>
            </div>

        <div>
            <div class="card" style="margin-bottom: 1.5rem;">
                <label style="font-weight: bold; margin-bottom: 10px; display: block;">STOK MENIPIS</label>
                <?php foreach($critical_stock as $s): ?>
                <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f3f4f6;">
                    <span style="font-size: 0.85rem;"><?= $s['name'] ?></span>
                    <span style="color: #ef4444; font-weight: bold; font-size: 0.85rem;"><?= number_format($s['stock_qty'],0) ?> <?= $s['unit'] ?></span>
                </div>
                <?php endforeach; ?>
                <?php if(empty($critical_stock)): ?>
                    <p style="font-size: 0.8rem; color: #10b981;">âœ… Semua stok aman.</p>
                <?php endif; ?>
            </div>

            <div class="card">
                <label style="font-weight: bold; margin-bottom: 10px; display: block;">AKTIVITAS TERBARU</label>
                <?php
                $logsStmt = $pdo->query("SELECT t.*, u.username FROM transactions t JOIN users u ON t.user_id = u.id ORDER BY t.transaction_date DESC LIMIT 5");
                $logs = $logsStmt->fetchAll();
                foreach($logs as $l):
                ?>
                <div style="padding: 8px 0; border-bottom: 1px solid #f3f4f6; font-size: 0.8rem;">
                    <strong><?= $l['username'] ?></strong> jualan <br>
                    <span style="color: #10b981; font-weight: bold;">+Rp <?= number_format($l['total_profit'], 0, ',', '.') ?></span>
                    <span style="color: #999; font-size: 0.7rem; float: right;"><?= date('H:i', strtotime($l['transaction_date'])) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('profitChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: <?= json_encode($labels) ?>,
        datasets: [{
            label: 'Profit',
            data: <?= json_encode($values) ?>,
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            fill: true,
            tension: 0.4,
            borderWidth: 3,
            pointRadius: 4
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: { legend: { display: false } },
        scales: { y: { beginAtZero: true }, x: { grid: { display: false } } }
    }
});
</script>