<?php 
session_start();

// Redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

include 'db.php';
include 'layout.php';

// Helper function
function getSingleValue($conn, $query, $key, $fallback = 0) {
    $result = mysqli_query($conn, $query);
    if ($result && $row = mysqli_fetch_assoc($result)) {
        return $row[$key] ?? $fallback;
    }
    return $fallback;
}

// Get dashboard data
$todaySalesRaw          = (float)getSingleValue($conn, "SELECT SUM(net_amount) AS today_sales FROM sales WHERE DATE(sale_date) = CURDATE()", "today_sales", 0.00);
$todayPurchaseRaw       = (float)getSingleValue($conn, "SELECT SUM(net_amount) AS today_purchase FROM purchases WHERE DATE(purchase_date) = CURDATE()", "today_purchase", 0.00);
$totalSalesRaw          = (float)getSingleValue($conn, "SELECT SUM(net_amount) AS total_sales FROM sales", "total_sales", 0.00);
$totalExpensesRaw       = (float)getSingleValue($conn, "SELECT SUM(amount) AS total_expenses FROM expenses", "total_expenses", 0.00);
$totalCustomers         = (int)getSingleValue($conn, "SELECT COUNT(*) AS total FROM customers", "total", 0);
$totalSuppliers         = (int)getSingleValue($conn, "SELECT COUNT(*) AS total FROM vendors", "total", 0);
$totalPurchaseInvoices  = (int)getSingleValue($conn, "SELECT COUNT(*) AS total FROM purchases", "total", 0);
$totalSalesInvoices     = (int)getSingleValue($conn, "SELECT COUNT(*) AS total FROM sales", "total", 0);

// Format
$todaySalesFormatted        = number_format($todaySalesRaw, 2);
$todayPurchaseFormatted     = number_format($todayPurchaseRaw, 2);
$totalSalesFormatted        = number_format($totalSalesRaw, 2);
$totalExpensesFormatted     = number_format($totalExpensesRaw, 2);




?>

