<?php

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


if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    header('Location: /unauthorized.php');
    exit;
}


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


require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../classes/Expense.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Notifications.php';
require_once __DIR__ . '/../../classes/CreditSales.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';


$sales = new Sales($conn);
$expense = new Expense($conn);
$creditSales = new CreditSales($conn);
/*

$startDate = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$endDate = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-t');
$selectedBranchId = isset($_GET['branch_id']) && !empty($_GET['branch_id']) ? $_GET['branch_id'] : null;


$salesData = $sales->getSalesForPeriod($startDate, $endDate, $selectedBranchId);


$totalSales = 0;
if (!empty($salesData)) {
    foreach ($salesData as $sale) {
        $totalSales += $sale['total_price'];
    }
}


$totalExpenses = $expense->getTotalExpenses($startDate, $endDate, $selectedBranchId);


$salesRevenue = $totalSales * 0.2;
$totalProfit = $salesRevenue - $totalExpenses;
$profitMargin = ($totalSales > 0) ? ($totalProfit / $totalSales) * 100 : 0;


$weekStartDate = date('Y-m-d', strtotime('-7 days'));
$weekEndDate = date('Y-m-d');

$weeklySalesData = $sales->getSalesForPeriod($weekStartDate, $weekEndDate);
$weeklySalesTotal = 0;
if (!empty($weeklySalesData)) {
    foreach ($weeklySalesData as $sale) {
        $weeklySalesTotal += $sale['total_price'];
    }
}

$weeklyExpenses = $expense->getTotalExpenses($weekStartDate, $weekEndDate);
*/

$branch = new Branch($conn);


$branchesResult = $branch->getAllBranches();
$branches = $branchesResult->fetchAll(PDO::FETCH_ASSOC);

/*
$branchLabels = [];
$branchSales = [];
$branchExpenses = [];
$branchProfits = [];


foreach ($branches as $branchData) {
    $branchId = $branchData['branch_id'];
    $branchLabels[] = $branchData['branch_name'];


    $branchSalesData = $sales->getSalesByBranch($branchId, $startDate, $endDate);
    $branchSalesTotal = 0;
    foreach ($branchSalesData as $sale) {
        $branchSalesTotal += $sale['total_price'];
    }
    $branchSales[] = $branchSalesTotal;


    $branchExpenseTotal = $expense->getBranchExpenses($branchId, $startDate, $endDate);
    $branchExpenses[] = $branchExpenseTotal;



    $branchRevenue = $branchSalesTotal * 0.2;
    $branchProfits[] = $branchRevenue - $branchExpenseTotal;
}


$expenseCategories = $expense->getExpenseCategories();
$categoryLabels = [];
$categoryExpenses = [];

foreach ($expenseCategories as $category) {
    $categoryLabels[] = $category['category_name'];
    $amount = $expense->getCategoryExpenses($category['category_id'], $startDate, $endDate);
    $categoryExpenses[] = $amount;
}

*/

try {
    // No-button config sync: skips terminals that are still fresh, so this is
    // cheap on every request and only reaches out to MRA when something is due.
    (new MraEisCompliance($conn))->syncAllTerminalConfigurations();
} catch (Throwable $e) {
    error_log('MRA EIS automatic configuration sync failed: ' . $e->getMessage());
}

$notifications = new Notifications($conn);
$unread = $notifications->getUnreadnotificationAdmin();
$creditSummary = $creditSales->getSummary(null);

?>

