<?php
require_once 'config.php';

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

try {
    // 1. Today's Revenue
    $stmt = $pdo->prepare("SELECT SUM(grand_total) as revenue FROM transactions WHERE DATE(created_at) = ?");
    $stmt->execute([$today]);
    $todayRevenue = $stmt->fetch()['revenue'] ?? 0.0;

    // 2. Today's Transactions
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM transactions WHERE DATE(created_at) = ?");
    $stmt->execute([$today]);
    $todayTxCount = $stmt->fetch()['count'] ?? 0;

    // 3. Low Stock Items Count (Threshold from settings)
    $stmt = $pdo->query("SELECT low_stock_threshold FROM settings WHERE id = 1");
    $threshold = $stmt->fetch()['low_stock_threshold'] ?? 10;
    
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM products WHERE stock <= ?");
    $stmt->execute([$threshold]);
    $lowStockCount = $stmt->fetch()['count'] ?? 0;

    // 4. Total Active Receivables (Piutang)
    $stmt = $pdo->query("SELECT SUM(total_amount - paid_amount) as total FROM receivables WHERE status != 'paid'");
    $receivablesTotal = $stmt->fetch()['total'] ?? 0.0;

    // 5. Fetch low stock products
    $stmt = $pdo->prepare("
        SELECT p.name, p.stock, p.unit, c.name as category 
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE p.stock <= ? 
        ORDER BY p.stock ASC 
        LIMIT 5
    ");
    $stmt->execute([$threshold]);
    $lowStockProducts = $stmt->fetchAll();

    // 6. Fetch recent transactions
    $stmt = $pdo->query("
        SELECT t.id, t.invoice_no, u.name as cashier_name, t.grand_total, t.payment_type, t.status, t.created_at 
        FROM transactions t 
        JOIN users u ON t.user_id = u.id 
        ORDER BY t.created_at DESC 
        LIMIT 10
    ");
    $recentTransactions = $stmt->fetchAll();

} catch (PDOException $e) {
    die("Database query error: " . $e->getMessage());
}

// Format Rupiah helper
function formatRupiah($amount) {
    return 'Rp ' . number_format($amount, 0, ',', '.');
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Owner Dashboard - Toko Barokah</title>
    
    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Feather Icons for Clean UI -->
    <script src="https://unpkg.com/feather-icons"></script>

    <!-- Custom Premium Styling -->
    <style>
        :root {
            --bg-color: #0f172a;
            --surface-color: rgba(30, 41, 59, 0.7);
            --border-color: rgba(255, 255, 255, 0.08);
            --primary: #6366f1;
            --primary-glow: rgba(99, 102, 241, 0.2);
            --accent: #a855f7;
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Outfit', sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        body {
            background-color: var(--bg-color);
            background-image: 
                radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.15) 0px, transparent 50%),
                radial-gradient(at 100% 100%, rgba(168, 85, 247, 0.1) 0px, transparent 50%);
            background-attachment: fixed;
            color: var(--text-main);
            min-height: 100vh;
            padding: 2rem 1.5rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* Header section */
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2.5rem;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 1.5rem;
        }

        .header-title h1 {
            font-size: 2.2rem;
            font-weight: 800;
            background: linear-gradient(135deg, #fff 30%, #a855f7 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            letter-spacing: -1px;
        }

        .header-title p {
            color: var(--text-muted);
            font-size: 0.95rem;
            margin-top: 0.25rem;
        }

        .live-badge {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            background: rgba(16, 185, 129, 0.1);
            border: 1px solid rgba(16, 185, 129, 0.2);
            color: var(--success);
            padding: 0.5rem 1rem;
            border-radius: 9999px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .pulse-dot {
            width: 8px;
            height: 8px;
            background-color: var(--success);
            border-radius: 50%;
            animation: pulse 1.8s infinite;
        }

        @keyframes pulse {
            0% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
            70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(16, 185, 129, 0); }
            100% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2.5rem;
        }

        .card {
            background: var(--surface-color);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid var(--border-color);
            border-radius: 1.25rem;
            padding: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1.25rem;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, rgba(255,255,255,0.05) 0%, transparent 100%);
            pointer-events: none;
        }

        .card:hover {
            transform: translateY(-4px);
            border-color: rgba(99, 102, 241, 0.3);
            box-shadow: 0 12px 20px -10px var(--primary-glow);
        }

        .card-icon {
            width: 3.5rem;
            height: 3.5rem;
            border-radius: 1rem;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(255, 255, 255, 0.03);
            border: 1px solid var(--border-color);
            color: var(--primary);
        }

        .card-revenue .card-icon { color: var(--success); background: rgba(16, 185, 129, 0.05); }
        .card-tx .card-icon { color: var(--primary); background: rgba(99, 102, 241, 0.05); }
        .card-stock .card-icon { color: var(--danger); background: rgba(239, 68, 68, 0.05); }
        .card-receivable .card-icon { color: var(--warning); background: rgba(245, 158, 11, 0.05); }

        .card-content h3 {
            font-size: 0.85rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: var(--text-muted);
            margin-bottom: 0.25rem;
        }

        .card-content p {
            font-size: 1.6rem;
            font-weight: 700;
            color: var(--text-main);
        }

        /* Content Sections */
        .dashboard-body {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 1.5rem;
        }

        @media (max-width: 900px) {
            .dashboard-body {
                grid-template-columns: 1fr;
            }
        }

        .section-panel {
            background: var(--surface-color);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid var(--border-color);
            border-radius: 1.5rem;
            padding: 1.75rem;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .section-header h2 {
            font-size: 1.25rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        /* Custom Table design */
        .table-container {
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
        }

        th {
            padding: 0.75rem 1rem;
            color: var(--text-muted);
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 1px solid var(--border-color);
        }

        td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.03);
            font-size: 0.9rem;
        }

        tr:last-child td {
            border-bottom: none;
        }

        tr:hover td {
            background: rgba(255, 255, 255, 0.01);
            color: #fff;
        }

        .invoice-link {
            color: var(--primary);
            text-decoration: none;
            font-weight: 600;
            cursor: pointer;
        }

        .invoice-link:hover {
            text-decoration: underline;
        }

        .badge {
            display: inline-block;
            padding: 0.25rem 0.6rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .badge-cash { background: rgba(16, 185, 129, 0.1); color: var(--success); border: 1px solid rgba(16, 185, 129, 0.2); }
        .badge-piutang { background: rgba(245, 158, 11, 0.1); color: var(--warning); border: 1px solid rgba(245, 158, 11, 0.2); }
        .badge-paid { background: rgba(16, 185, 129, 0.1); color: var(--success); }
        .badge-unpaid { background: rgba(239, 68, 68, 0.1); color: var(--danger); }

        /* Stock list */
        .stock-list {
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        .stock-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.75rem 1rem;
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid var(--border-color);
            border-radius: 0.75rem;
        }

        .stock-item-info h4 {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 0.15rem;
        }

        .stock-item-info p {
            font-size: 0.75rem;
            color: var(--text-muted);
        }

        .stock-badge {
            font-size: 0.8rem;
            font-weight: 700;
            padding: 0.35rem 0.75rem;
            border-radius: 0.5rem;
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            border: 1px solid rgba(239, 68, 68, 0.15);
        }

        .stock-badge.ok {
            background: rgba(245, 158, 11, 0.1);
            color: var(--warning);
            border: 1px solid rgba(245, 158, 11, 0.15);
        }

        /* Modal Details */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(15, 23, 42, 0.85);
            backdrop-filter: blur(8px);
            justify-content: center;
            align-items: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .modal.show {
            display: flex;
            opacity: 1;
        }

        .modal-content {
            background: #1e293b;
            border: 1px solid var(--border-color);
            width: 100%;
            max-width: 550px;
            border-radius: 1.5rem;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            transform: scale(0.95);
            transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
        }

        .modal.show .modal-content {
            transform: scale(1);
        }

        .modal-header {
            background: rgba(255, 255, 255, 0.02);
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 1.1rem;
            font-weight: 700;
        }

        .close-btn {
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            transition: color 0.2s;
        }

        .close-btn:hover {
            color: var(--danger);
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-summary-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 1rem;
            margin-bottom: 1.5rem;
            background: rgba(255, 255, 255, 0.01);
            padding: 1rem;
            border-radius: 0.75rem;
            border: 1px solid var(--border-color);
        }

        .summary-label {
            font-size: 0.75rem;
            color: var(--text-muted);
            text-transform: uppercase;
        }

        .summary-val {
            font-size: 0.95rem;
            font-weight: 600;
            color: var(--text-main);
            margin-top: 0.15rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Dashboard Header -->
        <header>
            <div class="header-title">
                <h1>Toko Barokah</h1>
                <p>Owner Monitoring Dashboard • Real-time Cloud Data</p>
            </div>
            <div class="live-badge">
                <div class="pulse-dot"></div>
                LIVE DATABASE
            </div>
        </header>

        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="card card-revenue">
                <div class="card-icon"><i data-feather="dollar-sign"></i></div>
                <div class="card-content">
                    <h3>Omset Hari Ini</h3>
                    <p><?php echo formatRupiah($todayRevenue); ?></p>
                </div>
            </div>
            
            <div class="card card-tx">
                <div class="card-icon"><i data-feather="shopping-bag"></i></div>
                <div class="card-content">
                    <h3>Transaksi Hari Ini</h3>
                    <p><?php echo $todayTxCount; ?> sales</p>
                </div>
            </div>

            <div class="card card-stock">
                <div class="card-icon"><i data-feather="alert-triangle"></i></div>
                <div class="card-content">
                    <h3>Stok Menipis</h3>
                    <p><?php echo $lowStockCount; ?> item</p>
                </div>
            </div>

            <div class="card card-receivable">
                <div class="card-icon"><i data-feather="credit-card"></i></div>
                <div class="card-content">
                    <h3>Total Piutang</h3>
                    <p><?php echo formatRupiah($receivablesTotal); ?></p>
                </div>
            </div>
        </div>

        <!-- Dashboard Body Layout -->
        <div class="dashboard-body">
            <!-- Left Panel: Recent Transactions -->
            <div class="section-panel">
                <div class="section-header">
                    <h2><i data-feather="clock" style="color: var(--primary)"></i> Transaksi Terakhir</h2>
                </div>
                
                <div class="table-container">
                    <table>
                        <thead>
                            <tr>
                                <th>No Invoice</th>
                                <th>Kasir</th>
                                <th>Total Belanja</th>
                                <th>Metode</th>
                                <th>Status</th>
                                <th>Waktu Transaksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentTransactions)): ?>
                                <tr>
                                    <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 2rem;">
                                        Belum ada transaksi tersinkronisasi.
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($recentTransactions as $tx): ?>
                                    <tr>
                                        <td>
                                            <span class="invoice-link" onclick="openDetailsModal(<?php echo $tx['id']; ?>, '<?php echo $tx['invoice_no']; ?>')">
                                                <?php echo $tx['invoice_no']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($tx['cashier_name']); ?></td>
                                        <td style="font-weight: 600;"><?php echo formatRupiah($tx['grand_total']); ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo strtolower($tx['payment_type']); ?>">
                                                <?php echo htmlspecialchars($tx['payment_type']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge badge-<?php echo strtolower($tx['status']); ?>">
                                                <?php echo htmlspecialchars($tx['status']); ?>
                                            </span>
                                        </td>
                                        <td style="color: var(--text-muted); font-size: 0.85rem;">
                                            <?php echo date('d M H:i', strtotime($tx['created_at'])); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Right Panel: Low Stock alerts -->
            <div class="section-panel">
                <div class="section-header">
                    <h2><i data-feather="box" style="color: var(--danger)"></i> Peringatan Stok</h2>
                </div>
                
                <div class="stock-list">
                    <?php if (empty($lowStockProducts)): ?>
                        <div style="text-align: center; color: var(--text-muted); padding: 1rem;">
                            Stok semua barang aman!
                        </div>
                    <?php else: ?>
                        <?php foreach ($lowStockProducts as $p): ?>
                            <div class="stock-item">
                                <div class="stock-item-info">
                                    <h4><?php echo htmlspecialchars($p['name']); ?></h4>
                                    <p><?php echo htmlspecialchars($p['category'] ?? 'Tanpa Kategori'); ?></p>
                                </div>
                                <span class="stock-badge <?php echo $p['stock'] > 5 ? 'ok' : ''; ?>">
                                    <?php echo $p['stock'] . ' ' . $p['unit']; ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Transaction Details Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Detail Transaksi</h3>
                <button class="close-btn" onclick="closeDetailsModal()"><i data-feather="x"></i></button>
            </div>
            <div class="modal-body">
                <div class="modal-summary-grid">
                    <div>
                        <span class="summary-label">No Invoice</span>
                        <div id="summaryInvoice" class="summary-val">-</div>
                    </div>
                    <div>
                        <span class="summary-label">Kasir</span>
                        <div id="summaryCashier" class="summary-val">-</div>
                    </div>
                    <div>
                        <span class="summary-label">Waktu</span>
                        <div id="summaryTime" class="summary-val">-</div>
                    </div>
                    <div>
                        <span class="summary-label">Metode Pembayaran</span>
                        <div id="summaryMethod" class="summary-val">-</div>
                    </div>
                </div>

                <div class="table-container" style="border: 1px solid var(--border-color); border-radius: 0.75rem; background: rgba(0,0,0,0.1);">
                    <table style="width: 100%;">
                        <thead>
                            <tr style="background: rgba(255,255,255,0.02)">
                                <th style="padding: 0.5rem 0.75rem;">Nama Produk</th>
                                <th style="text-align: right; padding: 0.5rem 0.75rem;">Harga</th>
                                <th style="text-align: center; padding: 0.5rem 0.75rem;">Qty</th>
                                <th style="text-align: right; padding: 0.5rem 0.75rem;">Subtotal</th>
                            </tr>
                        </thead>
                        <tbody id="modalItemsBody">
                            <!-- Injected dynamically via JS fetch -->
                        </tbody>
                        <tfoot>
                            <tr style="border-top: 1px solid var(--border-color); font-weight: bold; background: rgba(255,255,255,0.01)">
                                <td colspan="3" style="text-align: right; padding: 0.75rem 1rem;">Total Akhir:</td>
                                <td id="summaryGrandTotal" style="text-align: right; padding: 0.75rem 1rem; color: var(--success); font-size: 1.05rem;">Rp 0</td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Initialize Feather Icons -->
    <script>
        feather.replace();

        function openDetailsModal(txId, invoiceNo) {
            const modal = document.getElementById('detailsModal');
            
            // Set invoice header in modal
            document.getElementById('modalTitle').innerText = 'Detail Transaksi ' + invoiceNo;
            document.getElementById('summaryInvoice').innerText = invoiceNo;
            
            // Clear previous items
            const tbody = document.getElementById('modalItemsBody');
            tbody.innerHTML = '<tr><td colspan=\"4\" style=\"text-align:center; padding:1.5rem; color:var(--text-muted);\">Memuat data...</td></tr>';
            
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);

            // Fetch details from API
            fetch('api.php?action=get_dashboard_data&tx_id=' + txId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('summaryCashier').innerText = data.transaction.cashier_name;
                        document.getElementById('summaryTime').innerText = data.transaction.created_at;
                        document.getElementById('summaryMethod').innerText = data.transaction.payment_type.toUpperCase();
                        
                        // Format currency formatter helper
                        const formatCurr = (val) => 'Rp ' + Number(val).toLocaleString('id-ID');
                        document.getElementById('summaryGrandTotal').innerText = formatCurr(data.transaction.grand_total);
                        
                        // Render products table
                        tbody.innerHTML = '';
                        data.details.forEach(item => {
                            const tr = document.createElement('tr');
                            tr.innerHTML = `
                                <td style="padding: 0.75rem;">${item.product_name}</td>
                                <td style="text-align: right; padding: 0.75rem;">${formatCurr(item.price)}</td>
                                <td style="text-align: center; padding: 0.75rem;">${item.qty}</td>
                                <td style="text-align: right; padding: 0.75rem; font-weight:600;">${formatCurr(item.subtotal)}</td>
                            `;
                            tbody.appendChild(tr);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan=\"4\" style=\"text-align:center; padding:1.5rem; color:var(--danger);\">Gagal memuat detail transaksi.</td></tr>';
                    }
                })
                .catch(err => {
                    tbody.innerHTML = '<tr><td colspan=\"4\" style=\"text-align:center; padding:1.5rem; color:var(--danger);\">Kesalahan jaringan.</td></tr>';
                });
        }

        function closeDetailsModal() {
            const modal = document.getElementById('detailsModal');
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }

        // Close modal if user clicks outside content
        window.onclick = function(event) {
            const modal = document.getElementById('detailsModal');
            if (event.target == modal) {
                closeDetailsModal();
            }
        }
    </script>
</body>
</html>