<!-- Start of main wrapper -->
<div class="page-wrapper">

    <!-- Dashboard Cards -->
    <div class="content">
        <div class="row">

            <!-- Today's Sales -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-widget w-100">
                    <div class="dash-widgetimg">
                        <span><img src="assets/img/icons/dash1.svg" alt="img"></span>
                    </div>
                    <div class="dash-widgetcontent">
                        <h5><span class="counters" data-count="<?= $todaySalesRaw; ?>">$<?= $todaySalesFormatted; ?></span></h5>
                        <h6>Today's Sale</h6>
                    </div>
                </div>
            </div>

            <!-- Today's Purchases -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-widget dash1 w-100">
                    <div class="dash-widgetimg">
                        <span><img src="assets/img/icons/dash2.svg" alt="img"></span>
                    </div>
                    <div class="dash-widgetcontent">
                        <h5><span class="counters" data-count="<?= $todayPurchaseRaw; ?>">$<?= $todayPurchaseFormatted; ?></span></h5>
                        <h6>Today's Purchase</h6>
                    </div>
                </div>
            </div>

            <!-- Total Sales -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-widget dash2 w-100">
                    <div class="dash-widgetimg">
                        <span><img src="assets/img/icons/dash1.svg" alt="img"></span>
                    </div>
                    <div class="dash-widgetcontent">
                        <h5><span class="counters" data-count="<?= $totalSalesRaw; ?>">$<?= $totalSalesFormatted; ?></span></h5>
                        <h6>Total Sale Amount</h6>
                    </div>
                </div>
            </div>

            <!-- Total Expenses -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-widget dash3 w-100">
                    <div class="dash-widgetimg">
                        <span><img src="assets/img/icons/dash4.svg" alt="img"></span>
                    </div>
                    <div class="dash-widgetcontent">
                        <h5><span class="counters" data-count="<?= $totalExpensesRaw; ?>">$<?= $totalExpensesFormatted; ?></span></h5>
                        <h6>Total Expense Amount</h6>
                    </div>
                </div>
            </div>

            <!-- Total Customers -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count">
                    <div class="dash-counts">
                        <h4><?= $totalCustomers; ?></h4>
                        <h5>Customers</h5>
                    </div>
                    <div class="dash-imgs">
                        <i data-feather="user"></i>
                    </div>
                </div>
            </div>

            <!-- Total Suppliers -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count das1">
                    <div class="dash-counts">
                        <h4><?= $totalSuppliers; ?></h4>
                        <h5>Suppliers</h5>
                    </div>
                    <div class="dash-imgs">
                        <i data-feather="user-check"></i>
                    </div>
                </div>
            </div>

            <!-- Total Purchase Invoices -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count das2">
                    <div class="dash-counts">
                        <h4><?= $totalPurchaseInvoices; ?></h4>
                        <h5>Purchase Invoice</h5>
                    </div>
                    <div class="dash-imgs">
                        <img src="assets/img/icons/file-text-icon-01.svg" class="img-fluid" alt="icon">
                    </div>
                </div>
            </div>

            <!-- Total Sales Invoices -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count das3">
                    <div class="dash-counts">
                        <h4><?= $totalSalesInvoices; ?></h4>
                        <h5>Sales Invoice</h5>
                    </div>
                    <div class="dash-imgs">
                        <i data-feather="file"></i>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <!-- Charts & Top Selling -->
    <div class="row">

        <!-- Chart Card -->
        <div class="col-xl-7 col-sm-12 col-12 d-flex">
            <div class="card flex-fill">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Purchase & Sales</h5>
                    <div class="graph-sets">
                        <ul class="mb-0">
                            <li><span>Sales</span></li>
                            <li><span>Purchase</span></li>
                        </ul>
                        <div class="dropdown dropdown-wraper">
                            <button class="btn btn-light btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
                                2023
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                <li><a href="javascript:void(0);" class="dropdown-item">2023</a></li>
                                <li><a href="javascript:void(0);" class="dropdown-item">2022</a></li>
                                <li><a href="javascript:void(0);" class="dropdown-item">2021</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div id="sales_charts"></div>
                </div>
            </div>
        </div>

        <!-- Top Selling Products -->
        <?php
        $topSellingItems = [];
        $sql = "SELECT 
                    si.item_id,
                    i.name AS item_name,
                    SUM(si.quantity) AS total_sold,
                    SUM(si.total_price) AS total_sales,
                    i.product_image
                FROM 
                    sale_items si
                JOIN 
                    items i ON si.item_id = i.id
                GROUP BY 
                    si.item_id, i.name, i.product_image
                ORDER BY 
                    total_sold DESC
                LIMIT 5";
        $result = mysqli_query($conn, $sql);
        while ($row = mysqli_fetch_assoc($result)) {
            $topSellingItems[] = $row;
        }
        ?>

        <div class="col-xl-5 col-sm-12 col-12 d-flex"> 
            <div class="card flex-fill default-cover mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4 class="card-title mb-0">Top Selling Products</h4>
                </div>
                <div class="card-body">
                    <div class="table-responsive dataview">
                        <table class="table dashboard-recent-products">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Products</th>
                                    <th>Total Sales</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $i = 1; foreach ($topSellingItems as $item): ?>
                                    <?php
                                        $img = !empty($item['product_image']) ? $item['product_image'] : 'default.png';
                                        $img_path = "assets/img/products/" . htmlspecialchars($img);
                                    ?>
                                    <tr>
                                        <td><?= $i++ ?></td>
                                        <td class="productimgname">
                                            <a href="#" class="product-img">
                                                <img src="<?= $img_path ?>" alt="product" style="width: 40px; height: 40px; object-fit: cover;" onerror="this.onerror=null;this.src='assets/img/products/default.png';">
                                            </a>
                                            <a href="#"><?= htmlspecialchars($item['item_name']) ?></a>
                                        </td>
                                        <td><?= number_format($item['total_sales'], 2) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($topSellingItems)): ?>
                                    <tr><td colspan="3" class="text-center">No sales data available.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <!-- Sticky Sidebar -->
    <div class="customizer-links" id="setdata">
        <ul class="sticky-sidebar">
            <li class="sidebar-icons">
                <a href="#" class="navigation-add" data-bs-toggle="tooltip" data-bs-placement="left" data-bs-original-title="Theme">
                    <i data-feather="settings" class="feather-five"></i>
                </a>
            </li>
        </ul>
    </div>

</div>
<!-- End of page-wrapper -->

</body>
</html>