<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">Admin Dashboard</div>
		
        <div class="sidebar-section">
            <div class="sidebar-heading">System Management</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../users/users_list.php">
                        <i class="fas fa-users"></i> Manage Users
                    </a>
                </li>
				
			
                <li>
                    <a href="../logs/system_logs.php">
                        <i class="fas fa-history"></i> System Logs
                    </a>
                </li>
                <li>
                    <a href="../admin/settings.php#branch-management">
                        <i class="fas fa-building"></i> Manage Branches
                    </a>
                </li>
                <li>
                    <a href="../admin/sales_targets.php">
                        <i class="fas fa-bullseye"></i> Sales Targets
                    </a>
                </li>
                <li>
                    <a href="../admin/expense_allocation.php">
                        <i class="fas fa-wallet"></i> Expense Allocation
                    </a>
                </li>
                <li>
                    <a href="../admin/financial_projections.php">
                        <i class="fas fa-chart-line"></i> Financial Projections
                    </a>
                </li>
                <li>
                    <a href="../admin/settings.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                </li>
               <!-- <li>
                    <a href="../admin/document_import.php">
                        <i class="fas fa-file-import"></i> AI Document Import
                    </a>
                </li>-->
                <li>
                    <a href="../admin/local_backup.php">
                        <i class="fas fa-download"></i> Local Backup
                    </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="../admin/creditors.php">
                        <i class="fas fa-file-invoice-dollar"></i> Creditors
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Communications</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../admin/mailbox.php">
                        <i class="fas fa-envelope"></i> Emails
                    </a>
                </li>
                <li>
                    <a href="../admin/messages_monitor.php">
                        <i class="fas fa-comments"></i> Messages
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">MRA EIS</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../admin/mra_eis_onboarding.php">
                        <i class="fas fa-network-wired"></i> Onboarding
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_site_products.php">
                        <i class="fas fa-boxes"></i> Site Products
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_site_products.php?warehouse_stock=1">
                        <i class="fas fa-warehouse"></i> EIS Stock
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_stock_batch_mapping.php">
                        <i class="fas fa-boxes"></i> Stock Batch Mapping
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_compliance.php">
                        <i class="fas fa-shield-alt"></i> Compliance Outbox
                    </a>
                </li>
                <li>
                    <a href="../admin/mra_eis_configuration.php">
                        <i class="fas fa-cogs"></i> EIS Configuration
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-section">
            <div class="sidebar-heading">Reports & Analysis</div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../expenses/monthly_report.php">
                        <i class="fas fa-file-invoice-dollar"></i> Monthly Financial Overview
                    </a>
                </li>
                <li>
                    <a href="../reports/sales.php">
                        <i class="fas fa-chart-line"></i> Branch Sales Reports
                    </a>
                </li>

                 <li>
                    <a href="../reports/branch_selection.php">
                        <i class="fas fa-chart-pie"></i> Sales Tracking
                    </a>
                </li>
                <li>

                <li>
                    <a href="../reports/sales_summary.php">
                        <i class="fas fa-chart-pie"></i> Sales Summary
                    </a>
                </li>
                <li>
                    <a href="../reports/top_selling_items.php">
                        <i class="fas fa-trophy"></i> Top Selling Items
                    </a>
                </li>
                <li>
                    <a href="../reports/profit_loss.php">
                        <i class="fas fa-chart-bar"></i> Profit & Loss
                    </a>
                </li>
                <li>
                    <a href="../expenses/manage_expenses.php">
                        <i class="fas fa-money-bill-wave"></i> Expenses
                    </a>
                </li>
                <li>
                    <a href="../sales/quotation_branch_selection.php">
                        <i class="fas fa-file-alt"></i> Quotations
                    </a>
                </li>
				
				
				 <li>
                    <a href="../sales/invoice_branch_selection.php">
                        <i class="fas fa-file-invoice-dollar"></i> Invoices
                    </a>
                </li>
				 <li>
                    <a href="../sales/delivery_note_branch_selection.php">
                        <i class="fas fa-truck-loading"></i> Delivery Notes
                    </a>
                </li>

                 <li>
                    <a href="../sales/request_branch_selection.php">
                        <i class="fas fa-clipboard-list"></i> Item Requests
                    </a>
                </li>

                <li>
                    <a href="../laybuy_&_loans/loan_laybuy_branch_selection.php">
                        <i class="fas fa-hand-holding-usd"></i> Lay-Buys
                    </a>
                </li>

                <li>
                    <a href="../orders/order_branch_selection.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>
                <li>
                    <a href="../services/index.php">
                        <i class="fas fa-tools"></i> Services
                    </a>
                </li>

            </ul>
        </div>

		     <div class="sidebar-section">
            <div class="sidebar-heading">Inventory </div>
            <ul class="sidebar-menu">
				<li>
                    <a href="../inventory/category_list.php">
                        <i class="fas fa-list"></i> Manage item categories
                    </a>
                </li>
                <li>
                    <a href="../inventory/get_branch_inventory.php">
                        <i class="fas fa-warehouse"></i> Branch Stocks
                    </a>
                </li>
                <li>
                    <a href="../inventory/barcode_labels.php">
                        <i class="fas fa-barcode"></i> Barcode Labels
                    </a>
                </li>
				
				<li>
                    <a href="../inventory/get_branch_missing_items.php">
                        <i class="fas fa-question-circle"></i> Branch Missing items
                    </a>
                </li>
				
				
				 <li>
                    <a href="../inventory/get_branch_inventory_unknown.php">
                        <i class="fas fa-map-marker-alt"></i> Stock - Unknown Loacation
                    </a>
                </li>
                <li>
                    <a href="../inventory/add_items_dashboard2.php">
                        <i class="fas fa-shipping-fast"></i> Ship Items
                    </a>
                </li>
                <li>
                    <a href="../inventory/choose_warehouse_form.php">
                        <i class="fas fa-dolly-flatbed"></i> Add to Warehouse
                    </a>
                </li>
                <li>
                    <a href="../inventory/product_stock_code_generator.php">
                        <i class="fas fa-tags"></i> Product Stock Codes
                    </a>
                </li>
                <li>
                    <a href="../shipments/shipment_dashboard.php">
                        <i class="fas fa-truck"></i> Shipment Records
                    </a>
                </li>
				
				<!--
                <li>
                    <a href="../shipments/pending_approvals.php">
                        <i class="fas fa-check-double"></i> Approve Shipments
                    </a>
                </li> -->
                <li>
                    <a href="../inventory/sold_items_dashboard.php">
                        <i class="fas fa-tags"></i> Sold Items
                    </a>
                </li>
                <li>
                    <a href="../tracking/item_tracking.php">
                        <i class="fas fa-search"></i> Item Tracking
                    </a>
                </li>
				<li>
                    <a href="../inventory/change_price.php">
                        <i class="fas fa-dollar-sign"></i> Adjust Prices
                    </a>
                </li>
				
				<!--<li>
                    <a href="../tracking/txn_tracking.php">
                        <i class="fas fa-search"></i> Search Receipt
                    </a>
                </li>-->
                <li>
                    <a href="../stocktaking/stocktaking_dashboard.php">
                        <i class="fas fa-clipboard-check"></i> Stock Taking
                    </a>
                </li>
                <li>
                    <a href="../inventory/low_stock_items.php">
                        <i class="fas fa-exclamation-triangle"></i> Low Stock Items
                    </a>
                </li>
                <li>
                    <a href="../disposals/index.php">
                        <i class="fas fa-archive"></i> Inventory Disposals
                    </a>
                </li>
                <li>
                    <a href="../reminders/index.php">
                        <i class="fas fa-bell"></i> Renewal Reminders
                    </a>
                </li>
                <li>
                    <a href="../discrepancies/index.php">
                        <i class="fas fa-exclamation-triangle"></i> Discrepancies
                    </a>
                </li>
            </ul>
        </div>
   


		

        <div class="sidebar-section">
            <div class="sidebar-heading"> HR - Payroll </div>
            <ul class="sidebar-menu">
                <li>
                    <a href="../payroll/index.php">
                        <i class="fas fa-gauge-high"></i> Payroll overview
                    </a>
                </li>
                <li>
                    <a href="../payroll/employee_list.php">
                        <i class="fas fa-user-tie"></i> Employees
                    </a>
                </li>
                <li>
                    <a href="../payroll/departments.php">
                        <i class="fas fa-building-user"></i> Departments
                    </a>
                </li>
               
                <li>
                    <a href="../payroll/salaries.php">
                        <i class="fas fa-money-check-alt"></i> Manage salaries
                    </a>
                </li>
                <li>
                    <a href="../payroll/pay_runs.php">
                        <i class="fas fa-file-invoice-dollar"></i> Pay runs
                    </a>
                </li>
                <li>
                    <a href="../payroll/payslips.php">
                        <i class="fas fa-receipt"></i> Payslips
                    </a>
                </li>
                <li>
                    <a href="../payroll/attendance.php">
                        <i class="fas fa-calendar-check"></i> Attendance 
                    </a>
                </li>
                <li>
                    <a href="../payroll/leave.php">
                        <i class="fas fa-calendar-alt"></i> Leave 
                    </a>
                </li>
                <li>
                    <a href="../payroll/loans.php">
                        <i class="fas fa-hand-holding-usd"></i> Loans 
                    </a>
                </li>
                <li>
                    <a href="../payroll/remunerations.php">
                        <i class="fas fa-receipt"></i> Remunerations 
                    </a>
                </li>
                <li>
                    <a href="../payroll/pension.php">
                        <i class="fas fa-piggy-bank"></i> Pension & gratuities
                    </a>
                </li>
                <li>
                    <a href="../payroll/compliance.php">
                        <i class="fas fa-shield-halved"></i> Compliance
                    </a>
                </li>
                <li>
                    <a href="../payroll/setup.php">
                        <i class="fas fa-screwdriver-wrench"></i> Setup
                    </a>
                </li>
               
            </ul>
        </div>
    
	    <div class="sidebar-section">
            <div class="sidebar-heading"> External Links  </div>
            <ul class="sidebar-menu">
                <li>
                    <a href="https://143.105.113.177:8098" target="_blank">
                        <i class="fas fa-door-open"></i> Access Control
                    </a>
                </li>
               
                <li>
                    <a href="http://143.105.113.177/login/?next=/" target="_blank">
                        <i class="fas fa-clock"></i> Time Attendance
                    </a>
                </li>
                <li>
                    <a href="https://143.105.113.177:8089" target="_blank">
                        <i class="fas fa-phone"></i> IP Phones                    </a>
                </li>
               
            </ul>
        </div>
   
	
	
	</div>

    <div class="main-content">
        <div class="container">
            <h1 class="mb-4">Admin 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 Debtors</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 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 Credit 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">Review credit sales</a></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card summary-card bg-secondary text-white">
                        <div class="card-body">
                            <h5 class="card-title">Total Credit Sales</h5>
                            <h3>K<?php echo number_format((float)($creditSummary['total_credit'] ?? 0), 2); ?></h3>
                            <p class="mb-0">Paid K<?php echo number_format((float)($creditSummary['total_paid'] ?? 0), 2); ?></p>
                        </div>
                    </div>
                </div>
            </div>
			<?php if ($unread): ?>
                <?php foreach ($unread as $notification): ?>
                <?php $previewLink = $notifications->getPreviewLinkForNotification($notification); ?>
				<div class="alert alert-success" 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;">
                        <input  type="hidden" name="notification_id" value="<?php echo htmlspecialchars($notification['notification_id']); ?>">
                        <input type="hidden" name="return_to" value="admin.php">
						<button type="submit" name="delete_message" value="1" class="btn btn-sm btn-success"><i class="fas fa-check"></i> Mark as read</button>
                    </form>
				</div>
   				<?php endforeach; ?>
			<?php endif; ?>
			
			
			
			
			
			
			
			
            <div class="card filter-form mb-4">
                <div class="card-body">
                    <form  class="row g-3" id="dashboard_filter_form">
                        <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 date('Y-m-01'); ?>">
                        </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 date('Y-m-d'); ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="branch_id" class="form-label">Branch</label>
                            <select class="form-control" id="branch_id" name="branch_id">
                                <option value="all">All Branches</option>
                                <?php foreach ($branches as $branchItem): ?>
                                    <option value="<?php echo $branchItem['branch_id']; ?>" <?php echo (isset($_GET['branch_id']) && $_GET['branch_id'] == $branchItem['branch_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($branchItem['branch_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <button type="button" class="btn btn-primary w-100"  id="btn_filter" >Apply Filter</button>
                        </div>
                    </form>
                </div>
            </div>

			<span id="result_data">
		
			</span>
		
		</div>
    </div>
</div>

<footer>
    <p>&copy; <?php echo date('Y'); ?> Inventory Management System. All rights reserved.</p>
</footer>


<script>
	$(document).ready(function () {

    function loadData() {
        var start_date = $("#start_date").val();
        var end_date = $("#end_date").val();
        var branch_id = $("#branch_id").val();

        console.log("Sending:", start_date, end_date, branch_id);

        $.post("admin_dashboard_data.php", {
            start_date: start_date,
            end_date: end_date,
            branch_id: branch_id
        })
        .done(function (data) {
            console.log("Response:", data);
            $("#result_data").html(data);
        })
        .fail(function (xhr, status, error) {
            console.error("Error:", error);
            console.log(xhr.responseText);
        });
    }

    // Load on page ready
    loadData();

    // On button click
    $("#dashboard_filter_form").on("submit", function (event) {
        event.preventDefault();
        loadData();
    });

    $("#btn_filter").click(function (event) {
        event.preventDefault();
        loadData();
    });

    $(document).on('click', '#result_data .today-summary-card', function () {
        var target = $(this).data('target');
        var details = $('#result_data .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'; ?>
</body>
</html>
