<?php
session_start();
require_once('includes/vendor-security.php');
include_once('../includes/config.php');

// Get vendor stats
$vendorId = $_SESSION['vendor_id'];

// Total products
$productsQuery = mysqli_query($con, "SELECT COUNT(*) as total FROM products WHERE vendor_id='$vendorId'");
$totalProducts = mysqli_fetch_assoc($productsQuery)['total'];

// Total orders
$ordersQuery = mysqli_query($con, "SELECT COUNT(DISTINCT o.id) as total 
                                   FROM orders o 
                                   JOIN products p ON o.productId = p.id 
                                   WHERE p.vendor_id='$vendorId'");
$totalOrders = mysqli_fetch_assoc($ordersQuery)['total'];

// Pending orders
$pendingQuery = mysqli_query($con, "SELECT COUNT(DISTINCT o.id) as total 
                                    FROM orders o 
                                    JOIN products p ON o.productId = p.id 
                                    WHERE p.vendor_id='$vendorId' 
                                    AND (o.orderStatus IS NULL OR o.orderStatus = '' OR o.orderStatus = 'Packed')");
$pendingOrders = mysqli_fetch_assoc($pendingQuery)['total'];

// Total earnings
$earningsQuery = mysqli_query($con, "SELECT COALESCE(SUM(vendor_earning), 0) as total 
                                     FROM vendor_earnings 
                                     WHERE vendor_id='$vendorId'");
$totalEarnings = mysqli_fetch_assoc($earningsQuery)['total'];

// Pending payouts
$payoutQuery = mysqli_query($con, "SELECT COALESCE(SUM(vendor_earning), 0) as pending 
                                   FROM vendor_earnings 
                                   WHERE vendor_id='$vendorId' AND status='pending'");
$pendingPayouts = mysqli_fetch_assoc($payoutQuery)['pending'];
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Vendor Dashboard -
        <?php echo $VENDOR_INFO['store_name']; ?>
    </title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>

        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-tachometer-alt me-2"></i> Dashboard</h1>
                            <p>Welcome back,
                                <?php echo htmlentities($VENDOR_INFO['store_name']); ?>!
                            </p>
                        </div>
                    </div>

                    <!-- Stats Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="fas fa-boxes"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $totalProducts; ?>
                                </div>
                                <div class="stat-label">Total Products</div>
                                <a class="stat-link" href="products/manage-products.php">Manage →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon primary">
                                    <i class="fas fa-shopping-cart"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $totalOrders; ?>
                                </div>
                                <div class="stat-label">Total Orders</div>
                                <a class="stat-link" href="orders/all-orders.php">View →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon warning">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="stat-value">
                                    <?php echo $pendingOrders; ?>
                                </div>
                                <div class="stat-label">Pending Orders</div>
                                <a class="stat-link" href="orders/pending-orders.php">Process →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon info">
                                    <i class="fas fa-money-bill-wave"></i>
                                </div>
                                <div class="stat-value">₵
                                    <?php echo number_format($pendingPayouts, 2); ?>
                                </div>
                                <div class="stat-label">Pending Earnings</div>
                                <a class="stat-link" href="earnings/dashboard.php">Details →</a>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mb-4">
                        <div class="col-lg-12">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-bolt me-2"></i>Quick Actions</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-3 mb-3">
                                            <a href="products/add-product.php" class="btn btn-primary w-100">
                                                <i class="fas fa-plus me-2"></i>Add Product
                                            </a>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <a href="orders/all-orders.php" class="btn btn-outline-primary w-100">
                                                <i class="fas fa-list me-2"></i>View Orders
                                            </a>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <a href="store/profile.php" class="btn btn-outline-primary w-100">
                                                <i class="fas fa-store me-2"></i>Edit Store
                                            </a>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <a href="reports/sales-report.php" class="btn btn-outline-primary w-100">
                                                <i class="fas fa-chart-bar me-2"></i>View Reports
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Orders -->
                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-shopping-bag me-2"></i>Recent Orders</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Order #</th>
                                        <th>Product</th>
                                        <th>Customer</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $recentOrders = mysqli_query($con, "SELECT o.*, p.productName, u.email, ud.name 
                                                                        FROM orders o 
                                                                        JOIN products p ON o.productId = p.id 
                                                                        JOIN users u ON o.userId = u.id 
                                                                        LEFT JOIN user_details ud ON ud.user_id = u.id 
                                                                        WHERE p.vendor_id='$vendorId' 
                                                                        ORDER BY o.orderDate DESC 
                                                                        LIMIT 5");

                                    if (mysqli_num_rows($recentOrders) > 0) {
                                        while ($order = mysqli_fetch_array($recentOrders)) {
                                            $statusClass = 'pending';
                                            if ($order['orderStatus'] == 'Delivered')
                                                $statusClass = 'delivered';
                                            elseif ($order['orderStatus'] == 'Dispatched')
                                                $statusClass = 'dispatched';
                                            ?>
                                            <tr>
                                                <td><strong>
                                                        <?php echo $order['orderNumber']; ?>
                                                    </strong></td>
                                                <td>
                                                    <?php echo htmlentities($order['productName']); ?>
                                                </td>
                                                <td>
                                                    <?php echo htmlentities($order['name'] ?: $order['email']); ?>
                                                </td>
                                                <td><strong>₵
                                                        <?php echo number_format($order['totalAmount'], 2); ?>
                                                    </strong></td>
                                                <td><span class="status-badge <?php echo $statusClass; ?>">
                                                        <?php echo $order['orderStatus'] ?: 'Pending'; ?>
                                                    </span></td>
                                                <td>
                                                    <?php echo date('M d, Y', strtotime($order['orderDate'])); ?>
                                                </td>
                                            </tr>
                                            <?php
                                        }
                                    } else {
                                        echo '<tr><td colspan="6" class="text-center text-muted">No orders yet</td></tr>';
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../__admin__/js/scripts.js"></script>
</body>

</html>