<?php
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/accounting.php';
requireLogin();

// ── AJAX quick-add ─────────────────────────────────────────
if (($_GET['ajax'] ?? '') === 'quick_add') {
    header('Content-Type: application/json');
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        echo json_encode(['success'=>false,'error'=>'Invalid token']); exit;
    }
    $type = $_POST['type'] ?? '';

    if ($type === 'expense_category') {
        $name = trim($_POST['name'] ?? '');
        if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
        // Auto-generate expense account for new category
        $lastCode = $pdo->query("SELECT MAX(CAST(account_code AS UNSIGNED)) FROM accounts WHERE account_type='expense' AND NOT is_system")->fetchColumn() ?: 5199;
        $newCode = $lastCode + 1;
        $groupId = $pdo->query("SELECT id FROM account_groups WHERE group_name='Operating Expenses' LIMIT 1")->fetchColumn();
        $pdo->prepare("INSERT IGNORE INTO accounts (account_code,account_name,account_type,account_subtype,group_id) VALUES (?,?,'expense','expense',?)")
            ->execute([$newCode, $name . ' Expense', $groupId]);
        echo json_encode(['success'=>true,'name'=>$name]); exit;
    }

    if ($type === 'bank_account') {
        $name    = trim($_POST['name'] ?? '');
        $subtype = $_POST['subtype'] ?? 'bank';
        if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
        $lastCode = $pdo->query("SELECT MAX(CAST(account_code AS UNSIGNED)) FROM accounts WHERE account_subtype IN ('bank','cash','credit_card') AND NOT is_system")->fetchColumn() ?: 1009;
        $newCode  = $lastCode + 1;
        $groupId  = $subtype === 'cash'
            ? $pdo->query("SELECT id FROM account_groups WHERE group_name='Cash in Hand' LIMIT 1")->fetchColumn()
            : $pdo->query("SELECT id FROM account_groups WHERE group_name='Bank Accounts' LIMIT 1")->fetchColumn();
        $pdo->prepare("INSERT INTO accounts (account_code,account_name,account_type,account_subtype,group_id,current_balance) VALUES (?,?,'asset',?,?,0)")
            ->execute([$newCode, $name, $subtype, $groupId]);
        $id = $pdo->lastInsertId();
        echo json_encode(['success'=>true,'id'=>$id,'name'=>$name]); exit;
    }
    echo json_encode(['success'=>false,'error'=>'Unknown type']); exit;
}

// ── Handle save expense ────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') !== 'quick_add') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: expenses.php'); exit;
    }
    $date     = $_POST['expense_date'];
    $category = trim($_POST['category']);
    $desc     = trim($_POST['description']);
    $amount   = (float)$_POST['amount'];
    $paidFrom = (int)$_POST['paid_from'];
    $vendor   = trim($_POST['vendor_name'] ?? '');
    $ref      = trim($_POST['reference_no'] ?? '');

    if (!$date || !$category || !$desc || !$amount || !$paidFrom) {
        setFlash('danger','Please fill all required fields.'); header('Location: expenses.php'); exit;
    }

    try {
        $pdo->beginTransaction();

        // Find or match expense account by category name
        $expAcc = $pdo->prepare("SELECT id FROM accounts WHERE account_type='expense' AND (LOWER(account_name) LIKE LOWER(?) OR LOWER(account_name) LIKE LOWER(?)) LIMIT 1");
        $expAcc->execute(["%$category%", "%".(str_replace(' Expense','',$category))."%"]);
        $expAccountId = $expAcc->fetchColumn()
            ?: $pdo->query("SELECT id FROM accounts WHERE account_code='5105'")->fetchColumn();

        $journalId = createJournalEntry($date, 'expense',
            "$category: $desc" . ($vendor ? " (Vendor: $vendor)" : ""),
            [
                ['account_id' => $expAccountId, 'debit' => $amount,  'credit' => 0,      'narration' => $desc],
                ['account_id' => $paidFrom,      'debit' => 0,       'credit' => $amount, 'narration' => "Paid from account"],
            ], 'expense', null, currentUserId()
        );

        $pdo->prepare("INSERT INTO expenses (expense_date,category,description,amount,paid_from,vendor_name,reference_no,journal_id,created_by)
                       VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute([$date,$category,$desc,$amount,$paidFrom,$vendor,$ref,$journalId,currentUserId()]);

        $pdo->commit();
        setFlash('success','Expense recorded and journal entry created.');
    } catch (Exception $e) {
        $pdo->rollBack();
        setFlash('danger','Error: '.$e->getMessage());
    }
    header('Location: expenses.php'); exit;
}

