<?php

include '../../includes/header.php';


$auth = new Auth($conn);
$auth->isBranchManager($_SESSION['user_id']);


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Notifications.php';
require_once __DIR__ . '/../../classes/Laybuy.php';
require_once __DIR__ . '/../../classes/Deposit.php';
require_once __DIR__ . '/../../classes/Expense.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../classes/CreditSales.php';

$sales = new Sales($conn);
$inventory = new Inventory($conn);
$laybuy = new Laybuy($conn);
$expense = new Expense($conn);
$deposit = new Deposit($conn);
$systemSettings = new SystemSettings();
$creditSales = new CreditSales($conn);
$profitRate = $systemSettings->profitRate();
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

$todayDate = date('Y-m-d');
$todaySalesData = $sales->getSalesByBranch($userBranchId, $todayDate, $todayDate);
$todaySales = 0;
foreach ($todaySalesData as $todaySale) {
    $todaySales += (float)($todaySale['total_price'] ?? 0);
}

$todayLaybuy = 0;
foreach ($laybuy->getBranchLayBuyStats($userBranchId, $todayDate, $todayDate) as $todayLaybuyPayment) {
    $todayLaybuy += (float)($todayLaybuyPayment['body_amount'] ?? 0);
}

// Order deposits received today (initial deposit recorded at order creation)
$stmt = $conn->prepare("SELECT o.order_number, o.item_name, o.customer_name, op.amount as amount_paid, op.payment_date as created_at
    FROM order_payments op JOIN orders o ON o.order_id = op.order_id
    WHERE o.branch_id = :b AND DATE(op.payment_date) = :t AND op.is_initial = 1");
$stmt->execute([':b' => $userBranchId, ':t' => $todayDate]);
$todayOrderDepositDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
$todayOrderDeposits = array_sum(array_column($todayOrderDepositDetails, 'amount_paid'));

// Additional/balance payments (including final payments) recorded against orders today —
// this is what add_order_payment.php writes to, so it must be sourced from order_payments,
// not orders.final_payment_amount (which is only ever set once, when an order is completed).
$stmt = $conn->prepare("SELECT o.order_number, o.item_name, o.customer_name, op.amount as final_payment_amount, op.payment_date as completed_at
    FROM order_payments op JOIN orders o ON o.order_id = op.order_id
    WHERE o.branch_id = :b AND DATE(op.payment_date) = :t AND op.is_initial = 0");
$stmt->execute([':b' => $userBranchId, ':t' => $todayDate]);
$todayOrderFinalDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
$todayOrderFinals = array_sum(array_column($todayOrderFinalDetails, 'final_payment_amount'));

// Credit sale payments received today
$stmt = $conn->prepare("SELECT cp.amount, cp.payment_method, cp.notes, cp.payment_date, ca.credit_number, ca.customer_name
    FROM credit_payments cp LEFT JOIN credit_accounts ca ON ca.credit_id = cp.credit_id
    WHERE cp.branch_id = :b AND DATE(cp.payment_date) = :t");
$stmt->execute([':b' => $userBranchId, ':t' => $todayDate]);
$todayCreditPaymentDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
$todayCreditPayments = array_sum(array_column($todayCreditPaymentDetails, 'amount'));

// Other branch income today
$stmt = $conn->prepare("SELECT income_type, description, reference, amount, created_at FROM branch_income WHERE branch_id = :b AND DATE(created_at) = :t");
$stmt->execute([':b' => $userBranchId, ':t' => $todayDate]);
$todayBranchIncomeDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
$todayBranchIncome = array_sum(array_column($todayBranchIncomeDetails, 'amount'));

$todayIncome = $todaySales + $todayLaybuy + $todayOrderDeposits + $todayOrderFinals + $todayCreditPayments + $todayBranchIncome;

$todayDeposits = 0;
$todayDepositStmt = $conn->prepare("SELECT d.id as deposit_id, d.deposit_date, d.amount, d.notes, u.username as created_by_user FROM deposits d LEFT JOIN users u ON d.created_by = u.user_id WHERE d.branch_id = :branch_id AND DATE(d.deposit_date) = :today ORDER BY d.deposit_date DESC");
$todayDepositStmt->bindParam(':branch_id', $userBranchId, PDO::PARAM_INT);
$todayDepositStmt->bindParam(':today', $todayDate);
$todayDepositStmt->execute();
$todayDepositsDetails = $todayDepositStmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($todayDepositsDetails as $depositRecord) {
    $todayDeposits += (float)($depositRecord['amount'] ?? 0);
}

$todayExpensesDetails = $expense->getExpensesForPeriod($todayDate, $todayDate, null, $userBranchId)->fetchAll(PDO::FETCH_ASSOC);
$todayExpenses = 0;
foreach ($todayExpensesDetails as $expenseRecord) {
    $todayExpenses += (float)($expenseRecord['amount'] ?? 0);
}


$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');


$salesStats = $sales->getBranchSalesStats($userBranchId, $startDate, $endDate);
$layBuyStats = $laybuy->getBranchLayBuyStats($userBranchId, $startDate, $endDate);
$expensesStats = $laybuy->getBranchExpensesStats($userBranchId, $startDate, $endDate);



$totalLaybuy = 0;
foreach ($layBuyStats as $layBuyStats) {
    $totalLaybuy += (float)($layBuyStats['body_amount'] ?? 0);
}

$totalExpenses = 0;
foreach ($expensesStats as $expensesStats) {
    $totalExpenses += (float)($expensesStats['amount'] ?? 0);
}


$inventoryStats = $sales->getBranchInventoryStats($userBranchId);
$lowStockStats = $sales->getLowStockItems($userBranchId);
$targetBalance = $sales->getTargetBalance($userBranchId, date('Y-m', strtotime($startDate)));
$creditSummary = $creditSales->getSummary($userBranchId);
$notifications = new Notifications($conn);
$unread = $notifications->getUnreadnotification($userBranchId);

if (isset($_POST['btn_filter'])){
	
	$startDate = $_POST['start_date'];
	$endDate = $_POST['end_date'];
	//header("location:login.php?id=3");
	//exit; 
}
?>

<style>

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Roboto', sans-serif;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        background-color: #f8f9fa;
    }

    .container {
        width: 100%;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
    }


    .dashboard-container {
        display: flex;
        width: 100%;
        margin-top: 20px;
    }


    .sidebar {
        width: 250px;
        background-color: #343a40;
        color: white;
        padding: 20px;
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        overflow-y: auto;
        z-index: 100;
    }

    .sidebar-heading {
        padding: 10px 0;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        margin-bottom: 15px;
    }

    .sidebar-menu {
        list-style: none;
        padding: 0;
        margin: 0 0 25px 0;
    }

    .sidebar-menu li {
        margin-bottom: 5px;
    }

    .sidebar-menu a {
        display: block;
        padding: 10px 15px;
        color: rgba(255,255,255,0.8);
        text-decoration: none;
        transition: all 0.3s;
        border-radius: 4px;
    }

    .sidebar-menu a:hover {
        background-color: rgba(255,255,255,0.1);
        color: white;
    }

    .sidebar-menu i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
    }

    .sidebar-section {
        margin-bottom: 25px;
    }


    .main-content {
        flex: 1;
        margin-left: 250px;
        padding: 20px;
        width: calc(100% - 250px);
    }


    .card {
        background-color: white;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        width: 100%;
    }

    .card-header {
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header h2, .card-header h5 {
        margin: 0;
        font-size: 1.2rem;
    }

    .card-body {
        padding: 20px;
    }


    .chart-container {
        position: relative;
        height: 350px;
        margin-bottom: 20px;
    }


    .summary-card {
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        transition: transform 0.3s;
        margin-bottom: 20px;
    }

    .summary-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0,0,0,0.2);
    }


    .filter-form {
        background-color: #f8f9fa;
        padding: 15px;
        border-radius: 5px;
        margin-bottom: 20px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    }


    footer {
        margin-left: 250px;
        background-color: #f8f9fa;
        text-align: center;
        padding: 15px 0;
        border-top: 1px solid #eee;
        width: calc(100% - 250px);
    }


    @media (max-width: 768px) {
        .sidebar {
            width: 200px;
        }
        .main-content, footer {
            margin-left: 200px;
            width: calc(100% - 200px);
        }
    }
