<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();

require_once '../../vendor/autoload.php';
require_once '../../classes/Database.php';
require_once '../../classes/Projections.php';

session_start();
require_once '../../includes/auth.php';
$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);

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

$projections = new Projections($conn);
$branches = $projections->getBranches();

$selectedBranchId = (isset($_GET['branch_id']) && $_GET['branch_id'] !== '') ? (int) $_GET['branch_id'] : null;
$monthsBack = isset($_GET['history']) ? max(3, min(24, (int) $_GET['history'])) : 6;
$horizon = isset($_GET['horizon']) ? max(1, min(6, (int) $_GET['horizon'])) : 3;

$branchName = 'All Branches (Consolidated)';
if ($selectedBranchId) {
    foreach ($branches as $b) {
        if ((int) $b['branch_id'] === $selectedBranchId) {
            $branchName = $b['branch_name'];
            break;
        }
    }
}
$projectionBranding = $selectedBranchId
    ? Branding::documentDetailsForBranchId($conn, $selectedBranchId)
    : Branding::companyDetails();
$companyName = $projectionBranding['name'];

$report = $projections->buildReport($selectedBranchId, $monthsBack, $horizon);
$perBranch = $selectedBranchId ? [] : $projections->getPerBranchSummary($monthsBack);

$projectedSalesNext = $report['sales_projection']['projected'][0] ?? 0;
$projectedExpensesNext = $report['expense_projection']['projected'][0] ?? 0;
$projectedNetNext = $report['net_projected'][0] ?? 0;

class FinancialProjectionPdf extends TCPDF {
    public array $documentBranding = [];
    public string $documentScope = '';

    public function Header() {
        $logoFile = (string)($this->documentBranding['logo_file'] ?? '');
        $hasLocalLogo = $logoFile !== '' && is_file($logoFile);
        if ($hasLocalLogo) {
            $this->Image($logoFile, 15, 7, 18, 14, '', '', '', true, 300, '', false, false, 0, 'CM');
        }

        $textX = $hasLocalLogo ? 38 : 15;
        $this->SetXY($textX, 7);
        $this->SetFont('helvetica', 'B', 10);
        $this->Cell(0, 5, (string)($this->documentBranding['name'] ?? ''), 0, 1);
        $this->SetX($textX);
        $this->SetFont('helvetica', '', 8);
        $this->MultiCell(0, 4, "Financial Projections Report\n" . $this->documentScope . "\nGenerated: " . date('M d, Y H:i'), 0, 'L');
        $this->SetDrawColor(120, 135, 150);
        $this->Line(15, 24, $this->getPageWidth() - 15, 24);
    }
}

