<?php

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

use ChurchCRM\Authentication\AuthenticationManager;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Service\ExpenseService;
use ChurchCRM\view\PageHeader;
use ChurchCRM\Utils\InputUtils;
use ChurchCRM\Utils\RedirectUtils;

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

$expenseService = new ExpenseService();
$categories = $expenseService->getCategories();

$sPageTitle = gettext('Expense Entry');
$sPageSubtitle = gettext('Record and manage church expenses');

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

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

<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h3 class="card-title mb-0">
                    <i class="fa-solid fa-money-bill-wave"></i> <?= gettext('New Expense') ?>
                </h3>
            </div>
            <div class="card-body">
                <form id="expenseForm" method="post" name="ExpenseEditor">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expenseDate" class="form-label"><?= gettext('Date') ?> *</label>
                            <input type="date" class="form-control" id="expenseDate" name="date" required value="<?= date('Y-m-d') ?>">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expenseAmount" class="form-label"><?= gettext('Amount') ?> *</label>
                            <div class="input-group">
                                <span class="input-group-text">₦</span>
                                <input type="number" step="0.01" class="form-control" id="expenseAmount" name="amount" required placeholder="0.00">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expenseCategory" class="form-label"><?= gettext('Category') ?> *</label>
                            <select class="form-select" id="expenseCategory" name="category" required>
                                <option value="">-- <?= gettext('Select Category') ?> --</option>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?= $category['cat_ID'] ?>"><?= htmlspecialchars($category['cat_Name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expensePaymentMethod" class="form-label"><?= gettext('Payment Method') ?></label>
                            <select class="form-select" id="expensePaymentMethod" name="payment_method">
                                <option value="Check"><?= gettext('Check') ?></option>
                                <option value="Cash"><?= gettext('Cash') ?></option>
                                <option value="Credit Card"><?= gettext('Credit Card') ?></option>
                                <option value="Bank Transfer"><?= gettext('Bank Transfer') ?></option>
                                <option value="Other"><?= gettext('Other') ?></option>
                            </select>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expenseVendor" class="form-label"><?= gettext('Vendor/Payee') ?></label>
                            <input type="text" class="form-control" id="expenseVendor" name="vendor" placeholder="e.g., Electric Company">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expenseReference" class="form-label"><?= gettext('Reference') ?></label>
                            <input type="text" class="form-control" id="expenseReference" name="reference" placeholder="e.g., Invoice #, Check #">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="expenseDescription" class="form-label"><?= gettext('Description') ?></label>
                        <textarea class="form-control" id="expenseDescription" name="description" rows="3" placeholder="<?= gettext('Details about this expense') ?>"></textarea>
                    </div>

                    <div class="mb-3">
                        <label for="expenseNotes" class="form-label"><?= gettext('Notes') ?></label>
                        <textarea class="form-control" id="expenseNotes" name="notes" rows="2" placeholder="<?= gettext('Additional notes or approval comments') ?>"></textarea>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <button type="submit" class="btn btn-primary" name="SaveExpense">
                                <i class="fa-solid fa-floppy-disk"></i> <?= gettext('Save Expense') ?>
                            </button>
                            <button type="reset" class="btn btn-outline-secondary">
                                <i class="fa-solid fa-redo"></i> <?= gettext('Clear') ?>
                            </button>
                            <a href="/finance/" class="btn btn-outline-secondary">
                                <i class="fa-solid fa-times"></i> <?= gettext('Cancel') ?>
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card">
            <div class="card-header bg-info text-white">
                <h5 class="card-title mb-0"><?= gettext('Quick Guide') ?></h5>
            </div>
            <div class="card-body small">
                <h6><?= gettext('Expense Categories') ?></h6>
                <ul class="list-unstyled">
                    <li><i class="fa-solid fa-check text-success"></i> Utilities</li>
                    <li><i class="fa-solid fa-check text-success"></i> Salaries</li>
                    <li><i class="fa-solid fa-check text-success"></i> Supplies</li>
                    <li><i class="fa-solid fa-check text-success"></i> Maintenance</li>
                    <li><i class="fa-solid fa-check text-success"></i> Programs</li>
                    <li><i class="fa-solid fa-check text-success"></i> And more...</li>
                </ul>

                <hr>

                <h6><?= gettext('Status Flow') ?></h6>
                <p class="mb-1">
                    <span class="badge bg-warning text-dark">Pending</span>
                    <i class="fa-solid fa-arrow-right small"></i>
                    <span class="badge bg-info">Approved</span>
                </p>
                <p>
                    <i class="fa-solid fa-arrow-right small"></i>
                    <span class="badge bg-success">Paid</span>
                </p>

                <hr>

                <h6><?= gettext('Tips') ?></h6>
                <ul class="list-unstyled small">
                    <li>✓ <?= gettext('All expenses start as "Pending"') ?></li>
                    <li>✓ <?= gettext('Admins can approve/reject') ?></li>
                    <li>✓ <?= gettext('Track all spending') ?></li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= SystemURLs::getCSPNonce() ?>">
$(document).ready(function() {
    $('#expenseForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = {
            date: $('#expenseDate').val(),
            amount: parseFloat($('#expenseAmount').val()),
            category: parseInt($('#expenseCategory').val()),
            vendor: $('#expenseVendor').val() || null,
            payment_method: $('#expensePaymentMethod').val(),
            description: $('#expenseDescription').val(),
            reference: $('#expenseReference').val(),
            notes: $('#expenseNotes').val()
        };

        $.ajax({
            type: 'POST',
            url: window.CRM.root + '/api/expenses',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function(data) {
                swal({
                    title: 'Success!',
                    text: 'Expense recorded successfully',
                    icon: 'success'
                }).then(() => {
                    window.location.href = '/finance/';
                });
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.error || 'Failed to save expense';
                swal({
                    title: 'Error',
                    text: errorMsg,
                    icon: 'error'
                });
            }
        });
    });
});
</script>

<!-- SweetAlert 2 Library -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

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