<?php

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Service\FinancialService;
use ChurchCRM\Service\ExpenseService;
use ChurchCRM\view\PageHeader;

require_once __DIR__ . '/Include/Config.php';
require_once __DIR__ . '/Include/PageInit.php';

// Security: user must have finance permission
AuthenticationManager::redirectHomeIfNotFinance();

$financialService = new FinancialService();
$expenseService = new ExpenseService();

$sPageTitle = gettext('Financial Analysis');
$sPageSubtitle = gettext('Deposits vs Expenses Remaining Balance');

$aBreadcrumbs = PageHeader::breadcrumbs([
    [gettext('Finance'), '/finance/'],
    [gettext('Financial Analysis')],
]);

require_once __DIR__ . '/Include/Header.php';

// Get fiscal year dates
$dashboardData = $financialService->getDashboardData();
$fiscalYear = $dashboardData['fiscalYear'];
$fyStartDate = $fiscalYear['startDate'];
$fyEndDate = $fiscalYear['endDate'];
$fyLabel = $fiscalYear['label'];

// Get financial data
$ytdPaymentTotal = $dashboardData['ytdPaymentTotal'] ?? 0;
$ytdPledgeTotal = $dashboardData['ytdPledgeTotal'] ?? 0;
$totalDeposits = $ytdPaymentTotal + $ytdPledgeTotal;

// Get expense data via API format
$expenseSummary = $expenseService->getDashboardSummary($fyStartDate, $fyEndDate);
$totalExpenses = $expenseSummary['total_expenses'] ?? 0;

// Calculate remaining balance
$remainingBalance = $totalDeposits - $totalExpenses;
$balancePercentage = $totalDeposits > 0 ? ($remainingBalance / $totalDeposits) * 100 : 0;
$expensePercentage = $totalDeposits > 0 ? ($totalExpenses / $totalDeposits) * 100 : 0;

// Determine status color
if ($remainingBalance < 0) {
    $statusColor = 'danger';
    $statusIcon = 'fa-triangle-exclamation';
    $statusText = gettext('Deficit');
} elseif ($remainingBalance < ($totalDeposits * 0.1)) {
    $statusColor = 'warning';
    $statusIcon = 'fa-circle-exclamation';
    $statusText = gettext('Low Balance');
} else {
    $statusColor = 'success';
    $statusIcon = 'fa-check-circle';
    $statusText = gettext('Healthy');
}

$sRootPath = SystemURLs::getRootPath();
?>

