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

$sales = new Sales($conn);
$inventory = new Inventory($conn);
$laybuy = new Laybuy($conn);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);


$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)));
$notifications = new Notifications($conn);
$unread = $notifications->getUnreadnotification($userBranchId);
?>

<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/list_quotations.php">
                        <i class="fas fa-file-invoice-dollar"></i> Quotations
                    </a>
                </li>
                <li>
                    <a href="../orders/list_orders.php">
                        <i class="fas fa-shopping-cart"></i> Orders
                    </a>
                </li>
            </ul>
        </div>

         <div class="sidebar-section">
            <div class="sidebar-heading"><a href="http://www.login.ft-mw.com" target="_blank"  style="color:white;"> Repairs & Other Services </a></div>
            <ul class="sidebar-menu">
                
                <!--<li>
                    <a href="../inventory/sold_items_branch.php">
                        <i class="fas fa-box-open"></i> Sold Items
                    </a>
                </li>
                <li>
                    <a href="../sales/list_quotations.php">
                        <i class="fas fa-file-invoice-dollar"></i> Quotations
                    </a>
                </li>
                <li>
                    <a href="../orders/list_orders.php">
                        <i class="fas fa-shopping-cart"></i> Orders
                    </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="../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>
            </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>
				<?php if ($unread): ?>
                <?php foreach ($unread as $unread): ?>
				<div class="alert alert-danger" role="alert">
				 <?php echo htmlspecialchars($unread['created_at']). " ". htmlspecialchars($unread['message']);  ?>
					<form action="mark_message.php" method="POST" style="display:inline;" onsubmit="return confirmDelete('sale');">
                        <input  type="hidden" name="notification_id" value="<?php echo htmlspecialchars($unread['notification_id']); ?>">
						<button type="submit" name="delete_message" class="btn btn-sm btn-danger"><i class="fas fa-pencil"></i> Edit report</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" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" 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">Apply Filter</button>
                        </div>
                    </form>
                </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">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>

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