<?php
require_once __DIR__ . '/../includes/config.php';

// Set page title
$page_title = 'Dashboard';

// Get statistics
$today = date('Y-m-d');
$this_month = date('Y-m');

// Total revenue
$result = $db->query("
    SELECT SUM((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) - 
           COALESCE((SELECT (CASE WHEN d.type='percent' THEN ROUND((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) * d.value / 100) ELSE d.value END) FROM discounts d WHERE d.id = o.discount_id), 0) + 
           (CASE WHEN o.delivery_enabled THEN o.delivery_price ELSE 0 END)) as total_revenue
    FROM orders o
");
$total_revenue = ($result->fetch_assoc()['total_revenue'] ?? 0);

// Month revenue
$result = $db->query("
    SELECT SUM((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) - 
           COALESCE((SELECT (CASE WHEN d.type='percent' THEN ROUND((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) * d.value / 100) ELSE d.value END) FROM discounts d WHERE d.id = o.discount_id), 0) + 
           (CASE WHEN o.delivery_enabled THEN o.delivery_price ELSE 0 END)) as month_revenue
    FROM orders o
    WHERE DATE_FORMAT(o.order_date, '%Y-%m') = '$this_month'
");
$month_revenue = ($result->fetch_assoc()['month_revenue'] ?? 0);

// Today's revenue
$result = $db->query("
    SELECT SUM((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) - 
           COALESCE((SELECT (CASE WHEN d.type='percent' THEN ROUND((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) * d.value / 100) ELSE d.value END) FROM discounts d WHERE d.id = o.discount_id), 0) + 
           (CASE WHEN o.delivery_enabled THEN o.delivery_price ELSE 0 END)) as today_revenue
    FROM orders o
    WHERE o.order_date = '$today'
");
$today_revenue = ($result->fetch_assoc()['today_revenue'] ?? 0);

// Orders count
$result = $db->query("SELECT COUNT(*) as count FROM orders");
$total_orders = $result->fetch_assoc()['count'];

// Month orders
$result = $db->query("SELECT COUNT(*) as count FROM orders WHERE DATE_FORMAT(order_date, '%Y-%m') = '$this_month'");
$month_orders = $result->fetch_assoc()['count'];

// Today orders
$result = $db->query("SELECT COUNT(*) as count FROM orders WHERE order_date = '$today'");
$today_orders = $result->fetch_assoc()['count'];

// Delivery vs pickup
$result = $db->query("SELECT COUNT(*) as count FROM orders WHERE delivery_enabled = TRUE");
$delivery_orders = $result->fetch_assoc()['count'];

$result = $db->query("SELECT COUNT(*) as count FROM orders WHERE delivery_enabled = FALSE");
$pickup_orders = $result->fetch_assoc()['count'];

// Delivery revenue
$result = $db->query("SELECT SUM(delivery_price) as total FROM orders WHERE delivery_enabled = TRUE");
$delivery_revenue = ($result->fetch_assoc()['total'] ?? 0);

// Active products
$result = $db->query("SELECT COUNT(*) as count FROM products WHERE active = TRUE");
$active_products = $result->fetch_assoc()['count'];

// Low stock products
$result = $db->query("SELECT COUNT(*) as count FROM products WHERE stock <= min_stock AND stock > 0");
$low_stock = $result->fetch_assoc()['count'];

// Out of stock
$result = $db->query("SELECT COUNT(*) as count FROM products WHERE stock <= 0");
$out_of_stock = $result->fetch_assoc()['count'];

require_once __DIR__ . '/../includes/header.php';
?>

<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon orange">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M12 2v20M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/>
            </svg>
        </div>
        <div class="stat-label">Venituri totale</div>
        <div class="stat-value" style="color:var(--accent)"><?php echo number_format($total_revenue, 2, '.', ''); ?> lei</div>
        <div class="stat-sub"><?php echo $total_orders; ?> comenzi · livrare <?php echo number_format($delivery_revenue, 2, '.', ''); ?> lei</div>
    </div>

    <div class="stat-card">
        <div class="stat-icon green">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/>
                <rect x="9" y="3" width="6" height="4" rx="1"/>
            </svg>
        </div>
        <div class="stat-label">Luna aceasta</div>
        <div class="stat-value" style="color:var(--green)"><?php echo number_format($month_revenue, 2, '.', ''); ?> lei</div>
        <div class="stat-sub"><?php echo $month_orders; ?> comenzi în <?php echo date('Y-m'); ?></div>
    </div>

    <div class="stat-card">
        <div class="stat-icon blue">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="1" y="3" width="15" height="13" rx="2"/>
                <path d="M16 8h4l3 5v3h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/>
            </svg>
        </div>
        <div class="stat-label">Cu livrare</div>
        <div class="stat-value" style="color:var(--blue)"><?php echo $delivery_orders; ?></div>
        <div class="stat-sub"><?php echo $pickup_orders; ?> ridicare personală</div>
    </div>

    <div class="stat-card">
        <div class="stat-icon purple">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="2" y="3" width="6" height="6" rx="1"/><rect x="9" y="3" width="6" height="6" rx="1"/><rect x="16" y="3" width="6" height="6" rx="1"/>
            </svg>
        </div>
        <div class="stat-label">Produse active</div>
        <div class="stat-value" style="color:var(--purple)"><?php echo $active_products; ?></div>
        <div class="stat-sub"><?php echo $low_stock; ?> cu stoc scăzut</div>
    </div>
</div>

<div class="dash-grid">
    <div class="card">
        <div class="card-header">
            <div class="card-title">Ultimele comenzi</div>
            <a href="<?php echo APP_URL; ?>/admin/orders.php" class="btn btn-ghost btn-sm">Vezi toate →</a>
        </div>
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Client</th>
                        <th>Telefon</th>
                        <th>Total</th>
                        <th>Livrare</th>
                        <th>Status</th>
                        <th>Data</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $result = $db->query("
                        SELECT o.*, c.first_name, c.last_name, c.phone, os.name as status_name, os.color as status_color
                        FROM orders o
                        JOIN clients c ON o.client_id = c.id
                        JOIN order_statuses os ON o.status_id = os.id
                        ORDER BY o.created_at DESC
                        LIMIT 8
                    ");
                    if ($result && $result->num_rows > 0) {
                        while ($order = $result->fetch_assoc()) {
                            // Calculate order total
                            $item_result = $db->query("SELECT SUM(price * quantity) as subtotal FROM order_items WHERE order_id = " . $order['id']);
                            $subtotal = ($item_result->fetch_assoc()['subtotal'] ?? 0);
                            
                            // Apply discount
                            $discount = 0;
                            if ($order['discount_id']) {
                                $disc_result = $db->query("SELECT * FROM discounts WHERE id = " . $order['discount_id']);
                                if ($disc = $disc_result->fetch_assoc()) {
                                    $discount = $disc['type'] === 'percent' ? round($subtotal * $disc['value'] / 100) : $disc['value'];
                                }
                            }
                            
                            $delivery = $order['delivery_enabled'] ? $order['delivery_price'] : 0;
                            $total = max(0, $subtotal - $discount + $delivery);
                            $client_name = getClientName($order['first_name'], $order['last_name']);
                            $initials = strtoupper(substr($client_name, 0, 1)) . (isset($client_name[strrpos($client_name, ' ') + 1]) ? strtoupper(substr($client_name, strrpos($client_name, ' ') + 1, 1)) : '');
                            ?>
                            <tr>
                                <td style="color:var(--text3);font-size:12px">#<?php echo $order['id']; ?></td>
                                <td>
                                    <div style="display:flex;align-items:center;gap:8px">
                                        <div class="avatar" style="width:26px;height:26px;font-size:10px"><?php echo $initials; ?></div>
                                        <span style="font-weight:500"><?php echo htmlspecialchars($client_name); ?></span>
                                    </div>
                                </td>
                                <td class="td-muted"><?php echo htmlspecialchars($order['phone'] ?: '—'); ?></td>
                                <td style="font-weight:700;color:var(--accent)"><?php echo number_format($total, 2, '.', ''); ?> lei</td>
                                <td><?php echo $order['delivery_enabled'] ? '<span class="badge badge-blue">+' . number_format($order['delivery_price'], 2, '.', '') . ' lei</span>' : '<span style="color:var(--text3);font-size:12px">Ridicare</span>'; ?></td>
                                <td><span class="badge" style="background:<?php echo $order['status_color']; ?>22;color:<?php echo $order['status_color']; ?>"><span style="background:<?php echo $order['status_color']; ?>;width:5px;height:5px;border-radius:50%;display:inline-block;margin-right:4px"></span><?php echo htmlspecialchars($order['status_name']); ?></span></td>
                                <td class="td-muted"><?php echo formatDate($order['order_date']); ?></td>
                            </tr>
                            <?php
                        }
                    } else {
                        echo '<tr><td colspan="7"><div class="empty-state" style="padding:24px"><h3>Nicio comandă</h3></div></td></tr>';
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>

    <div style="display:flex;flex-direction:column;gap:14px">
        <div class="card">
            <div class="card-header">
                <div class="card-title">Stoc</div>
            </div>
            <div class="card-body" style="padding:14px 16px">
                <div style="margin-bottom:12px">
                    <div style="display:flex;justify-content:space-between;margin-bottom:3px">
                        <span style="font-size:12.5px;display:flex;align-items:center;gap:5px">
                            <span style="width:7px;height:7px;border-radius:50%;background:var(--green);display:inline-block"></span>
                            Stoc ok
                        </span>
                        <span style="font-size:11.5px;color:var(--text3)"><?php echo ($active_products - $low_stock - $out_of_stock); ?></span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width:<?php echo $active_products > 0 ? round((($active_products - $low_stock - $out_of_stock) / $active_products) * 100) : 0; ?>%;background:var(--green)"></div>
                    </div>
                </div>
                <div style="margin-bottom:12px">
                    <div style="display:flex;justify-content:space-between;margin-bottom:3px">
                        <span style="font-size:12.5px;display:flex;align-items:center;gap:5px">
                            <span style="width:7px;height:7px;border-radius:50%;background:var(--yellow);display:inline-block"></span>
                            Stoc scăzut
                        </span>
                        <span style="font-size:11.5px;color:var(--text3)"><?php echo $low_stock; ?></span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width:<?php echo $active_products > 0 ? round(($low_stock / $active_products) * 100) : 0; ?>%;background:var(--yellow)"></div>
                    </div>
                </div>
                <div>
                    <div style="display:flex;justify-content:space-between;margin-bottom:3px">
                        <span style="font-size:12.5px;display:flex;align-items:center;gap:5px">
                            <span style="width:7px;height:7px;border-radius:50%;background:var(--red);display:inline-block"></span>
                            Epuizat
                        </span>
                        <span style="font-size:11.5px;color:var(--text3)"><?php echo $out_of_stock; ?></span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width:<?php echo $active_products > 0 ? round(($out_of_stock / $active_products) * 100) : 0; ?>%;background:var(--red)"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <div class="card-title">Venituri Azi</div>
            </div>
            <div class="card-body">
                <div style="font-family:'Syne',sans-serif;font-size:32px;font-weight:700;color:var(--accent);margin-bottom:8px"><?php echo number_format($today_revenue, 2, '.', ''); ?> lei</div>
                <div style="font-size:12px;color:var(--text3)"><?php echo $today_orders; ?> comenzi astazi</div>
            </div>
        </div>
    </div>
</div>

<!-- ALERTS SECTION -->
<div class="dash-grid2" style="margin-top:22px">
    <!-- Low Stock Alerts -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">⚠️ Stoc scăzut</div>
            <a href="<?php echo APP_URL; ?>/admin/products.php" class="btn btn-ghost btn-sm">Vezi →</a>
        </div>
        <div style="max-height:300px;overflow-y:auto">
            <?php
            $result = $db->query("SELECT p.*, c.name as category_name FROM products p 
                                  JOIN categories c ON p.category_id = c.id 
                                  WHERE p.stock <= p.min_stock AND p.stock > 0 
                                  ORDER BY p.stock ASC 
                                  LIMIT 10");
            if ($result && $result->num_rows > 0) {
                while ($product = $result->fetch_assoc()) {
                    echo '<div style="padding:12px 16px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">
                        <div style="flex:1">
                            <div style="font-size:12.5px;font-weight:500">' . htmlspecialchars($product['name']) . '</div>
                            <div style="font-size:11px;color:var(--text3)">' . htmlspecialchars($product['category_name']) . '</div>
                        </div>
                        <div style="background:var(--yellow-bg);color:var(--yellow);padding:4px 8px;border-radius:4px;font-size:11px;font-weight:600">
                            Stoc: ' . $product['stock'] . '/' . $product['min_stock'] . '
                        </div>
                    </div>';
                }
            } else {
                echo '<div style="padding:32px 16px;text-align:center;color:var(--text3);font-size:13px">Nicio alertă stoc</div>';
            }
            ?>
        </div>
    </div>

    <!-- Pending Orders -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">⏳ Comenzi în așteptare</div>
            <a href="<?php echo APP_URL; ?>/admin/orders.php?status=1" class="btn btn-ghost btn-sm">Vezi →</a>
        </div>
        <div style="max-height:300px;overflow-y:auto">
            <?php
            $result = $db->query("SELECT o.*, c.first_name, c.last_name, c.phone, os.name as status_name, os.color as status_color
                                  FROM orders o
                                  JOIN clients c ON o.client_id = c.id
                                  JOIN order_statuses os ON o.status_id = os.id
                                  WHERE o.status_id = 1
                                  ORDER BY o.created_at ASC
                                  LIMIT 10");
            if ($result && $result->num_rows > 0) {
                while ($order = $result->fetch_assoc()) {
                    $client_name = getClientName($order['first_name'], $order['last_name']);
                    // Calculate total
                    $item_result = $db->query("SELECT SUM(price * quantity) as subtotal FROM order_items WHERE order_id = " . $order['id']);
                    $subtotal = ($item_result->fetch_assoc()['subtotal'] ?? 0);
                    $discount = 0;
                    if ($order['discount_id']) {
                        $disc_result = $db->query("SELECT * FROM discounts WHERE id = " . $order['discount_id']);
                        if ($disc = $disc_result->fetch_assoc()) {
                            $discount = $disc['type'] === 'percent' ? round($subtotal * $disc['value'] / 100) : $disc['value'];
                        }
                    }
                    $delivery = $order['delivery_enabled'] ? $order['delivery_price'] : 0;
                    $total = max(0, $subtotal - $discount + $delivery);
                    
                    echo '<div style="padding:12px 16px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center">
                        <div style="flex:1">
                            <div style="font-size:12.5px;font-weight:500">#' . $order['id'] . ' - ' . htmlspecialchars($client_name) . '</div>
                            <div style="font-size:11px;color:var(--text3)">' . htmlspecialchars($order['phone']) . ' · ' . date('d.m H:i', strtotime($order['created_at'])) . '</div>
                        </div>
                        <div style="background:var(--accent-bg);color:var(--accent);padding:4px 8px;border-radius:4px;font-size:11px;font-weight:600">
                            ' . number_format($total, 0) . ' lei
                        </div>
                    </div>';
                }
            } else {
                echo '<div style="padding:32px 16px;text-align:center;color:var(--text3);font-size:13px">Nicio comandă în așteptare</div>';
            }
            ?>
        </div>
    </div>
</div>

<?php
require_once __DIR__ . '/../includes/footer.php';
?>
