<?php
session_start();
require_once __DIR__.'/../../vendor/autoload.php';
require_once __DIR__.'/../../includes/auth.php';
require_once __DIR__.'/../../classes/Database.php';
require_once __DIR__.'/../../classes/FinancialReport.php';
require_once __DIR__.'/../../classes/SystemSettings.php';
require_once __DIR__.'/../../classes/Branding.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)){http_response_code(400);exit('Invalid month.');}
$branchId=!empty($_GET['branch'])?(int)$_GET['branch']:null;$rate=(new SystemSettings(null,$conn))->profitRate();
$r=(new FinancialReport($conn))->monthly($month,$branchId,$rate);$monthLabel=date('F Y',strtotime($month.'-01'));
$company=Branding::companyName();$logo=Branding::logoFilePath();$branchName='All Branches';
if($branchId){$s=$conn->prepare('SELECT * FROM branches WHERE branch_id=?');$s->execute([$branchId]);$branch=$s->fetch(PDO::FETCH_ASSOC);if($branch){$branchName=$branch['branch_name'];$brand=Branding::documentDetailsForBranch($branch);$company=$brand['name'];$logo=$brand['logo_file'];}}
function ph($v){return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}function pm($v){return 'MWK '.number_format((float)$v,2);}
$pdf=new TCPDF('L',PDF_UNIT,PDF_PAGE_FORMAT,true,'UTF-8',false);$pdf->SetCreator($company);$pdf->SetAuthor($_SESSION['username']??$company);$pdf->SetTitle("Monthly Financial Overview - {$monthLabel}");$pdf->SetHeaderData(is_file($logo)?$logo:'',16,$company,"Monthly Financial Overview\n{$monthLabel} | {$branchName}");$pdf->setHeaderFont([PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN]);$pdf->setFooterFont([PDF_FONT_NAME_DATA,'',PDF_FONT_SIZE_DATA]);$pdf->SetMargins(10,29,10);$pdf->SetHeaderMargin(6);$pdf->SetFooterMargin(8);$pdf->SetAutoPageBreak(true,14);$pdf->SetFont('helvetica','',8);$pdf->AddPage();
$profitLabel=$r['net_profit']>=0?'profit':'loss';$cashLabel=$r['net_cash']>=0?'surplus':'shortfall';
$html='<h1 style="text-align:center">Monthly Financial Overview</h1><p style="text-align:center;color:#555">Income, operating cash movement, expenses and profit or loss</p>';
$html.='<table cellpadding="6" style="background-color:#eef5ff"><tr><td><b>Executive Financial Summary</b><br>Sales were '.pm($r['revenue']).'. After estimated cost of sales and operating expenses, the business made a '.$profitLabel.' of <b>'.pm(abs($r['net_profit'])).'</b>. Recorded operating cash movement was a '.$cashLabel.' of <b>'.pm(abs($r['net_cash'])).'</b>.</td></tr></table><br>';
$html.='<h2>1. Profit &amp; Loss Statement</h2><table border="1" cellpadding="5"><tr style="background-color:#2c3e50;color:#fff;font-weight:bold"><th width="35%">Line</th><th width="40%">Description</th><th width="25%" align="right">Amount</th></tr>';
$lines=[['Sales revenue','Goods sold during the month',$r['revenue'],false],['Less: estimated cost of sales','Estimated cost of goods sold',$r['cost_of_sales'],true],['Estimated gross profit',number_format($rate*100,1).'% configured gross-profit rate',$r['gross_profit'],false],['Less: operating expenses','Day-to-day business costs',$r['expenses_total'],true],['Net profit / loss','What remains after operating expenses',$r['net_profit'],false]];
foreach($lines as $x)$html.='<tr><td><b>'.ph($x[0]).'</b></td><td>'.ph($x[1]).'</td><td align="right">'.($x[3]?'(':'').pm($x[2]).($x[3]?')':'').'</td></tr>';$html.='</table><br>';
$html.='<h2>2. Operating Cash Movement</h2><table border="1" cellpadding="5"><tr style="background-color:#2c3e50;color:#fff;font-weight:bold"><th width="50%">Line</th><th width="25%">Meaning</th><th width="25%" align="right">Amount</th></tr><tr><td>Total cash-equivalent receipts</td><td>Money received</td><td align="right">'.pm($r['cash_in']).'</td></tr><tr><td>Less: recorded expense outflows</td><td>Money treated as paid out</td><td align="right">('.pm($r['cash_out']).')</td></tr><tr><td><b>Net operating cash movement</b></td><td>Not a bank balance</td><td align="right"><b>'.pm($r['net_cash']).'</b></td></tr><tr><td>Bank deposits recorded</td><td>Transfer only; not income again</td><td align="right">'.pm($r['bank_deposits']).'</td></tr></table>';
$html.='<p style="font-size:8px;color:#805b00"><b>Accounting note:</b> Gross profit is estimated using the configured '.number_format($rate*100,1).'% rate. Lay-by, credit and order receipts are included in cash received but not counted again as sales. Net cash movement is not a closing cash or bank balance.</p>';
$pdf->writeHTML($html,true,false,true,false,'');

