<?php
session_start();
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../classes/Database.php';
require_once __DIR__.'/../../classes/FinancialReport.php';
require_once __DIR__.'/../../classes/SystemSettings.php';
$conn=(new Database())->getConnection(); $auth=new Auth($conn);
if(!isset($_SESSION['user_id'])){header('Location: ../../login.php');exit;}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);
$month=$_GET['month']??date('Y-m'); if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/',$month))$month=date('Y-m');
$branchId=!empty($_GET['branch'])?(int)$_GET['branch']:null;
$branches=[];$reportError=null;
try{
    $branches=$conn->query("SELECT branch_id,branch_name FROM branches WHERE branch_id!=7 ORDER BY branch_name")->fetchAll(PDO::FETCH_ASSOC);
    $rate=(new SystemSettings(null,$conn))->profitRate();
    $report=(new FinancialReport($conn))->monthly($month,$branchId,$rate);
}catch(Throwable $error){
    error_log('Monthly financial report failed: '.$error->getMessage());
    $reportError=$error->getMessage();
}
$monthLabel=date('F Y',strtotime($month.'-01')); $pdfQuery=http_build_query(['month'=>$month,'branch'=>$branchId]);
$expenseExportQuery=http_build_query(['start_date'=>date('Y-m-d',strtotime('first day of last month')),'end_date'=>date('Y-m-d'),'branch'=>$branchId]);
function fh($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');} function money($v){return 'MWK '.number_format((float)$v,2);}
if($reportError!==null){
    include __DIR__.'/../../includes/header.php';
    echo '<div class="container mt-4"><div class="alert alert-danger"><h4>Financial report could not be loaded</h4><p class="mb-2">The server returned a database compatibility error instead of generating the report.</p><div class="bg-light border rounded p-2"><code>'.fh($reportError).'</code></div><p class="mt-2 mb-0">This error has also been written to the PHP error log.</p></div><a class="btn btn-secondary" href="../dashboard/admin.php">Back to Dashboard</a></div>';
    include __DIR__.'/../../includes/footer.php';
    exit;
}
$receiptTypes=[];foreach($report['receipts'] as $r){$receiptTypes[$r['type']]=($receiptTypes[$r['type']]??0)+$r['amount'];}
$positive=$report['net_profit']>=0;
?>
<?php include __DIR__.'/../../includes/header.php'; ?>
<style>
.finance-card{border:0;box-shadow:0 3px 13px rgba(0,0,0,.08)}.kpi{border-left:4px solid #0d6efd}.kpi.good{border-color:#198754}.kpi.bad{border-color:#dc3545}.kpi.warn{border-color:#ffc107}.kpi-value{font-size:1.35rem;font-weight:700}.statement td:last-child,.statement th:last-child{white-space:nowrap;text-align:right}.explain{color:#6c757d;font-size:.88rem}.section-title{font-weight:700}.scroll-table{max-height:520px;overflow:auto}.plain-box{background:#f4f8ff;border-left:5px solid #0d6efd}.table tfoot{font-weight:700}.amount-positive{color:#198754}.amount-negative{color:#dc3545}
@media print{.no-print,header,nav,footer{display:none!important}.container-fluid{max-width:none!important}.finance-card{box-shadow:none!important;break-inside:avoid}.scroll-table{max-height:none;overflow:visible}.table{font-size:9px}}
</style>
<div class="container-fluid px-lg-4 mt-4 mb-5">
 <div class="d-flex flex-wrap justify-content-between gap-3 mb-3"><div><h2 class="mb-1"><i class="fas fa-chart-line me-2"></i>Monthly Financial Overview</h2><div class="text-muted"><?=fh($monthLabel)?> Â· Income, cash movement, expenses and profit or loss</div></div><div class="d-flex gap-2 align-items-start no-print"><a class="btn btn-secondary" href="../dashboard/admin.php"><i class="fas fa-arrow-left"></i> Dashboard</a><button class="btn btn-outline-primary" onclick="window.print()"><i class="fas fa-print"></i> Print</button><a class="btn btn-danger" href="generate_monthly_report_pdf.php?<?=fh($pdfQuery)?>"><i class="fas fa-file-pdf"></i> PDF</a></div></div>
 <div class="card finance-card mb-4 no-print"><div class="card-body"><form id="monthlyFinancialReportForm" action="<?=fh($_SERVER['PHP_SELF'])?>" method="get" class="row g-3 align-items-end"><div class="col-md-4"><label class="form-label" for="reportMonth">Month</label><input type="month" class="form-control" id="reportMonth" name="month" value="<?=fh($month)?>" required></div><div class="col-md-5"><label class="form-label" for="reportBranch">Branch</label><select class="form-select" id="reportBranch" name="branch"><option value="">All branches</option><?php foreach($branches as $b):?><option value="<?=(int)$b['branch_id']?>" <?=$branchId===(int)$b['branch_id']?'selected':''?>><?=fh($b['branch_name'])?></option><?php endforeach;?></select></div><div class="col-md-3"><button id="generateMonthlyReportButton" class="btn btn-primary w-100" type="submit"><i class="fas fa-sync"></i> Generate Report</button></div></form></div></div>

 <script>
 (function () {
     const form = document.getElementById('monthlyFinancialReportForm');
     const button = document.getElementById('generateMonthlyReportButton');
     if (!form) return;

     form.addEventListener('submit', function (event) {
         if (!form.checkValidity()) return;
         event.preventDefault();
         if (button) {
             button.disabled = true;
             button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating...';
         }
         const query = new URLSearchParams(new FormData(form));
         window.location.assign(form.action + '?' + query.toString());
     });
 })();
 </script>
 <div class="plain-box p-3 rounded mb-4"><h5 class="mb-2">Monthly Financial Performance Summary</h5><p class="mb-1">The business recorded <strong><?=money($report['revenue'])?></strong> in sales and an estimated gross profit of <strong><?=money($report['gross_profit'])?></strong>. After <strong><?=money($report['expenses_total'])?></strong> in operating expenses, the month ended with a <strong class="<?=$positive?'text-success':'text-danger'?>"><?=$positive?'profit':'loss'?> of <?=money(abs($report['net_profit']))?></strong>.</p><p class="mb-0">Recorded cash-equivalent receipts were <strong><?=money($report['cash_in'])?></strong>, while recorded expense outflows were <strong><?=money($report['cash_out'])?></strong>, giving a net operating cash movement of <strong><?=money($report['net_cash'])?></strong>.</p></div>

 <div class="row g-3 mb-4"><?php $cards=[['Sales revenue',$report['revenue'],'','Sales made during the month'],['Estimated gross profit',$report['gross_profit'],'good','Sales less estimated cost of goods'],['Operating expenses',$report['expenses_total'],'warn','Day-to-day business costs'],['Net profit / loss',$report['net_profit'],$positive?'good':'bad','What remains after expenses']];foreach($cards as $c):?><div class="col-sm-6 col-xl-3"><div class="card finance-card kpi <?=$c[2]?> h-100"><div class="card-body"><div class="text-muted small"><?=fh($c[0])?></div><div class="kpi-value"><?=money($c[1])?></div><div class="explain"><?=fh($c[3])?></div></div></div></div><?php endforeach;?></div>

 <div class="row g-4 mb-4"><div class="col-xl-6"><div class="card finance-card h-100"><div class="card-header section-title"><i class="fas fa-file-invoice-dollar me-2"></i>Profit & Loss Statement</div><div class="card-body p-0"><table class="table statement mb-0"><thead><tr><th>Line</th><th class="explain">Meaning</th><th>Amount</th></tr></thead><tbody><tr><td>Sales revenue</td><td class="explain">Value of goods sold</td><td><?=money($report['revenue'])?></td></tr><tr><td>Less: estimated cost of sales</td><td class="explain">Estimated cost of goods sold</td><td>(<?=money($report['cost_of_sales'])?>)</td></tr><tr class="table-primary fw-bold"><td>Estimated gross profit</td><td class="explain"><?=number_format($rate*100,1)?>% configured gross-profit rate</td><td><?=money($report['gross_profit'])?></td></tr><tr><td>Less: operating expenses</td><td class="explain">Rent, salaries and other running costs</td><td>(<?=money($report['expenses_total'])?>)</td></tr></tbody><tfoot><tr class="<?=$positive?'table-success':'table-danger'?>"><td>Net <?=$positive?'profit':'loss'?></td><td class="explain">Estimated result for the month</td><td><?=money($report['net_profit'])?></td></tr><tr><td>Net margin</td><td class="explain">Net result as a percentage of sales</td><td><?=number_format($report['profit_margin'],1)?>%</td></tr></tfoot></table></div></div></div>
 <div class="col-xl-6"><div class="card finance-card h-100"><div class="card-header section-title"><i class="fas fa-money-bill-transfer me-2"></i>Operating Cash Movement</div><div class="card-body p-0"><table class="table statement mb-0"><thead><tr><th>Cash movement</th><th class="explain">Meaning</th><th>Amount</th></tr></thead><tbody><?php foreach($receiptTypes as $type=>$amount):?><tr><td><?=fh($type)?></td><td class="explain">Money received</td><td class="amount-positive"><?=money($amount)?></td></tr><?php endforeach;?><tr><td>Total recorded inflows</td><td class="explain">All supported cash-equivalent receipts</td><td><?=money($report['cash_in'])?></td></tr><tr><td>Less: expense outflows</td><td class="explain">Expenses are treated as paid cash outflows</td><td class="amount-negative">(<?=money($report['cash_out'])?>)</td></tr></tbody><tfoot><tr class="<?=$report['net_cash']>=0?'table-success':'table-danger'?>"><td>Net operating cash movement</td><td class="explain">Inflows less outflowsâ€”not a bank balance</td><td><?=money($report['net_cash'])?></td></tr><tr><td>Bank deposits recorded</td><td class="explain">Cash transferred to bank; not counted again as income</td><td><?=money($report['bank_deposits'])?></td></tr></tfoot></table></div></div></div></div>

 <div class="alert alert-warning"><strong>Accounting note:</strong> Gross profit is estimated using the configured <?=number_format($rate*100,1)?>% rate because this systemâ€™s existing profit report uses that policy. Lay-by, credit and order payments appear in cash receipts but are not counted again as sales revenue. â€œNet cash movementâ€ is not the closing cash or bank balance because the system does not store a complete opening-balance ledger.</div>

 <div class="card finance-card mb-4"><div class="card-header section-title">Branch Performance</div><div class="table-responsive"><table class="table table-striped mb-0"><thead><tr><th>Branch</th><th class="text-end">Sales</th><th class="text-end">Gross profit</th><th class="text-end">Expenses</th><th class="text-end">Net result</th><th class="text-end">Cash received</th></tr></thead><tbody><?php if(!$report['branches']):?><tr><td colspan="6" class="text-center text-muted py-3">No data</td></tr><?php endif;foreach($report['branches'] as $name=>$row):?><tr><td><?=fh($name)?></td><td class="text-end"><?=money($row['revenue'])?></td><td class="text-end"><?=money($row['gross_profit'])?></td><td class="text-end"><?=money($row['expenses'])?></td><td class="text-end <?=$row['net_profit']>=0?'amount-positive':'amount-negative'?>"><?=money($row['net_profit'])?></td><td class="text-end"><?=money($row['cash_in'])?></td></tr><?php endforeach;?></tbody></table></div></div>

 <div class="row g-4 mb-4"><div class="col-lg-5"><div class="card finance-card h-100"><div class="card-header section-title">Expenses by Category</div><div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Category</th><th class="text-end">Entries</th><th class="text-end">Amount</th></tr></thead><tbody><?php foreach($report['expense_categories'] as $row):?><tr><td><?=fh($row['label'])?></td><td class="text-end"><?=number_format($row['expense_count'])?></td><td class="text-end"><?=money($row['total_amount'])?></td></tr><?php endforeach;?></tbody></table></div></div></div><div class="col-lg-7"><div class="card finance-card h-100"><div class="card-header section-title">Daily Movement</div><div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Date</th><th class="text-end">Sales</th><th class="text-end">Cash in</th><th class="text-end">Expenses</th><th class="text-end">Net cash</th></tr></thead><tbody><?php foreach($report['daily'] as $day=>$row):?><tr><td><?=fh(date('d M Y',strtotime($day)))?></td><td class="text-end"><?=money($row['revenue'])?></td><td class="text-end"><?=money($row['cash_in'])?></td><td class="text-end"><?=money($row['expenses'])?></td><td class="text-end <?=$row['net_cash']>=0?'amount-positive':'amount-negative'?>"><?=money($row['net_cash'])?></td></tr><?php endforeach;?></tbody></table></div></div></div></div>

 <div class="card finance-card mb-4"><div class="card-header section-title">Income Detail â€” Sales Transactions</div><div class="scroll-table table-responsive"><table class="table table-sm table-striped mb-0"><thead class="sticky-top table-light"><tr><th>Date</th><th>Reference</th><th>Customer</th><th>Items</th><th>Branch</th><th>Method</th><th class="text-end">Revenue</th></tr></thead><tbody><?php if(!$report['sales']):?><tr><td colspan="7" class="text-center text-muted py-3">No sales</td></tr><?php endif;foreach($report['sales'] as $row):?><tr><td><?=fh(date('d M Y',strtotime($row['date'])))?></td><td><?=fh($row['reference'])?></td><td><?=fh($row['customer'])?></td><td><?=fh(implode(', ',$row['items']))?></td><td><?=fh($row['branch_name'])?></td><td><?=fh(ucwords($row['payment_method']))?></td><td class="text-end"><?=money($row['amount'])?></td></tr><?php endforeach;?></tbody><tfoot><tr><td colspan="6" class="text-end">Total sales</td><td class="text-end"><?=money($report['revenue'])?></td></tr></tfoot></table></div></div>

 <div class="card finance-card mb-4"><div class="card-header section-title">Cash Receipt Detail</div><div class="scroll-table table-responsive"><table class="table table-sm table-striped mb-0"><thead class="sticky-top table-light"><tr><th>Date</th><th>Type</th><th>Reference</th><th>Description</th><th>Branch</th><th>Method</th><th class="text-end">Amount</th></tr></thead><tbody><?php if(!$report['receipts']):?><tr><td colspan="7" class="text-center text-muted py-3">No receipts</td></tr><?php endif;foreach($report['receipts'] as $row):?><tr><td><?=fh(date('d M Y',strtotime($row['date'])))?></td><td><?=fh($row['type'])?></td><td><?=fh($row['reference'])?></td><td><?=fh($row['description'])?></td><td><?=fh($row['branch_name'])?></td><td><?=fh(ucwords($row['method']))?></td><td class="text-end"><?=money($row['amount'])?></td></tr><?php endforeach;?></tbody><tfoot><tr><td colspan="6" class="text-end">Total receipts</td><td class="text-end"><?=money($report['cash_in'])?></td></tr></tfoot></table></div></div>

 <div class="card finance-card"><div class="card-header section-title">Expense Detail</div><div class="scroll-table table-responsive"><table class="table table-sm table-striped mb-0"><thead class="sticky-top table-light"><tr><th>Date</th><th>Category</th><th>Description</th><th>Branch</th><th>Recorded by</th><th class="text-end">Amount</th></tr></thead><tbody><?php if(!$report['expenses']):?><tr><td colspan="6" class="text-center text-muted py-3">No expenses</td></tr><?php endif;foreach($report['expenses'] as $row):?><tr><td><?=fh(date('d M Y',strtotime($row['expense_date'])))?></td><td><?=fh($row['category_name']?:'Uncategorised')?></td><td><?=fh($row['description'])?></td><td><?=fh($row['branch_name']?:'Unassigned')?></td><td><?=fh($row['username']?:'Unknown')?></td><td class="text-end"><?=money($row['amount'])?></td></tr><?php endforeach;?></tbody><tfoot><tr><td colspan="5" class="text-end">Total expenses</td><td class="text-end"><?=money($report['expenses_total'])?></td></tr></tfoot></table></div></div>
</div>
<?php include __DIR__.'/../../includes/footer.php'; ?>
