<?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;
}

// Update check and modal logic
if (!empty($_SESSION['show_update_prompt'])) {
    unset($_SESSION['show_update_prompt']); // Only show once
    $current_version = trim(file_get_contents('version.txt'));
    $server_url = 'https://itresources.com.pk/itr/api/get_latest_update.php';
    $response = @file_get_contents($server_url . '?current_version=' . urlencode($current_version));
    $data = @json_decode($response, true);
    if (!empty($data['update_available']) && !empty($data['updates'])) {
        $show_update_modal = true;
        $update_version = $data['updates'][0]['version'] ?? '';
    }
}

// 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);
$totalCustomerOutstanding = (float)getSingleValue($conn, "SELECT SUM(amount) AS total FROM cus_outstanding WHERE status IN ('unpaid', 'partial')", "total", 0.00);
$totalSupplierOutstanding = (float)getSingleValue($conn, "SELECT SUM(amount) AS total FROM sup_outstanding WHERE status IN ('unpaid', 'partial')", "total", 0.00);
$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);

// Cash Balance
$cash_in = (float)getSingleValue($conn, "SELECT SUM(amount) AS total FROM account_transactions WHERE account_type = 'cash'", "total", 0);
$cash_out = (float)getSingleValue($conn, "SELECT SUM(amount) AS total FROM expenses WHERE payment_method = 'cash'", "total", 0);
$net_cash = $cash_in - $cash_out;

// Bank Balances
$bank_balances = [];
$bank_result = mysqli_query($conn, "
    SELECT 
        ba.id,
        ba.account_title,
        (
            SELECT COALESCE(SUM(at.amount), 0)
            FROM account_transactions at
            WHERE at.account_id = ba.id AND at.account_type IN ('bank', 'card', 'upi')
        ) AS received,
        (
            SELECT COALESCE(SUM(e.amount), 0)
            FROM expenses e
            WHERE e.bank_account_id = ba.id AND e.payment_method = 'bank'
        ) AS spent
    FROM bank_accounts ba
    WHERE ba.is_active = 1
");

while ($row = mysqli_fetch_assoc($bank_result)) {
    $row['net_balance'] = $row['received'] - $row['spent'];
    $bank_balances[] = $row;
}





?>

<!-- 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 Customer Outstanding -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count">
                    <div class="dash-counts">
                        <h4>Rs <?= number_format($totalCustomerOutstanding, 2); ?></h4>
                        <h5>Customer Outstanding</h5>
                    </div>
                    <div class="dash-imgs">
                        <i data-feather="user"></i>
                    </div>
                </div>
            </div>

            <!-- Total Supplier Outstanding -->
            <div class="col-xl-3 col-sm-6 col-12 d-flex">
                <div class="dash-count das1">
                    <div class="dash-counts">
                        <h4>Rs <?= number_format($totalSupplierOutstanding, 2); ?></h4>
                        <h5>Supplier Outstanding</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>
<?php 
$topSellingItems = [];

$topSellingQuery = "
    SELECT 
        si.item_name,
        i.product_image,
        SUM(si.quantity) AS total_sales
    FROM sale_items si
    INNER JOIN sales s ON si.sale_id = s.id
    LEFT JOIN items i ON si.item_id = i.id
    GROUP BY si.item_name, i.product_image
    ORDER BY total_sales DESC
    LIMIT 5
";

$result = mysqli_query($conn, $topSellingQuery);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $topSellingItems[] = $row;
    }
}


?>
<!-- Charts, Top Products, and Vertical Balances -->
<div class="row">

    <!-- Chart Section -->
    <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">
                            2025
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                            <li><a href="javascript:void(0);" class="dropdown-item">2024</a></li>
                            <li><a href="javascript:void(0);" class="dropdown-item">2023</a></li>
                            <li><a href="javascript:void(0);" class="dropdown-item">2022</a></li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="sales_charts"></div>
            </div>
        </div>
    </div>

    <!-- Top Selling Products -->
    <div class="col-xl-3 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>

    <!-- Account Balances Sidebar -->
    <div class="col-xl-2 col-sm-12 col-12">
        <!-- Cash -->
        <div class="dash-count das3 mb-3">
            <div class="dash-counts">
                <h4>Rs <?= number_format($net_cash, 2) ?></h4>
                <h5>Cash Balance</h5>
            </div>
            <div class="dash-imgs">
                <i data-feather="dollar-sign"></i>
            </div>
        </div>

        <!-- Bank Balances -->
        <?php foreach ($bank_balances as $bank): ?>
            <div class="dash-count das2 mb-3">
                <div class="dash-counts">
                    <h4>Rs <?= number_format($bank['net_balance'], 2) ?></h4>
                    <h5><?= htmlspecialchars($bank['account_title']) ?></h5>
                </div>
                <div class="dash-imgs">
                    <i data-feather="credit-card"></i>
                </div>
            </div>
        <?php endforeach; ?>
    </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>
<?php if (!empty($show_update_modal)): ?>
<!-- Update Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="updateModalLabel">Pending Update Available</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p>You are currently on version <strong>v<?= htmlspecialchars($current_version) ?></strong>.<br>
        The latest version is <strong>v<?= htmlspecialchars($update_version) ?></strong>.<br>
        Would you like to update your POS?</p>
      </div>
      <div class="modal-footer">
        <a href="apply_update.php" class="btn btn-success">Update</a>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Skip</button>
      </div>
    </div>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', function() {
    var updateModal = new bootstrap.Modal(document.getElementById('updateModal'));
    updateModal.show();
  });
</script>
<?php endif; ?>
</body>
</html>