</style>

<div class="dashboard-container">
    <div class="sidebar">
        <div class="sidebar-heading">Branch Dashboard</div>
		

        <div class="sidebar-section">
            <div class="sidebar-heading">Sales & Transactions</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../sales/create_sale.php">
                        <i class="fas fa-cash-register"></i> Record Sales
                    </a>
                </li>
                <li>
                    <a href="../inventory/sold_items_branch.php">
                        <i class="fas fa-tags"></i> Sold Items
                    </a>
                </li>
                <li><a href="../sales/credit_sales.php"><i class="fas fa-hand-holding-usd"></i> Debtors / Credit Sales</a></li>
                <li>
                    <a href="../sales/list_quotations.php">
                        <i class="fas fa-file-invoice-dollar"></i> Quotations
                    </a>
                </li>
				 <li>
                    <a href="../sales/list_invoices.php">
                        <i class="fas fa-file-invoice-dollar"></i> Invoices
                    </a>
                </li>
				 <li>
                    <a href="../sales/list_delivery_notes.php">
                        <i class="fas fa-truck-loading"></i> Delivery Notes
                    </a>
                </li>
                <li>
                    <a href="../orders/list_orders.php">
                        <i class="fas fa-shopping-cart"></i> Orders
                    </a>
                </li>
                <li>
                    <a href="../customer_service/index.php">
                        <i class="fas fa-headset"></i> Customer Claims & Service
                    </a>
                </li>

            </ul>
        </div>

         <div class="sidebar-section">
            <div class="sidebar-heading"><a  style="color:white;"> Repairs & Other Services </a></div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../services/index.php">
                        <i class="fas fa-screwdriver-wrench"></i> Service / Repair Transactions
                    </a>
                </li>
                <li>
                    <a href="../services/index.php?type=repair">
                        <i class="fas fa-laptop-medical"></i> Repair Job Cards
                    </a>
                </li>
                <li>
                    <a href="../services/index.php?type=installation">
                        <i class="fas fa-network-wired"></i> Installations & Setup
                    </a>
                </li>
                <li>
                    <a href="../customer_service/index.php">
                        <i class="fas fa-headset"></i> Claims / Warranty Follow-up
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Inventory & Stock</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../inventory/branch_stock.php">
                        <i class="fas fa-boxes"></i> Branch Stock
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_site_products.php">
                        <i class="fas fa-receipt"></i> EIS Stock
                    </a>
                </li>
                <li>
                    <a href="../inventory/barcode_labels.php">
                        <i class="fas fa-barcode"></i> Barcode Labels
                    </a>
                </li>
                <li>
                    <a href="../inventory/verify.php">
                        <i class="fas fa-truck-loading"></i> Shipment Records
                    </a>
                </li>
				 <li>
                    <a href="../inventory/add_items_dashboard3.php">
                        <i class="fas fa-shipping-fast"></i> Ship Items
                    </a>
                </li>
				<!--
                <li>
                    <a href="../tracking/item_tracking.php">
                        <i class="fas fa-search"></i> Item Tracking
                    </a>
                </li> -->
                <li>
                    <a href="../stocktaking/stocktaking_dashboard.php">
                        <i class="fas fa-clipboard-check"></i> Stock Taking
                    </a>
                </li>
				<li>
                    <a href="../inventory/missing_items.php">
                        <i class="fas fa-question-circle"></i> Missing Items
                    </a>
                </li>
				<!--
                <li>
                    <a href="../discrepancies/index.php">
                        <i class="fas fa-exclamation-triangle"></i> Discrepancies
                    </a>
                </li> -->

                  <li>
                    <a href="../inventory/assets.php">
                        <i class="fas fa-laptop"></i> Branch Assets
                    </a>
                </li>

                <li>
                     <a href="../inventory/damaged_items.php">
                        <i class="fas fa-tools"></i> Damaged Items
                    </a>
                </li>
                <li>
                    <a href="../disposals/index.php">
                        <i class="fas fa-archive"></i> Disposal Requests
                    </a>
                </li>
                <li>
                    <a href="../reminders/index.php">
                        <i class="fas fa-bell"></i> Renewal Reminders
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Reports & Finance</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../logs/system_logs.php">
                        <i class="fas fa-clipboard-list"></i> System Logs
                    </a>
                </li>
                <li>
                    <a href="../sales/weekly2.php">
                        <i class="fas fa-chart-line"></i> Sales Reports
                    </a>
                </li>
                <li>
                    <a href="../reports/branch_reports.php">
                        <i class="fas fa-history"></i> Historical Reports
                    </a>
                </li>
                <li>
                    <a href="../laybuy_&_loans/laybuy_and_loans.php">
                        <i class="fas fa-hand-holding-usd"></i> Lay-Buys
                    </a>
                </li>
            </ul>
        </div>


        <div class="sidebar-section">
            <div class="sidebar-heading">Extras</div>
            <ul class="sidebar-menu">
              <!--  <li>
                    <a href="../logs/system_logs.php">
                        <i class="fas fa-clipboard-list"></i> Request items from warehouse
                    </a>
                </li>
               
                -->
                <li>
                    <a href="../sales/list_request.php">
                        <i class="fas fa-clipboard-list"></i> Request Items 
                    </a>
                </li>

                <!--
                <li>
                    <a href="../reports/branch_reports.php">
                        <i class="fas fa-history"></i> Historical Reports
                    </a>
                </li>
                <li>
                    <a href="../laybuy_&_loans/laybuy_and_loans.php">
                        <i class="fas fa-hand-holding-usd"></i> Loans & Lay-Buys
                    </a>
                </li> -->
            </ul>
        </div>

    </div>

    <div class="main-content">
        <div class="container">
            <h1 class="mb-4">Branch  Dashboard</h1>
            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card summary-card bg-warning text-dark">
                        <div class="card-body">
                            <h5 class="card-title">Outstanding Credit Sales</h5>
                            <h3>K<?php echo number_format((float)($creditSummary['outstanding_balance'] ?? 0), 2); ?></h3>
                            <p class="mb-0"><?php echo (int)($creditSummary['open_accounts'] ?? 0); ?> active debtor accounts</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card summary-card bg-info text-white">
                        <div class="card-body">
                            <h5 class="card-title">Pending Approval</h5>
                            <h3><?php echo (int)($creditSummary['pending_accounts'] ?? 0); ?></h3>
                            <p class="mb-0"><a class="text-white" href="../sales/credit_sales.php?status=pending_controller_approval">View credit sales</a></p>
                        </div>
                    </div>
                </div>
            </div>
				<?php if ($unread): ?>
                <?php foreach ($unread as $notification): ?>
                <?php $previewLink = $notifications->getPreviewLinkForNotification($notification); ?>
				<div class="alert alert-danger" role="alert">
				 <?php echo htmlspecialchars($notification['created_at']). " ". htmlspecialchars($notification['message']);  ?>
                    <?php if ($previewLink): ?>
                        <a href="<?php echo htmlspecialchars($previewLink['url']); ?>" class="btn btn-sm btn-primary">
                            <i class="fas fa-eye"></i> <?php echo htmlspecialchars($previewLink['label']); ?>
                        </a>
                    <?php endif; ?>
					<form action="mark_message.php" method="POST" style="display:inline;" onsubmit="return confirmDelete('sale');">
                        <input  type="hidden" name="notification_id" value="<?php echo htmlspecialchars($notification['notification_id']); ?>">
                        <input type="hidden" name="return_to" value="branch.php">
						<button type="submit" name="delete_message" class="btn btn-sm btn-danger"><i class="fas fa-pencil"></i> Mark as read</button>
					</form>
				</div>
   				<?php endforeach; ?>
			<?php endif; ?>
             
			 
       
            <p class="text-muted">Monitor branch performance, sales, and inventory</p>

            <div class="card filter-form mb-4">
                <div class="card-body">
                    <form method="GET"  class="row g-3">
                        <div class="col-md-3">
                            <label for="start_date" class="form-label">Start Date</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="end_date" class="form-label">End Date</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary w-100" id="btn_filter" name="btn_filter">Apply Filter</button>
                        </div>
                    </form>
                </div>
            </div>

            <div class="row mb-4">
                <div class="col-md-4">
                    <div class="card summary-card today-summary-card" data-target="#today-income-details" style="cursor:pointer;">
                        <div class="card-body text-center">
                            <h5 class="card-title">Today's Income</h5>
                            <h3 class="card-text">MWK <?php echo number_format($todayIncome, 2); ?></h3>
                            <small class="text-muted">Sales, Lay-Buys, Orders, Credit &amp; Other</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card summary-card today-summary-card" data-target="#today-deposits-details" style="cursor:pointer;">
                        <div class="card-body text-center">
                            <h5 class="card-title">Today's Deposits</h5>
                            <h3 class="card-text">MWK <?php echo number_format($todayDeposits, 2); ?></h3>
                            <small class="text-muted">Deposits recorded today</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card summary-card today-summary-card" data-target="#today-expenses-details" style="cursor:pointer;">
                        <div class="card-body text-center">
                            <h5 class="card-title">Today's Expenses</h5>
                            <h3 class="card-text">MWK <?php echo number_format($todayExpenses, 2); ?></h3>
                            <small class="text-muted">Branch expenses today</small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row mb-4">
                <div class="col-12">
                    <div class="card d-none today-details-card" id="today-income-details">
                        <div class="card-header">
                            <h5>Today's Income Details</h5>
                        </div>
                        <div class="card-body">
                            <?php
                                $todayLaybuyDetails = $laybuy->getBranchLayBuyStats($userBranchId, $todayDate, $todayDate);
                                $hasAnyIncome = !empty($todaySalesData) || !empty($todayLaybuyDetails)
                                    || !empty($todayOrderDepositDetails) || !empty($todayOrderFinalDetails)
                                    || !empty($todayCreditPaymentDetails) || !empty($todayBranchIncomeDetails);
                            ?>
                            <?php if (!$hasAnyIncome): ?>
                                <p class="text-muted">No income transactions were recorded today.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Type</th>
                                                <th>Description</th>
                                                <th>Amount</th>
                                                <th>Time</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($todaySalesData as $sale): ?>
                                                <tr>
                                                    <td><span class="badge bg-primary">Sale</span></td>
                                                    <td><?php echo htmlspecialchars($sale['item_name'] ?? 'Sale'); ?></td>
                                                    <td>MWK <?php echo number_format($sale['total_price'], 2); ?></td>
                                                    <td><?php echo date('H:i', strtotime($sale['sold_at'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <?php foreach ($todayLaybuyDetails as $lp): ?>
                                                <tr>
                                                    <td><span class="badge bg-info text-dark">Lay-Buy</span></td>
                                                    <td><?php echo htmlspecialchars($lp['notes'] ?? 'Lay-Buy payment'); ?></td>
                                                    <td>MWK <?php echo number_format($lp['body_amount'] ?? 0, 2); ?></td>
                                                    <td><?php echo date('M d', strtotime($lp['payment_date'] ?? $todayDate)); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <?php foreach ($todayOrderDepositDetails as $od): ?>
                                                <tr>
                                                    <td><span class="badge bg-warning text-dark">Order Deposit</span></td>
                                                    <td><?php echo htmlspecialchars($od['customer_name'] . ' — ' . $od['item_name']); ?></td>
                                                    <td>MWK <?php echo number_format($od['amount_paid'], 2); ?></td>
                                                    <td><?php echo date('H:i', strtotime($od['created_at'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <?php foreach ($todayOrderFinalDetails as $of): ?>
                                                <tr>
                                                    <td><span class="badge bg-success">Order Balance</span></td>
                                                    <td><?php echo htmlspecialchars($of['customer_name'] . ' — ' . $of['item_name']); ?></td>
                                                    <td>MWK <?php echo number_format($of['final_payment_amount'], 2); ?></td>
                                                    <td><?php echo date('H:i', strtotime($of['completed_at'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <?php foreach ($todayCreditPaymentDetails as $cp): ?>
                                                <tr>
                                                    <td><span class="badge bg-secondary">Credit Payment</span></td>
                                                    <td><?php echo htmlspecialchars($cp['customer_name'] . ' (' . $cp['credit_number'] . ')'); ?></td>
                                                    <td>MWK <?php echo number_format($cp['amount'], 2); ?></td>
                                                    <td><?php echo date('H:i', strtotime($cp['payment_date'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                            <?php foreach ($todayBranchIncomeDetails as $bi): ?>
                                                <tr>
                                                    <td><span class="badge bg-dark">Other</span></td>
                                                    <td><?php echo htmlspecialchars($bi['description'] ?? $bi['reference'] ?? 'Income'); ?></td>
                                                    <td>MWK <?php echo number_format($bi['amount'], 2); ?></td>
                                                    <td><?php echo date('H:i', strtotime($bi['created_at'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="card d-none today-details-card" id="today-deposits-details">
                        <div class="card-header">
                            <h5>Today's Deposit Details</h5>
                        </div>
                        <div class="card-body">
                            <?php if (empty($todayDepositsDetails)): ?>
                                <p class="text-muted">No deposits were recorded today.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Deposit Date</th>
                                                <th>Amount</th>
                                                <th>Recorded By</th>
                                                <th>Notes</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($todayDepositsDetails as $depositRecord): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars(date('M d, Y', strtotime($depositRecord['deposit_date']))); ?></td>
                                                    <td>MWK <?php echo number_format($depositRecord['amount'], 2); ?></td>
                                                    <td><?php echo htmlspecialchars($depositRecord['created_by_user'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($depositRecord['notes'] ?? ''); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="card d-none today-details-card" id="today-expenses-details">
                        <div class="card-header">
                            <h5>Today's Expense Details</h5>
                        </div>
                        <div class="card-body">
                            <?php if (empty($todayExpensesDetails)): ?>
                                <p class="text-muted">No expenses were recorded today.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Expense Date</th>
                                                <th>Category</th>
                                                <th>Description</th>
                                                <th>Amount</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($todayExpensesDetails as $expenseRecord): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars(date('M d, Y', strtotime($expenseRecord['expense_date']))); ?></td>
                                                    <td><?php echo htmlspecialchars($expenseRecord['category_name'] ?? ''); ?></td>
                                                    <td><?php echo htmlspecialchars($expenseRecord['description'] ?? ''); ?></td>
                                                    <td>MWK <?php echo number_format($expenseRecord['amount'], 2); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>


            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="card summary-card">
                        <div class="card-body text-center">
                            <h5 class="card-title">Branch Sales</h5>
                            <h3 class="card-text">MWK <?php echo number_format(($salesStats['stats']['total_revenue']+$totalLaybuy) ?? 0, 2); ?></h3>
                            <small class="text-muted">This period</small>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card summary-card">
                        <div class="card-body text-center">
                            <h5 class="card-title">Target Balance</h5>
                            <?php if ($targetBalance['target_set']): ?>
                                <h3 class="card-text <?php echo $targetBalance['target_met'] ? 'text-success' : 'text-warning'; ?>">
                                    MWK <?php echo number_format(abs(($targetBalance['balance']-$totalLaybuy)), 2); ?>
                                </h3>
                                <small class="text-muted">
                                    <?php if ($targetBalance['target_met']): ?>
                                        Target Met!
                                    <?php else: ?>
                                       <!-- <?php echo number_format(($targetBalance['balance']-$totalLaybuy), 1); ?>% of target -->
                                    <?php endif; ?>
                                </small>
                                <!--<div class="progress mt-2" style="height: 6px;">
                                    <div class="progress-bar <?php echo $targetBalance['target_met'] ? 'bg-success' : 'bg-warning'; ?>"
                                         style="width: <?php echo min(100, $targetBalance['progress_percentage']); ?>%"></div>
                                </div> -->
                            <?php else: ?>
                                <h3 class="card-text text-muted">No Target Set</h3>
                                <small class="text-muted">Contact admin to set target</small>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card summary-card">
                        <div class="card-body text-center">
                            <h5 class="card-title">Branch Expenses</h5>
                            <h3 class="card-text">MWK <?php echo number_format($totalExpenses ?? 0, 2); ?></h3>
                            <small class="text-muted">This period</small>
                        </div>
                    </div>
                </div>
				  <div class="col-md-3">
                    <div class="card summary-card">
                        <div class="card-body text-center">
                            <h5 class="card-title">Branch Profit</h5>
                            <h3 class="card-text">MWK <?php echo number_format(((($salesStats['stats']['total_revenue']+$totalLaybuy)*$profitRate)-$totalExpenses) ?? 0, 2); ?></h3>
                            <small class="text-muted">This period</small>
                        </div>
                    </div>
                </div>
             <div class="col-md-3">
                    <div class="card summary-card">
                        <div class="card-body text-center">
                            <h5 class="card-title">Active Days</h5>
                            <h3 class="card-text"><?php echo number_format($salesStats['stats']['active_days'] ?? 0); ?></h3>
                            <small class="text-muted">Sales days this period</small>
                        </div>
                    </div>
                </div>
            
			</div>


            <div class="row mb-4">
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5>Daily Sales Trend</h5>
                        </div>
                        <div class="card-body">
                            <div class="chart-container">
                                <canvas id="salesTrendChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5>Top Selling Items</h5>
                        </div>
                        <div class="card-body">
                            <a href="../reports/top_selling_items.php?start_date=<?php echo $startDate; ?>&end_date=<?php echo $endDate; ?>" class="text-decoration-none" style="cursor: pointer;">
                                <div class="chart-container">
                                    <canvas id="topItemsChart"></canvas>
                                </div>
                                <div class="mt-2 text-center">
                                    <small class="text-primary">
                                        <i class="fas fa-external-link-alt"></i> Click to view detailed report
                                    </small>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>


            <div class="row mb-4">
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5>Low Stock Alert</h5>
                            <small class="text-muted">Items below <?php echo $lowStockStats['low_stock_threshold']; ?> units</small>
                        </div>
                        <div class="card-body">
                            <?php if (empty($lowStockStats['low_stock_items'])): ?>
                                <div class="text-center text-success">
                                    <i class="fas fa-check-circle fa-3x mb-3"></i>
                                    <h5>All items are well stocked!</h5>
                                    <p class="text-muted">No items are below the low stock threshold.</p>
                                </div>
                            <?php else: ?>
                                <a href="../inventory/low_stock_items.php" class="text-decoration-none" style="cursor: pointer;">
                                    <div class="chart-container">
                                        <canvas id="lowStockChart"></canvas>
                                    </div>
                                    <div class="mt-3 text-center">
                                        <small class="text-muted">
                                            <strong><?php echo $lowStockStats['total_low_stock_items']; ?> items</strong> need restocking
                                            (Total value: MWK <?php echo number_format($lowStockStats['total_low_stock_value'], 2); ?>)
                                        </small>
                                        <br>
                                        <small class="text-primary">
                                            <i class="fas fa-external-link-alt"></i> Click to view full list
                                        </small>
                                    </div>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5>Recent Sales</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            $recentSales = $sales->getSalesByBranch($userBranchId, $startDate, $endDate);
                            if (empty($recentSales)): ?>
                                <p class="text-muted text-center">No sales found for the selected period.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Item</th>
                                                <th>Amount</th>
                                                <th>Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach (array_slice($recentSales, 0, 5) as $sale): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($sale['item_name']); ?></td>
                                                    <td>MWK <?php echo number_format($sale['total_price'], 2); ?></td>
                                                    <td><?php echo date('M d', strtotime($sale['sold_at'])); ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
		
		
		
		
		const salesCtx = document.getElementById('salesTrendChart').getContext('2d');
        const salesChart = new Chart(salesCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_column($salesStats['daily_trends'], 'sale_date')); ?>,
                datasets: [{
                    label: 'Daily Sales',
                    data: <?php echo json_encode(array_column($salesStats['daily_trends'], 'daily_revenue')); ?>,
                    backgroundColor: 'rgba(78, 115, 223, 0.2)',
                    borderColor: 'rgba(78, 115, 223, 1)',
                    borderWidth: 2,
                    pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                    pointBorderColor: '#fff',
                    pointRadius: 5,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'MWK ' + value.toLocaleString();
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'MWK ' + context.raw.toLocaleString();
                            }
                        }
                    }
                }
            }
        });


        const topItemsCtx = document.getElementById('topItemsChart').getContext('2d');
        const topItemsChart = new Chart(topItemsCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_column($salesStats['top_items'], 'item_name')); ?>,
                datasets: [{
                    label: 'Revenue',
                    data: <?php echo json_encode(array_column($salesStats['top_items'], 'total_revenue')); ?>,
                    backgroundColor: 'rgba(28, 200, 138, 0.8)',
                    borderColor: 'rgba(28, 200, 138, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'MWK ' + value.toLocaleString();
                            }
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return 'MWK ' + context.raw.toLocaleString();
                            }
                        }
                    }
                }
            }
        });


        <?php if (!empty($lowStockStats['low_stock_items'])): ?>
        const lowStockCtx = document.getElementById('lowStockChart').getContext('2d');
        const lowStockChart = new Chart(lowStockCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_column($lowStockStats['low_stock_items'], 'item_name')); ?>,
                datasets: [{
                    label: 'Stock Count',
                    data: <?php echo json_encode(array_column($lowStockStats['low_stock_items'], 'item_count')); ?>,
                    backgroundColor: 'rgba(220, 53, 69, 0.8)',
                    borderColor: 'rgba(220, 53, 69, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: <?php echo $lowStockStats['low_stock_threshold']; ?>,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const itemName = context.label;
                                const count = context.raw;
                                const threshold = <?php echo $lowStockStats['low_stock_threshold']; ?>;
                                return itemName + ': ' + count + ' units (Threshold: ' + threshold + ')';
                            }
                        }
                    },
                    legend: {
                        display: false
                    }
                }
            }
        });
        <?php endif; ?>
    });
</script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        $(document).on('click', '.today-summary-card', function () {
            var target = $(this).data('target');
            var details = $('.today-details-card');
            if (!target) return;
            if ($(target).hasClass('d-none')) {
                details.addClass('d-none');
                $(target).removeClass('d-none');
            } else {
                $(target).addClass('d-none');
            }
        });
    });
</script>

<?php include '../../includes/footer.php'; ?>
