<?php

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

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\Service\ExpenseService;
use ChurchCRM\view\PageHeader;

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

$expenseService = new ExpenseService();

// Get date range from request
$startDate = $_GET['start_date'] ?? date('Y-01-01');
$endDate = $_GET['end_date'] ?? date('Y-m-d');

$sPageTitle = gettext('Financial Summary');
$sPageSubtitle = gettext('Income vs Expenses and Account Balance');

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

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

// Calculate totals
$expensesSummary = $expenseService->getDashboardSummary($startDate, $endDate);
$byCategory = $expensesSummary['by_category'] ?? [];

?>

<div class="row mb-4">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <label><?= gettext('Start Date') ?></label>
                        <input type="date" class="form-control" id="startDate" value="<?= htmlspecialchars($startDate) ?>">
                    </div>
                    <div class="col-md-4">
                        <label><?= gettext('End Date') ?></label>
                        <input type="date" class="form-control" id="endDate" value="<?= htmlspecialchars($endDate) ?>">
                    </div>
                    <div class="col-md-4">
                        <label>&nbsp;</label>
                        <button class="btn btn-primary w-100" id="filterBtn">
                            <i class="fa-solid fa-filter"></i> <?= gettext('Filter') ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Summary Cards -->
<div class="row mb-4">
    <div class="col-md-4">
        <div class="card border-success">
            <div class="card-body">
                <h6 class="text-muted mb-2"><?= gettext('Total Income') ?></h6>
                <h2 class="text-success">$0.00</h2>
                <small class="text-muted"><?= gettext('From deposits and offerings') ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-danger">
            <div class="card-body">
                <h6 class="text-muted mb-2"><?= gettext('Total Expenses') ?></h6>
                <h2 class="text-danger">₦<?= number_format($expensesSummary['total_expenses'], 2) ?></h2>
                <small class="text-muted"><?= $expensesSummary['expense_count'] ?> <?= gettext('transactions') ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-info">
            <div class="card-body">
                <h6 class="text-muted mb-2"><?= gettext('Net Balance') ?></h6>
                <h2 class="text-info">$0.00</h2>
                <small class="text-muted"><?= gettext('Income - Expenses') ?></small>
            </div>
        </div>
    </div>
</div>

<!-- Expenses by Category -->
<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><?= gettext('Expenses by Category') ?></h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead class="table-light">
                            <tr>
                                <th><?= gettext('Category') ?></th>
                                <th class="text-end"><?= gettext('Amount') ?></th>
                                <th class="text-end"><?= gettext('% of Total') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $totalExpenses = $expensesSummary['total_expenses'];
                            foreach ($byCategory as $category): 
                                $percentage = $totalExpenses > 0 ? ($category['total'] / $totalExpenses) * 100 : 0;
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($category['cat_Name']) ?></td>
                                <td class="text-end"><strong>₦<?= number_format($category['total'], 2) ?></strong></td>
                                <td class="text-end">
                                    <div class="progress" style="height: 20px;">
                                        <div class="progress-bar" role="progressbar" style="width: <?= $percentage ?>%">
                                            <?= round($percentage, 1) ?>%
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="table-light fw-bold">
                                <td><?= gettext('TOTAL') ?></td>
                                <td class="text-end">₦<?= number_format($totalExpenses, 2) ?></td>
                                <td class="text-end">100%</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0"><?= gettext('Expense Distribution Chart') ?></h5>
            </div>
            <div class="card-body" style="position: relative; height: 300px;">
                <canvas id="expenseChart"></canvas>
            </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="<?= \ChurchCRM\dto\SystemURLs::getCSPNonce() ?>"></script>

<script nonce="<?= \ChurchCRM\dto\SystemURLs::getCSPNonce() ?>">
$(document).ready(function() {
    $('#filterBtn').click(function() {
        const start = $('#startDate').val();
        const end = $('#endDate').val();
        window.location.href = `?start_date=${start}&end_date=${end}`;
    });
    
    // Render expense chart
    const categoryData = <?= json_encode($byCategory) ?>;
    if (categoryData && categoryData.length > 0) {
        renderExpenseChart(categoryData);
    }
    
    function renderExpenseChart(categories) {
        const ctx = document.getElementById('expenseChart');
        if (!ctx) return;
        
        const labels = categories.map(cat => cat.cat_Name);
        const data = categories.map(cat => parseFloat(cat.total));
        const colors = [
            'rgba(255, 99, 132, 0.7)',
            'rgba(54, 162, 235, 0.7)',
            'rgba(255, 206, 86, 0.7)',
            'rgba(75, 192, 192, 0.7)',
            'rgba(153, 102, 255, 0.7)',
            'rgba(255, 159, 64, 0.7)',
            'rgba(199, 199, 199, 0.7)',
            'rgba(83, 102, 255, 0.7)',
            'rgba(255, 99, 255, 0.7)',
            'rgba(99, 255, 132, 0.7)'
        ];
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors.slice(0, labels.length),
                    borderColor: colors.map(c => c.replace('0.7', '1')).slice(0, labels.length),
                    borderWidth: 2,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 15,
                            font: { size: 11 }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = '₦' + context.parsed.toFixed(2);
                                const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                const percentage = ((context.parsed / total) * 100).toFixed(1);
                                return label + ': ' + value + ' (' + percentage + '%)';
                            }
                        }
                    }
                }
            }
        });
    }
});
</script>

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