try {
    $pdf = new FinancialProjectionPdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->documentBranding = $projectionBranding;
    $pdf->documentScope = $branchName;

    $pdf->SetCreator($companyName);
    $pdf->SetAuthor($_SESSION['username']);
    $pdf->SetTitle('Financial Projections Report - ' . $branchName);
    $pdf->SetSubject('Financial Projections Report for ' . $branchName);
    $pdf->SetKeywords('financial, projections, forecast, sales, expenses, ' . $companyName);

    $pdf->setHeaderFont([PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN]);
    $pdf->setFooterFont([PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA]);

    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

    $pdf->SetFont('helvetica', '', 10);

    $pdf->AddPage();

    $companyDetails = $companyName . "\n" . Branding::contactLine($projectionBranding, "\n");
    $pdf->MultiCell(0, 10, $companyDetails, 0, 'C', 0, 1, '', '', true);
    $pdf->Ln(5);

    $profitPercentage = $report['profit_percentage'];
    $reportDetails = <<<EOD
<b>Financial Projections Report</b>
<b>Scope:</b> $branchName
<b>History Used:</b> Last {$monthsBack} complete months &nbsp; <b>Horizon:</b> {$horizon} month(s) ahead
<b>Profit Margin Applied:</b> {$profitPercentage}% of sold price (from Settings)
<b>Projected Revenue (next month):</b> MWK {$projectedSalesNext}
<b>Projected Expenses (next month):</b> MWK {$projectedExpensesNext}
<b>Projected Net Profit (next month):</b> MWK {$projectedNetNext}
<b>Confidence:</b> {$report['sales_projection']['confidence']} &nbsp; <b>Method:</b> {$report['sales_projection']['method']}
EOD;
    $pdf->writeHTML($reportDetails, true, false, true, false, '');
    $pdf->Ln(5);

    // Monthly breakdown table
    $html = '<h4>Monthly Breakdown</h4>';
    $html .= '<table border="1" cellpadding="4">';
    $html .= '<tr style="background-color:#f8f9fa;color:#2c3e50;font-weight:bold;">';
    $html .= '<th width="18%">Month</th><th width="16%">Sales</th><th width="18%">Gross Profit</th><th width="16%">Expenses</th><th width="16%">Net</th><th width="16%">Type</th>';
    $html .= '</tr>';

    foreach ($report['months'] as $i => $m) {
        $html .= '<tr>';
        $html .= '<td>' . date('M Y', strtotime($m . '-01')) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['sales_history'][$i], 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['gross_profit_history'][$i], 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['expense_history'][$i], 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['net_history'][$i], 2) . '</td>';
        $html .= '<td style="text-align:center;">Actual</td>';
        $html .= '</tr>';
    }

    $html .= '<tr style="background-color:#f1f1f1;">';
    $html .= '<td>' . date('M Y') . ' (to date)</td>';
    $html .= '<td style="text-align:right;">MWK ' . number_format($report['month_to_date_sales'], 2) . '</td>';
    $html .= '<td style="text-align:right;">MWK ' . number_format($report['month_to_date_gross_profit'], 2) . '</td>';
    $html .= '<td style="text-align:right;">MWK ' . number_format($report['month_to_date_expenses'], 2) . '</td>';
    $html .= '<td style="text-align:right;">MWK ' . number_format($report['month_to_date_gross_profit'] - $report['month_to_date_expenses'], 2) . '</td>';
    $html .= '<td style="text-align:center;">In Progress</td>';
    $html .= '</tr>';

    foreach ($report['sales_projection']['projected'] as $i => $s) {
        $html .= '<tr>';
        $html .= '<td>' . date('M Y', strtotime('first day of +' . ($i + 1) . ' month')) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($s, 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['gross_profit_projected'][$i], 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['expense_projection']['projected'][$i], 2) . '</td>';
        $html .= '<td style="text-align:right;">MWK ' . number_format($report['net_projected'][$i], 2) . '</td>';
        $html .= '<td style="text-align:center;">Projected</td>';
        $html .= '</tr>';
    }
    $html .= '</table>';

    $pdf->writeHTML($html, true, false, true, false, '');
    $pdf->Ln(5);

    // Expense category breakdown
    if (!empty($report['category_breakdown'])) {
        $catHtml = '<h4>Expense Breakdown by Category (Last ' . $monthsBack . ' Months)</h4>';
        $catHtml .= '<table border="1" cellpadding="4">';
        $catHtml .= '<tr style="background-color:#f8f9fa;color:#2c3e50;font-weight:bold;"><th width="70%">Category</th><th width="30%">Total</th></tr>';
        foreach ($report['category_breakdown'] as $cat) {
            $catHtml .= '<tr><td>' . htmlspecialchars($cat['category_name']) . '</td><td style="text-align:right;">MWK ' . number_format($cat['total'], 2) . '</td></tr>';
        }
        $catHtml .= '</table>';
        $pdf->writeHTML($catHtml, true, false, true, false, '');
        $pdf->Ln(5);
    }

    // Per-branch outlook (all branches view only)
    if (!$selectedBranchId && !empty($perBranch)) {
        $branchHtml = '<h4>Branch Outlook &ndash; Next Month Projection</h4>';
        $branchHtml .= '<table border="1" cellpadding="4">';
        $branchHtml .= '<tr style="background-color:#f8f9fa;color:#2c3e50;font-weight:bold;">';
        $branchHtml .= '<th width="20%">Branch</th><th width="16%">Proj. Sales</th><th width="18%">Proj. Gross Profit</th><th width="16%">Proj. Expenses</th><th width="16%">Proj. Net</th><th width="14%">Confidence</th>';
        $branchHtml .= '</tr>';
        foreach ($perBranch as $row) {
            $branchHtml .= '<tr>';
            $branchHtml .= '<td>' . htmlspecialchars($row['branch_name']) . '</td>';
            $branchHtml .= '<td style="text-align:right;">MWK ' . number_format($row['projected_sales'], 2) . '</td>';
            $branchHtml .= '<td style="text-align:right;">MWK ' . number_format($row['projected_gross_profit'], 2) . '</td>';
            $branchHtml .= '<td style="text-align:right;">MWK ' . number_format($row['projected_expenses'], 2) . '</td>';
            $branchHtml .= '<td style="text-align:right;">MWK ' . number_format($row['projected_net'], 2) . '</td>';
            $branchHtml .= '<td style="text-align:center;">' . $row['confidence'] . '</td>';
            $branchHtml .= '</tr>';
        }
        $branchHtml .= '</table>';
        $pdf->writeHTML($branchHtml, true, false, true, false, '');
        $pdf->Ln(5);
    }

    $methodology = <<<EOD
<h4>Methodology</h4>
<p>Projections use a {$report['sales_projection']['method']}. The current calendar month is excluded from the trend calculation because it is incomplete and shown separately as "In Progress". Gross Profit is Sales &times; {$profitPercentage}%, the profit margin configured on the Settings page (same rate used by the Profit &amp; Loss report). Net Profit = Gross Profit - Expenses. Projections are statistical estimates based on past performance and are not guarantees of future results.</p>
EOD;
    $pdf->writeHTML($methodology, true, false, true, false, '');

    $filename = 'Financial_Projections_' . str_replace(' ', '_', $branchName) . '_' . date('Ymd') . '.pdf';
    $pdf->Output($filename, 'D');
} catch (Exception $e) {
    echo "Error generating PDF: " . $e->getMessage();
}