<div class="container-fluid">

    <!-- Summary Cards Row -->
    <div class="row mb-4">
        <!-- Total Deposits Card -->
        <div class="col-md-6 col-lg-3">
            <div class="card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-success text-white avatar rounded-circle" style="width: 3rem; height: 3rem; font-size: 1.5rem;">
                                <i class="fa-solid fa-arrow-down-to-bracket"></i>
                            </span>
                        </div>
                        <div class="col">
                            <div class="text-body-secondary"><?= gettext('Total Deposits') ?></div>
                            <div class="fs-5 fw-bold">₦<?= number_format($totalDeposits, 2) ?></div>
                            <div class="text-muted" style="font-size: 0.85rem;">
                                <i class="fa-solid fa-circle-check text-success"></i> YTD Payments: ₦<?= number_format($ytdPaymentTotal, 2) ?><br>
                                <i class="fa-solid fa-file-signature text-info"></i> YTD Pledges: ₦<?= number_format($ytdPledgeTotal, 2) ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Total Expenses Card -->
        <div class="col-md-6 col-lg-3">
            <div class="card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-danger text-white avatar rounded-circle" style="width: 3rem; height: 3rem; font-size: 1.5rem;">
                                <i class="fa-solid fa-arrow-up-from-bracket"></i>
                            </span>
                        </div>
                        <div class="col">
                            <div class="text-body-secondary"><?= gettext('Total Expenses') ?></div>
                            <div class="fs-5 fw-bold">₦<?= number_format($totalExpenses, 2) ?></div>
                            <div class="text-muted" style="font-size: 0.85rem;">
                                <span class="badge bg-danger"><?= $expensePercentage ?>% of Deposits</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Remaining Balance Card -->
        <div class="col-md-6 col-lg-3">
            <div class="card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-<?= $statusColor ?> text-white avatar rounded-circle" style="width: 3rem; height: 3rem; font-size: 1.5rem;">
                                <i class="fa-solid <?= $statusIcon ?>"></i>
                            </span>
                        </div>
                        <div class="col">
                            <div class="text-body-secondary"><?= gettext('Remaining Balance') ?></div>
                            <div class="fs-5 fw-bold <?= $remainingBalance < 0 ? 'text-danger' : 'text-success' ?>">
                                ₦<?= number_format($remainingBalance, 2) ?>
                            </div>
                            <div class="text-muted" style="font-size: 0.85rem;">
                                <span class="badge bg-<?= $statusColor ?>"><?= $statusText ?></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Balance Percentage Card -->
        <div class="col-md-6 col-lg-3">
            <div class="card">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <span class="bg-info text-white avatar rounded-circle" style="width: 3rem; height: 3rem; font-size: 1.5rem;">
                                <i class="fa-solid fa-percent"></i>
                            </span>
                        </div>
                        <div class="col">
                            <div class="text-body-secondary"><?= gettext('Balance Ratio') ?></div>
                            <div class="fs-5 fw-bold"><?= number_format($balancePercentage, 1) ?>%</div>
                            <div class="text-muted" style="font-size: 0.85rem;">
                                <?= number_format($balancePercentage, 1) ?>% of income remains
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Financial Analysis Section -->
    <div class="row mb-4">
        <!-- Breakdown Visualization -->
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title mb-0">
                        <i class="fa-solid fa-chart-pie me-2"></i><?= gettext('Financial Distribution') ?>
                    </h3>
                </div>
                <div class="card-body" style="position: relative; height: 350px;">
                    <canvas id="financialDistributionChart"></canvas>
                </div>
            </div>
        </div>

        <!-- Detailed Breakdown Table -->
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title mb-0">
                        <i class="fa-solid fa-list-check me-2"></i><?= gettext('Financial Breakdown') ?>
                    </h3>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <tbody>
                                <tr>
                                    <td class="fw-bold">
                                        <i class="fa-solid fa-arrow-down-to-bracket text-success me-2"></i>
                                        <?= gettext('YTD Payments') ?>
                                    </td>
                                    <td class="text-end fw-bold">₦<?= number_format($ytdPaymentTotal, 2) ?></td>
                                    <td class="text-end text-muted" style="width: 100px;">
                                        <span class="badge bg-success"><?= $totalDeposits > 0 ? number_format(($ytdPaymentTotal / $totalDeposits) * 100, 1) : 0 ?>%</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">
                                        <i class="fa-solid fa-file-signature text-info me-2"></i>
                                        <?= gettext('YTD Pledges') ?>
                                    </td>
                                    <td class="text-end fw-bold">₦<?= number_format($ytdPledgeTotal, 2) ?></td>
                                    <td class="text-end text-muted">
                                        <span class="badge bg-info"><?= $totalDeposits > 0 ? number_format(($ytdPledgeTotal / $totalDeposits) * 100, 1) : 0 ?>%</span>
                                    </td>
                                </tr>
                                <tr class="table-light fw-bold" style="border-top: 2px solid #dee2e6;">
                                    <td>
                                        <i class="fa-solid fa-money-bill-wave text-success me-2"></i>
                                        <?= gettext('Total Income') ?>
                                    </td>
                                    <td class="text-end">₦<?= number_format($totalDeposits, 2) ?></td>
                                    <td class="text-end">
                                        <span class="badge bg-success">100%</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="fw-bold">
                                        <i class="fa-solid fa-arrow-up-from-bracket text-danger me-2"></i>
                                        <?= gettext('Total Expenses') ?>
                                    </td>
                                    <td class="text-end fw-bold text-danger">-₦<?= number_format($totalExpenses, 2) ?></td>
                                    <td class="text-end text-muted">
                                        <span class="badge bg-danger"><?= number_format($expensePercentage, 1) ?>%</span>
                                    </td>
                                </tr>
                                <tr class="table-light fw-bold" style="border: 2px solid #dee2e6; background-color: <?= $remainingBalance < 0 ? '#fff5f5' : '#f0fdf4' ?>;">
                                    <td>
                                        <i class="fa-solid <?= $statusIcon ?> text-<?= $statusColor ?> me-2"></i>
                                        <?= gettext('Remaining Balance') ?>
                                    </td>
                                    <td class="text-end fs-6 text-<?= $remainingBalance < 0 ? 'danger' : 'success' ?>">
                                        ₦<?= number_format($remainingBalance, 2) ?>
                                    </td>
                                    <td class="text-end">
                                        <span class="badge bg-<?= $statusColor ?>"><?= number_format($balancePercentage, 1) ?>%</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Expense Summary by Category -->
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title mb-0">
                        <i class="fa-solid fa-layer-group me-2"></i><?= gettext('Expenses by Category') ?>
                    </h3>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th><?= gettext('Category') ?></th>
                                    <th class="text-end"><?= gettext('Amount') ?></th>
                                    <th class="text-end"><?= gettext('% of Expenses') ?></th>
                                    <th class="text-end"><?= gettext('% of Deposits') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                if (!empty($expenseSummary['by_category'])) {
                                    foreach ($expenseSummary['by_category'] as $category):
                                        $categoryAmount = $category['total'];
                                        $categoryOfExpenses = $totalExpenses > 0 ? ($categoryAmount / $totalExpenses) * 100 : 0;
                                        $categoryOfDeposits = $totalDeposits > 0 ? ($categoryAmount / $totalDeposits) * 100 : 0;
                                        ?>
                                        <tr>
                                            <td class="fw-medium"><?= htmlspecialchars($category['cat_Name']) ?></td>
                                            <td class="text-end">₦<?= number_format($categoryAmount, 2) ?></td>
                                            <td class="text-end">
                                                <div class="progress" style="height: 24px;">
                                                    <div class="progress-bar bg-danger" role="progressbar" style="width: <?= $categoryOfExpenses ?>%" title="<?= $categoryOfExpenses ?>%">
                                                        <?= number_format($categoryOfExpenses, 1) ?>%
                                                    </div>
                                                </div>
                                            </td>
                                            <td class="text-end">
                                                <span class="badge bg-secondary"><?= number_format($categoryOfDeposits, 1) ?>%</span>
                                            </td>
                                        </tr>
                                    <?php endforeach;
                                } else {
                                    echo '<tr><td colspan="4" class="text-center text-muted">' . gettext('No expenses recorded') . '</td></tr>';
                                }
                                ?>
                            </tbody>
                            <tfoot class="table-light fw-bold">
                                <tr>
                                    <td><?= gettext('TOTAL') ?></td>
                                    <td class="text-end">₦<?= number_format($totalExpenses, 2) ?></td>
                                    <td class="text-end">100%</td>
                                    <td class="text-end"><?= number_format($expensePercentage, 1) ?>%</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Chart.js Library -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js" nonce="<?= SystemURLs::getCSPNonce() ?>"></script>

