<?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();
$expenses = $expenseService->getExpenses();
$summary = $expenseService->getDashboardSummary();

$sPageTitle = gettext('Expenses');
$sPageSubtitle = gettext('View and manage all church expenses');

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

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

<div class="row mb-4">
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <span class="text-muted small"><?= gettext('Total Expenses') ?></span>
                        <h3 class="mb-0">₦<?= number_format($summary['total_expenses'], 2) ?></h3>
                    </div>
                    <i class="fa-solid fa-arrow-trend-down text-danger fa-2x opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <span class="text-muted small"><?= gettext('Expense Count') ?></span>
                        <h3 class="mb-0"><?= $summary['expense_count'] ?></h3>
                    </div>
                    <i class="fa-solid fa-receipt fa-2x opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <span class="text-muted small"><?= gettext('Pending Approval') ?></span>
                        <h3 class="mb-0"><?= $summary['pending_approval'] ?></h3>
                    </div>
                    <i class="fa-solid fa-hourglass-end text-warning fa-2x opacity-25"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <a href="ExpenseEditor.php" class="btn btn-primary btn-lg w-100 h-100">
            <i class="fa-solid fa-plus"></i> <?= gettext('Add Expense') ?>
        </a>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0"><?= gettext('All Expenses') ?></h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover" id="expensesTable">
                <thead class="table-light">
                    <tr>
                        <th><?= gettext('Date') ?></th>
                        <th><?= gettext('Category') ?></th>
                        <th><?= gettext('Vendor') ?></th>
                        <th><?= gettext('Amount') ?></th>
                        <th><?= gettext('Status') ?></th>
                        <th><?= gettext('Method') ?></th>
                        <th><?= gettext('Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($expenses as $expense): ?>
                    <tr>
                        <td><?= htmlspecialchars($expense['exp_Date']) ?></td>
                        <td><?= htmlspecialchars($expense['cat_Name'] ?? 'N/A') ?></td>
                        <td><?= htmlspecialchars($expense['exp_Vendor'] ?? '-') ?></td>
                        <td><strong>₦<?= number_format($expense['exp_Amount'], 2) ?></strong></td>
                        <td>
                            <?php
                            $statusBadges = [
                                'Pending' => 'badge bg-warning text-dark',
                                'Approved' => 'badge bg-info',
                                'Rejected' => 'badge bg-danger',
                                'Paid' => 'badge bg-success'
                            ];
                            $badgeClass = $statusBadges[$expense['exp_Status']] ?? 'badge bg-secondary';
                            ?>
                            <span class="<?= $badgeClass ?>"><?= htmlspecialchars($expense['exp_Status']) ?></span>
                        </td>
                        <td><small><?= htmlspecialchars($expense['exp_PaymentMethod']) ?></small></td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <button class="btn btn-outline-primary edit-expense" data-id="<?= $expense['exp_ID'] ?>" title="Edit">
                                    <i class="fa-solid fa-pen-to-square"></i>
                                </button>
                                <?php if ($expense['exp_Status'] === 'Pending' && AuthenticationManager::getCurrentUser()->isAdmin()): ?>
                                <button class="btn btn-outline-success approve-expense" data-id="<?= $expense['exp_ID'] ?>" title="Approve">
                                    <i class="fa-solid fa-check"></i>
                                </button>
                                <button class="btn btn-outline-danger reject-expense" data-id="<?= $expense['exp_ID'] ?>" title="Reject">
                                    <i class="fa-solid fa-times"></i>
                                </button>
                                <?php endif; ?>
                                <?php if ($expense['exp_Status'] === 'Approved' && AuthenticationManager::getCurrentUser()->isAdmin()): ?>
                                <button class="btn btn-outline-success mark-paid" data-id="<?= $expense['exp_ID'] ?>" title="Mark Paid">
                                    <i class="fa-solid fa-money-check"></i>
                                </button>
                                <?php endif; ?>
                                <button class="btn btn-outline-danger delete-expense" data-id="<?= $expense['exp_ID'] ?>" title="Delete">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script nonce="<?= \ChurchCRM\dto\SystemURLs::getCSPNonce() ?>">
$(document).ready(function() {
    // Approve expense
    $(document).on('click', '.approve-expense', function() {
        const expenseId = $(this).data('id');
        
        swal({
            title: 'Approve Expense?',
            text: 'This expense will be marked as approved',
            icon: 'info',
            buttons: ['Cancel', 'Approve']
        }).then(approved => {
            if (approved) {
                $.post(`${window.CRM.root}/api/expenses/${expenseId}/approve`, function() {
                    swal('Success', 'Expense approved', 'success').then(() => location.reload());
                }).fail(function() {
                    swal('Error', 'Failed to approve expense', 'error');
                });
            }
        });
    });

    // Reject expense
    $(document).on('click', '.reject-expense', function() {
        const expenseId = $(this).data('id');
        
        swal({
            title: 'Reject Expense?',
            text: 'This expense will be rejected',
            icon: 'warning',
            buttons: ['Cancel', 'Reject']
        }).then(rejected => {
            if (rejected) {
                $.post(`${window.CRM.root}/api/expenses/${expenseId}/reject`, function() {
                    swal('Success', 'Expense rejected', 'success').then(() => location.reload());
                }).fail(function() {
                    swal('Error', 'Failed to reject expense', 'error');
                });
            }
        });
    });

    // Mark as paid
    $(document).on('click', '.mark-paid', function() {
        const expenseId = $(this).data('id');
        
        swal({
            title: 'Mark as Paid?',
            text: 'This expense will be marked as paid',
            icon: 'success',
            buttons: ['Cancel', 'Mark Paid']
        }).then(paid => {
            if (paid) {
                $.post(`${window.CRM.root}/api/expenses/${expenseId}/pay`, function() {
                    swal('Success', 'Expense marked as paid', 'success').then(() => location.reload());
                }).fail(function() {
                    swal('Error', 'Failed to mark expense as paid', 'error');
                });
            }
        });
    });

    // Delete expense
    $(document).on('click', '.delete-expense', function() {
        const expenseId = $(this).data('id');
        
        swal({
            title: 'Delete Expense?',
            text: 'This action cannot be undone',
            icon: 'warning',
            buttons: ['Cancel', 'Delete']
        }).then(deleted => {
            if (deleted) {
                $.ajax({
                    type: 'DELETE',
                    url: `${window.CRM.root}/api/expenses/${expenseId}`,
                    success: function() {
                        swal('Deleted', 'Expense deleted successfully', 'success').then(() => location.reload());
                    },
                    error: function() {
                        swal('Error', 'Failed to delete expense', 'error');
                    }
                });
            }
        });
    });

    // Initialize DataTable if available
    if ($.fn.dataTable) {
        $('#expensesTable').DataTable({
            order: [[0, 'desc']],
            pageLength: 25
        });
    }
});
</script>

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