function tableHead($title,$columns){$h='<h2>'.ph($title).'</h2><table border="1" cellpadding="3"><tr style="background-color:#2c3e50;color:#fff;font-weight:bold">';foreach($columns as $c)$h.='<th width="'.$c[1].'%"'.($c[2]?' align="right"':'').'>'.ph($c[0]).'</th>';return $h.'</tr>';}
$html=tableHead('3. Branch Performance',[['Branch',25,false],['Sales',15,true],['Gross Profit',15,true],['Expenses',15,true],['Net Result',15,true],['Cash Received',15,true]]);foreach($r['branches'] as $name=>$x)$html.='<tr><td>'.ph($name).'</td><td align="right">'.pm($x['revenue']).'</td><td align="right">'.pm($x['gross_profit']).'</td><td align="right">'.pm($x['expenses']).'</td><td align="right">'.pm($x['net_profit']).'</td><td align="right">'.pm($x['cash_in']).'</td></tr>';$html.='</table><br>';
$html.=tableHead('4. Expenses by Category',[['Category',55,false],['Entries',15,true],['Amount',30,true]]);foreach($r['expense_categories'] as $x)$html.='<tr><td>'.ph($x['label']).'</td><td align="right">'.number_format($x['expense_count']).'</td><td align="right">'.pm($x['total_amount']).'</td></tr>';$html.='</table>';$pdf->writeHTML($html,true,false,true,false,'');

$html=tableHead('5. Income Detail — Sales Transactions',[['Date',10,false],['Reference',15,false],['Customer',15,false],['Items',25,false],['Branch',15,false],['Method',8,false],['Revenue',12,true]]);foreach($r['sales'] as $x)$html.='<tr><td>'.date('d M Y',strtotime($x['date'])).'</td><td>'.ph($x['reference']).'</td><td>'.ph($x['customer']).'</td><td>'.ph(implode(', ',$x['items'])).'</td><td>'.ph($x['branch_name']).'</td><td>'.ph($x['payment_method']).'</td><td align="right">'.pm($x['amount']).'</td></tr>';$html.='<tr style="font-weight:bold"><td colspan="6" align="right">Total sales</td><td align="right">'.pm($r['revenue']).'</td></tr></table>';$pdf->writeHTML($html,true,false,true,false,'');

$html=tableHead('6. Cash Receipt Detail',[['Date',10,false],['Type',14,false],['Reference',14,false],['Description',24,false],['Branch',16,false],['Method',10,false],['Amount',12,true]]);foreach($r['receipts'] as $x)$html.='<tr><td>'.date('d M Y',strtotime($x['date'])).'</td><td>'.ph($x['type']).'</td><td>'.ph($x['reference']).'</td><td>'.ph($x['description']).'</td><td>'.ph($x['branch_name']).'</td><td>'.ph($x['method']).'</td><td align="right">'.pm($x['amount']).'</td></tr>';$html.='<tr style="font-weight:bold"><td colspan="6" align="right">Total receipts</td><td align="right">'.pm($r['cash_in']).'</td></tr></table>';$pdf->writeHTML($html,true,false,true,false,'');

$html=tableHead('7. Expense Detail',[['Date',12,false],['Category',18,false],['Description',30,false],['Branch',18,false],['Recorded By',10,false],['Amount',12,true]]);foreach($r['expenses'] as $x)$html.='<tr><td>'.date('d M Y',strtotime($x['expense_date'])).'</td><td>'.ph($x['category_name']?:'Uncategorised').'</td><td>'.ph($x['description']).'</td><td>'.ph($x['branch_name']?:'Unassigned').'</td><td>'.ph($x['username']?:'Unknown').'</td><td align="right">'.pm($x['amount']).'</td></tr>';$html.='<tr style="font-weight:bold"><td colspan="5" align="right">Total expenses</td><td align="right">'.pm($r['expenses_total']).'</td></tr></table><p style="font-size:8px;color:#666">Generated '.date('d M Y H:i').' by '.ph($_SESSION['username']??'System').'.</p>';$pdf->writeHTML($html,true,false,true,false,'');
$filename='Monthly_Financial_Overview_'.$month.'_'.preg_replace('/[^A-Za-z0-9_-]+/','_',$branchName).'.pdf';
$fileOutput=getenv('FINANCIAL_PDF_OUTPUT');
$pdf->Output($fileOutput?:$filename,$fileOutput?'F':'D');
