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

$auth = new Auth($conn);
if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
    die("Access denied. Admin privileges required.");
}

require_once __DIR__ . '/../../classes/Projections.php';
$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;
        }
    }
}

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

$nextMonthLabel = date('M Y', strtotime('first day of +1 month'));
$projectedSalesNext = $report['sales_projection']['projected'][0] ?? 0;
$projectedExpensesNext = $report['expense_projection']['projected'][0] ?? 0;
$projectedNetNext = $report['net_projected'][0] ?? 0;

$salesVsTarget = $report['sales_target'] > 0 ? $projectedSalesNext - $report['sales_target'] : null;
$expenseVsAllocation = $report['expense_allocation'] > 0 ? $projectedExpensesNext - $report['expense_allocation'] : null;

$exportParams = http_build_query([
    'branch_id' => $selectedBranchId ?: '',
    'history' => $monthsBack,
    'horizon' => $horizon,
]);
?>

<div class="container-fluid mt-4">
    <div class="row mb-3">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../dashboard/admin.php">Admin Dashboard</a></li>
                    <li class="breadcrumb-item active">Financial Projections</li>
                </ol>
            </nav>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-12 d-flex justify-content-between align-items-start flex-wrap gap-2">
            <div>
                <h2><i class="fas fa-chart-line me-2"></i>Financial Projections Report</h2>
                <p class="text-muted mb-0">Data-driven revenue, expense and net profit forecasts based on historical trends</p>
            </div>
            <div class="text-end d-print-none">
                <small class="text-muted d-block mb-1">Generated <?php echo date('M d, Y H:i'); ?> &bull; Scope: <?php echo htmlspecialchars($branchName); ?></small>
                <a class="btn btn-outline-secondary btn-sm" href="generate_financial_projections_pdf.php?<?php echo $exportParams; ?>">
                    <i class="fas fa-file-pdf me-1"></i>Export PDF
                </a>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="window.print()">
                    <i class="fas fa-print me-1"></i>Print
                </button>
            </div>
        </div>
    </div>

    <div class="alert alert-info d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <i class="fas fa-percent me-2"></i>
            Profit margin applied: <strong><?php echo number_format($report['profit_percentage'], 1); ?>%</strong> of sold price &mdash; Gross Profit and Net Profit figures below use this rate.
        </div>
        <a href="settings.php" class="btn btn-outline-primary btn-sm d-print-none">
            <i class="fas fa-cog me-1"></i>Change in Settings
        </a>
    </div>

    <div class="card mb-4 d-print-none">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-filter me-2"></i>Filter Options</h5>
        </div>
        <div class="card-body">
            <form class="row g-3" method="GET">
                <div class="col-md-4">
                    <label for="branch_id" class="form-label">Branch</label>
                    <select class="form-select" id="branch_id" name="branch_id">
                        <option value="">All Branches (Consolidated)</option>
                        <?php foreach ($branches as $b): ?>
                            <option value="<?php echo $b['branch_id']; ?>" <?php echo ($selectedBranchId === (int) $b['branch_id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($b['branch_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="history" class="form-label">History Used</label>
                    <select class="form-select" id="history" name="history">
                        <?php foreach ([3, 6, 12] as $opt): ?>
                            <option value="<?php echo $opt; ?>" <?php echo ($monthsBack === $opt) ? 'selected' : ''; ?>><?php echo $opt; ?> months</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="horizon" class="form-label">Projection Horizon</label>
                    <select class="form-select" id="horizon" name="horizon">
                        <?php foreach ([1, 3, 6] as $opt): ?>
                            <option value="<?php echo $opt; ?>" <?php echo ($horizon === $opt) ? 'selected' : ''; ?>><?php echo $opt; ?> month<?php echo $opt > 1 ? 's' : ''; ?> ahead</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-sync me-2"></i>Update Report
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card border-primary h-100">
                <div class="card-body text-center">
                    <div class="text-primary mb-2"><i class="fas fa-money-bill-wave fa-2x"></i></div>
                    <h6 class="card-title">Projected Revenue</h6>
                    <h4 class="text-primary">MWK <?php echo number_format($projectedSalesNext, 2); ?></h4>
                    <small class="text-muted"><?php echo $nextMonthLabel; ?></small>
                    <?php if ($salesVsTarget !== null): ?>
                        <div class="mt-1">
                            <span class="badge <?php echo $salesVsTarget >= 0 ? 'bg-success' : 'bg-danger'; ?>">
                                <?php echo $salesVsTarget >= 0 ? '+' : ''; ?>MWK <?php echo number_format($salesVsTarget, 0); ?> vs target
                            </span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-warning h-100">
                <div class="card-body text-center">
                    <div class="text-warning mb-2"><i class="fas fa-receipt fa-2x"></i></div>
                    <h6 class="card-title">Projected Expenses</h6>
                    <h4 class="text-warning">MWK <?php echo number_format($projectedExpensesNext, 2); ?></h4>
                    <small class="text-muted"><?php echo $nextMonthLabel; ?></small>
                    <?php if ($expenseVsAllocation !== null): ?>
                        <div class="mt-1">
                            <span class="badge <?php echo $expenseVsAllocation <= 0 ? 'bg-success' : 'bg-danger'; ?>">
                                <?php echo $expenseVsAllocation >= 0 ? '+' : ''; ?>MWK <?php echo number_format($expenseVsAllocation, 0); ?> vs allocation
                            </span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card <?php echo $projectedNetNext >= 0 ? 'border-success' : 'border-danger'; ?> h-100">
                <div class="card-body text-center">
                    <div class="<?php echo $projectedNetNext >= 0 ? 'text-success' : 'text-danger'; ?> mb-2">
                        <i class="fas <?php echo $projectedNetNext >= 0 ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down'; ?> fa-2x"></i>
                    </div>
                    <h6 class="card-title">Projected Net Profit</h6>
                    <h4 class="<?php echo $projectedNetNext >= 0 ? 'text-success' : 'text-danger'; ?>">
                        MWK <?php echo number_format($projectedNetNext, 2); ?>
                    </h4>
                    <small class="text-muted"><?php echo $nextMonthLabel; ?></small>
                    <div class="mt-1">
                        <span class="badge bg-light text-dark border">
                            Gross Profit: MWK <?php echo number_format($report['gross_profit_projected'][0] ?? 0, 2); ?> (<?php echo number_format($report['profit_percentage'], 1); ?>% of sales)
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card border-info h-100">
                <div class="card-body text-center">
                    <div class="text-info mb-2"><i class="fas fa-bullseye fa-2x"></i></div>
                    <h6 class="card-title">Revenue Trend</h6>
                    <h4 class="text-info">
                        <?php echo $report['sales_projection']['growth_rate_pct'] >= 0 ? '+' : ''; ?><?php echo number_format($report['sales_projection']['growth_rate_pct'], 1); ?>%
                    </h4>
                    <small class="text-muted">per month</small>
                    <div class="mt-1">
                        <span class="badge bg-secondary">Confidence: <?php echo $report['sales_projection']['confidence']; ?></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-chart-area me-2"></i>Sales, Expenses &amp; Net Profit &mdash; Actual vs Projected</h5>
        </div>
        <div class="card-body">
            <div style="height: 400px;">
                <canvas id="projectionChart"></canvas>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-table me-2"></i>Monthly Breakdown</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Month</th>
                                    <th class="text-end">Sales</th>
                                    <th class="text-end">Gross Profit (<?php echo number_format($report['profit_percentage'], 1); ?>%)</th>
                                    <th class="text-end">Expenses</th>
                                    <th class="text-end">Net</th>
                                    <th class="text-center">Type</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($report['months'] as $i => $m): ?>
                                    <tr>
                                        <td><?php echo date('M Y', strtotime($m . '-01')); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($report['sales_history'][$i], 2); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($report['gross_profit_history'][$i], 2); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($report['expense_history'][$i], 2); ?></td>
                                        <td class="text-end fw-bold <?php echo $report['net_history'][$i] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                            MWK <?php echo number_format($report['net_history'][$i], 2); ?>
                                        </td>
                                        <td class="text-center"><span class="badge bg-light text-dark border">Actual</span></td>
                                    </tr>
                                <?php endforeach; ?>
                                <tr class="table-secondary">
                                    <td><?php echo date('M Y'); ?> (to date)</td>
                                    <td class="text-end">MWK <?php echo number_format($report['month_to_date_sales'], 2); ?></td>
                                    <td class="text-end">MWK <?php echo number_format($report['month_to_date_gross_profit'], 2); ?></td>
                                    <td class="text-end">MWK <?php echo number_format($report['month_to_date_expenses'], 2); ?></td>
                                    <td class="text-end fw-bold">MWK <?php echo number_format($report['month_to_date_gross_profit'] - $report['month_to_date_expenses'], 2); ?></td>
                                    <td class="text-center"><span class="badge bg-warning text-dark">In Progress</span></td>
                                </tr>
                                <?php foreach ($report['sales_projection']['projected'] as $i => $s): ?>
                                    <tr>
                                        <td><?php echo date('M Y', strtotime('first day of +' . ($i + 1) . ' month')); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($s, 2); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($report['gross_profit_projected'][$i], 2); ?></td>
                                        <td class="text-end">MWK <?php echo number_format($report['expense_projection']['projected'][$i], 2); ?></td>
                                        <td class="text-end fw-bold <?php echo $report['net_projected'][$i] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                            MWK <?php echo number_format($report['net_projected'][$i], 2); ?>
                                        </td>
                                        <td class="text-center"><span class="badge bg-info text-dark">Projected</span></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-tags me-2"></i>Expense Breakdown</h5>
                    <small class="text-muted">Last <?php echo $monthsBack; ?> months by category</small>
                </div>
                <div class="card-body">
                    <?php if (empty($report['category_breakdown'])): ?>
                        <p class="text-muted text-center mb-0">No expense records in this period.</p>
                    <?php else: ?>
                        <ul class="list-group list-group-flush">
                            <?php foreach ($report['category_breakdown'] as $cat): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center px-0">
                                    <?php echo htmlspecialchars($cat['category_name']); ?>
                                    <span class="fw-bold">MWK <?php echo number_format($cat['total'], 2); ?></span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <?php if (!$selectedBranchId): ?>
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-store me-2"></i>Branch Outlook &mdash; <?php echo date('M Y', strtotime('+1 month')); ?> Projection</h5>
        </div>
        <div class="card-body">
            <?php if (empty($perBranch)): ?>
                <p class="text-muted text-center mb-0">No branch data available.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Branch</th>
                                <th class="text-end">Projected Sales</th>
                                <th class="text-end">Projected Gross Profit</th>
                                <th class="text-end">Projected Expenses</th>
                                <th class="text-end">Projected Net</th>
                                <th class="text-end">Trend</th>
                                <th class="text-center">Confidence</th>
                                <th class="text-center">Outlook</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($perBranch as $row): ?>
                                <tr>
                                    <td class="fw-bold"><?php echo htmlspecialchars($row['branch_name']); ?></td>
                                    <td class="text-end">MWK <?php echo number_format($row['projected_sales'], 2); ?></td>
                                    <td class="text-end">MWK <?php echo number_format($row['projected_gross_profit'], 2); ?></td>
                                    <td class="text-end">MWK <?php echo number_format($row['projected_expenses'], 2); ?></td>
                                    <td class="text-end fw-bold <?php echo $row['projected_net'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                        MWK <?php echo number_format($row['projected_net'], 2); ?>
                                    </td>
                                    <td class="text-end"><?php echo $row['growth_rate_pct'] >= 0 ? '+' : ''; ?><?php echo number_format($row['growth_rate_pct'], 1); ?>%</td>
                                    <td class="text-center"><span class="badge bg-secondary"><?php echo $row['confidence']; ?></span></td>
                                    <td class="text-center">
                                        <span class="badge <?php echo $row['projected_net'] >= 0 ? 'bg-success' : 'bg-danger'; ?>">
                                            <?php echo $row['projected_net'] >= 0 ? 'Profitable' : 'At Risk'; ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>

    <div class="card mb-4 d-print-none">
        <div class="card-header">
            <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Methodology</h5>
        </div>
        <div class="card-body">
            <p class="mb-2">Projections are computed with a <strong><?php echo Projections::MOVING_AVERAGE_WINDOW; ?>-month moving average blended with a linear trend line</strong> fitted to the historical months shown above. The current calendar month is shown separately as "In Progress" and is excluded from the trend calculation because it is incomplete.</p>
            <p class="mb-2"><strong>Gross Profit</strong> is Sales &times; <?php echo number_format($report['profit_percentage'], 1); ?>% &mdash; the profit margin configured on the <a href="settings.php">Settings</a> page, the same rate used by the Profit &amp; Loss report. <strong>Net Profit</strong> = Gross Profit &minus; Expenses. Sold price is not treated as 100% profit.</p>
            <p class="mb-2"><strong>Confidence</strong> reflects how much historical data is available and how stable it has been: <span class="badge bg-secondary">High</span> needs 6+ months of consistent history, <span class="badge bg-secondary">Medium</span> needs 4+ months with moderate variability, and <span class="badge bg-secondary">Low</span> applies when history is short or volatile.</p>
            <p class="mb-0 text-muted"><small>Projections are statistical estimates based on past performance, not guarantees of future results. Use alongside management judgement, especially for branches with seasonal demand or one-off events.</small></p>
        </div>
    </div>

    <div class="d-print-none">
        <a href="../dashboard/admin.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>
</div>

<script>
const projectionMonths = <?php echo json_encode(array_merge(
    array_map(function ($m) { return date('M Y', strtotime($m . '-01')); }, $report['months']),
    [date('M Y') . ' (to date)'],
    array_map(function ($i) { return date('M Y', strtotime('first day of +' . ($i + 1) . ' month')); }, array_keys($report['sales_projection']['projected']))
)); ?>;
const historyCount = <?php echo count($report['months']); ?>;

const actualSales = <?php echo json_encode(array_merge($report['sales_history'], [$report['month_to_date_sales']])); ?>;
const actualExpenses = <?php echo json_encode(array_merge($report['expense_history'], [$report['month_to_date_expenses']])); ?>;

const projectedSalesFull = new Array(historyCount + 1).fill(null).concat(<?php echo json_encode($report['sales_projection']['projected']); ?>);
const projectedExpensesFull = new Array(historyCount + 1).fill(null).concat(<?php echo json_encode($report['expense_projection']['projected']); ?>);

// Bridge the actual/projected lines so the chart doesn't show a gap.
projectedSalesFull[historyCount] = actualSales[historyCount];
projectedExpensesFull[historyCount] = actualExpenses[historyCount];

const actualSalesFull = actualSales.concat(new Array(<?php echo $horizon; ?>).fill(null));
const actualExpensesFull = actualExpenses.concat(new Array(<?php echo $horizon; ?>).fill(null));

const ctx = document.getElementById('projectionChart').getContext('2d');
new Chart(ctx, {
    type: 'line',
    data: {
        labels: projectionMonths,
        datasets: [
            {
                label: 'Sales (Actual)',
                data: actualSalesFull,
                borderColor: 'rgba(13, 110, 253, 1)',
                backgroundColor: 'rgba(13, 110, 253, 0.15)',
                fill: true,
                tension: 0.25,
            },
            {
                label: 'Sales (Projected)',
                data: projectedSalesFull,
                borderColor: 'rgba(13, 110, 253, 1)',
                borderDash: [6, 4],
                backgroundColor: 'transparent',
                fill: false,
                tension: 0.25,
            },
            {
                label: 'Expenses (Actual)',
                data: actualExpensesFull,
                borderColor: 'rgba(255, 193, 7, 1)',
                backgroundColor: 'rgba(255, 193, 7, 0.15)',
                fill: true,
                tension: 0.25,
            },
            {
                label: 'Expenses (Projected)',
                data: projectedExpensesFull,
                borderColor: 'rgba(255, 193, 7, 1)',
                borderDash: [6, 4],
                backgroundColor: 'transparent',
                fill: false,
                tension: 0.25,
            },
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        interaction: { mode: 'index', intersect: false },
        plugins: {
            legend: { position: 'top' },
            tooltip: {
                callbacks: {
                    label: function (context) {
                        if (context.parsed.y === null) return null;
                        return (context.dataset.label || '') + ': MWK ' + context.parsed.y.toLocaleString();
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function (value) { return 'MWK ' + value.toLocaleString(); }
                }
            }
        }
    }
});
</script>

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