<script nonce="<?= SystemURLs::getCSPNonce() ?>">
$(document).ready(function() {
    renderFinancialDistributionChart();
    
    function renderFinancialDistributionChart() {
        const ctx = document.getElementById('financialDistributionChart');
        if (!ctx) return;
        
        const deposits = <?= $totalDeposits ?>;
        const expenses = <?= $totalExpenses ?>;
        const remaining = <?= $remainingBalance ?>;
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: [
                    '<?= gettext("Expenses") ?>',
                    '<?= gettext("Remaining Balance") ?>'
                ],
                datasets: [{
                    data: [expenses, remaining],
                    backgroundColor: [
                        'rgba(220, 53, 69, 0.8)',
                        'rgba(40, 167, 69, 0.8)'
                    ],
                    borderColor: [
                        'rgba(220, 53, 69, 1)',
                        'rgba(40, 167, 69, 1)'
                    ],
                    borderWidth: 2,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 15,
                            font: { size: 12 }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = '₦' + context.parsed.toLocaleString('en-NG', { minimumFractionDigits: 2 });
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = total > 0 ? ((context.parsed / total) * 100).toFixed(1) : '0';
                                return label + ': ' + value + ' (' + percentage + '%)';
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>

<?php
require_once __DIR__ . '/Include/Footer.php';