// ── Load data ──────────────────────────────────────────────
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');
$stmt = $pdo->prepare("SELECT e.*, a.account_name as paid_from_name
                        FROM expenses e LEFT JOIN accounts a ON a.id=e.paid_from
                        WHERE e.expense_date BETWEEN ? AND ? ORDER BY e.expense_date DESC");
$stmt->execute([$from,$to]);
$expenses = $stmt->fetchAll();
$totalExpenses = array_sum(array_column($expenses,'amount'));

// Load existing expense categories from accounts table
$expAccounts = $pdo->query("SELECT account_name FROM accounts WHERE account_type='expense' AND is_active=1 ORDER BY account_name")->fetchAll(PDO::FETCH_COLUMN);
$expenseCategories = array_map(fn($n) => str_replace(' Expense','',$n), $expAccounts);
if (empty($expenseCategories)) {
    $expenseCategories = ['Rent','Electricity','Internet','Transport','Marketing','Office Supplies','Maintenance','Professional Fees','Taxes','Miscellaneous'];
}

$bankAccounts = $pdo->query("SELECT id, account_name, account_subtype, current_balance FROM accounts WHERE account_subtype IN ('bank','cash') AND is_active=1 ORDER BY account_code")->fetchAll();

$csrf = generateCSRFToken();
$pageTitle = 'Expenses';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0">Expenses</h2></div>
    <div class="flex gap-8">
        <a href="index.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <button class="btn btn-primary" onclick="document.getElementById('expModal').classList.add('show')"><?= icon('plus') ?> Add Expense</button>
    </div>
</div>

<!-- Filter + Summary -->
<div class="card" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:center;flex-wrap:wrap;">
        <div class="form-group mb-0"><label class="text-sm">From</label><input type="date" name="from" value="<?= $from ?>" style="width:145px;"></div>
        <div class="form-group mb-0"><label class="text-sm">To</label><input type="date" name="to" value="<?= $to ?>" style="width:145px;"></div>
        <button class="btn btn-primary" style="align-self:flex-end;"><?= icon('filter') ?> Filter</button>
        <div style="margin-left:auto;align-self:center;">Total: <strong class="mono text-danger"><?= formatMoney($totalExpenses) ?></strong></div>
    </form>
</div>

<div class="card">
    <?php if ($expenses): ?>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Date</th><th>Category</th><th>Description</th><th>Vendor</th><th>Paid From</th><th>Ref No</th><th class="text-right">Amount</th></tr></thead>
            <tbody>
            <?php foreach ($expenses as $e): ?>
            <tr>
                <td><?= formatDate($e['expense_date']) ?></td>
                <td><span class="badge"><?= sanitize($e['category']) ?></span></td>
                <td><?= sanitize($e['description']) ?></td>
                <td><?= sanitize($e['vendor_name'] ?? '-') ?></td>
                <td><?= sanitize($e['paid_from_name'] ?? '-') ?></td>
                <td class="mono"><?= sanitize($e['reference_no'] ?? '-') ?></td>
                <td class="num mono text-danger"><strong><?= formatMoney($e['amount']) ?></strong></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr><td colspan="6" style="font-weight:700;text-align:right;">Total</td>
                    <td class="num mono text-danger"><strong><?= formatMoney($totalExpenses) ?></strong></td></tr>
            </tfoot>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('receipt') ?> No expenses in this period.</div>
    <?php endif; ?>
</div>

<!-- Add Expense Modal -->
<div id="expModal" class="modal">
    <div class="modal-box" style="max-width:600px;">
        <div class="modal-header">
            <span>Add Expense</span>
            <button class="btn btn-icon" onclick="document.getElementById('expModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <div class="form-grid">
                <div class="form-group">
                    <label>Expense Date <span class="req">*</span></label>
                    <input type="date" name="expense_date" value="<?= date('Y-m-d') ?>" required>
                </div>

                <!-- Category with inline quick-add -->
                <div class="form-group">
                    <label>Category <span class="req">*</span></label>
                    <div class="flex gap-8">
                        <select name="category" id="categorySelect" required style="flex:1;">
                            <?php foreach ($expenseCategories as $cat): ?>
                            <option value="<?= sanitize($cat) ?>"><?= sanitize($cat) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                            onclick="toggleExpRow('newCatRow')" title="Add new category"><?= icon('plus') ?></button>
                    </div>
                    <div id="newCatRow" style="display:none;margin-top:6px;" class="flex gap-8">
                        <input type="text" id="newCatName" placeholder="e.g. Courier Expense" style="flex:1;">
                        <button type="button" class="btn btn-sm btn-primary" onclick="quickAddCategory()">Add</button>
                        <button type="button" class="btn btn-sm" onclick="toggleExpRow('newCatRow')">Cancel</button>
                    </div>
                </div>

                <div class="form-group full">
                    <label>Description <span class="req">*</span></label>
                    <input type="text" name="description" required placeholder="What was this expense for?">
                </div>
                <div class="form-group">
                    <label>Amount <span class="req">*</span></label>
                    <input type="number" step="0.01" name="amount" required placeholder="0.00">
                </div>

                <!-- Bank Account with inline quick-add -->
                <div class="form-group">
                    <label>Paid From <span class="req">*</span></label>
                    <div class="flex gap-8">
                        <select name="paid_from" id="paidFromSelect" required style="flex:1;">
                            <option value="">-- Select Account --</option>
                            <?php foreach ($bankAccounts as $acc): ?>
                            <option value="<?= $acc['id'] ?>"><?= sanitize($acc['account_name']) ?> (<?= formatMoney($acc['current_balance']) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                        <button type="button" class="btn btn-icon" style="width:36px;height:36px;flex-shrink:0;"
                            onclick="toggleExpRow('newBankRow')" title="Add bank account"><?= icon('plus') ?></button>
                    </div>
                    <div id="newBankRow" style="display:none;margin-top:6px;" class="flex gap-8">
                        <input type="text" id="newBankName" placeholder="e.g. SBI Current Account" style="flex:1;">
                        <select id="newBankType" style="width:110px;">
                            <option value="bank">Bank</option>
                            <option value="cash">Cash</option>
                        </select>
                        <button type="button" class="btn btn-sm btn-primary" onclick="quickAddBank()">Add</button>
                        <button type="button" class="btn btn-sm" onclick="toggleExpRow('newBankRow')">Cancel</button>
                    </div>
                </div>

                <div class="form-group">
                    <label>Vendor / Payee</label>
                    <input type="text" name="vendor_name" placeholder="Who was paid?">
                </div>
                <div class="form-group">
                    <label>Reference No</label>
                    <input type="text" name="reference_no" placeholder="Receipt / bill number">
                </div>
            </div>
            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="document.getElementById('expModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Expense</button>
            </div>
        </form>
    </div>
</div>

<script>
const CSRF_EXP = '<?= $csrf ?>';

function toggleExpRow(id) {
    const el = document.getElementById(id);
    el.style.display = el.style.display === 'none' ? 'flex' : 'none';
}

async function quickAddCategory() {
    const name = document.getElementById('newCatName').value.trim();
    if (!name) { alert('Enter a category name.'); return; }
    const fd = new FormData();
    fd.append('csrf_token', CSRF_EXP);
    fd.append('type', 'expense_category');
    fd.append('name', name);
    const r = await fetch('?ajax=quick_add', {method:'POST',body:fd}).then(r=>r.json());
    if (!r.success) { alert(r.error); return; }
    // Add to select
    const sel = document.getElementById('categorySelect');
    const opt = new Option(r.name, r.name, true, true);
    sel.appendChild(opt);
    sel.value = r.name;
    document.getElementById('newCatName').value = '';
    toggleExpRow('newCatRow');
}

async function quickAddBank() {
    const name    = document.getElementById('newBankName').value.trim();
    const subtype = document.getElementById('newBankType').value;
    if (!name) { alert('Enter account name.'); return; }
    const fd = new FormData();
    fd.append('csrf_token', CSRF_EXP);
    fd.append('type', 'bank_account');
    fd.append('name', name);
    fd.append('subtype', subtype);
    const r = await fetch('?ajax=quick_add', {method:'POST',body:fd}).then(r=>r.json());
    if (!r.success) { alert(r.error); return; }
    const sel = document.getElementById('paidFromSelect');
    const opt = new Option(r.name + ' (Rs.0.00)', r.id, true, true);
    sel.appendChild(opt);
    sel.value = r.id;
    document.getElementById('newBankName').value = '';
    toggleExpRow('newBankRow');
}
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
