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

// ── AJAX: quick-add new account inline ────────────────────
if (($_GET['ajax'] ?? '') === 'quick_add_account') {
    header('Content-Type: application/json');
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) { echo json_encode(['success'=>false]); exit; }
    $name    = trim($_POST['account_name'] ?? '');
    $type    = $_POST['account_type'] ?? 'expense';
    $subtype = $_POST['account_subtype'] ?? 'other';
    if (!$name) { echo json_encode(['success'=>false,'error'=>'Name required']); exit; }
    $lastCode = $pdo->query("SELECT MAX(CAST(account_code AS UNSIGNED)) FROM accounts WHERE NOT is_system")->fetchColumn() ?: 5300;
    $pdo->prepare("INSERT INTO accounts (account_code,account_name,account_type,account_subtype,current_balance) VALUES (?,?,?,?,0)")
        ->execute([$lastCode+1, $name, $type, $subtype]);
    $id = $pdo->lastInsertId();
    echo json_encode(['success'=>true,'id'=>$id,'name'=>$name,'type'=>$type]); exit;
}

// ── Handle journal entry save ──────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: journal.php'); exit;
    }
    $date      = $_POST['entry_date'];
    $type      = $_POST['entry_type'];
    $narration = trim($_POST['narration']);
    $accs      = $_POST['line_account'] ?? [];
    $debits    = $_POST['line_debit'] ?? [];
    $credits   = $_POST['line_credit'] ?? [];
    $lineNarr  = $_POST['line_narration'] ?? [];

    $lines = [];
    foreach ($accs as $i => $accId) {
        if (!$accId) continue;
        $d = (float)($debits[$i] ?? 0);
        $c = (float)($credits[$i] ?? 0);
        if ($d > 0 || $c > 0) {
            $lines[] = ['account_id' => $accId, 'debit' => $d, 'credit' => $c, 'narration' => $lineNarr[$i] ?? ''];
        }
    }
    if (count($lines) < 2) {
        setFlash('danger','At least 2 lines required for a journal entry.'); header('Location: journal.php'); exit;
    }
    try {
        createJournalEntry($date, $type, $narration, $lines, null, null, currentUserId());
        setFlash('success','Journal entry created successfully.');
    } catch (Exception $e) {
        setFlash('danger','Error: '.$e->getMessage());
    }
    header('Location: journal.php'); exit;
}

// List all journals
$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');
$stmt = $pdo->prepare("SELECT je.*, u.name as by_name FROM journal_entries je LEFT JOIN users u ON u.id=je.created_by WHERE je.entry_date BETWEEN ? AND ? ORDER BY je.entry_date DESC, je.id DESC");
$stmt->execute([$from,$to]);
$journals = $stmt->fetchAll();

$allAccounts = $pdo->query("SELECT id, account_code, account_name, account_type FROM accounts WHERE is_active=1 ORDER BY account_code")->fetchAll();

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

<div class="page-header">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0">Journal Entries</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('jeModal').classList.add('show')"><?= icon('plus') ?> New Journal Entry</button>
    </div>
</div>

<!-- Filter -->
<div class="card" style="padding:12px 16px;">
    <form method="GET" class="flex gap-8" style="align-items:flex-end;">
        <div class="form-group mb-0"><label class="text-sm">From</label><input type="date" name="from" value="<?= $from ?>"></div>
        <div class="form-group mb-0"><label class="text-sm">To</label><input type="date" name="to" value="<?= $to ?>"></div>
        <button class="btn btn-primary"><?= icon('filter') ?> Filter</button>
    </form>
</div>

<div class="card">
    <?php if ($journals): ?>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Entry No</th><th>Date</th><th>Type</th><th>Narration</th><th class="text-right">Debit</th><th class="text-right">Credit</th><th>By</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($journals as $je): ?>
            <tr>
                <td class="mono"><?= sanitize($je['entry_no']) ?></td>
                <td><?= formatDate($je['entry_date']) ?></td>
                <td><span class="badge"><?= ucfirst($je['entry_type']) ?></span></td>
                <td class="text-sm"><?= sanitize(substr($je['narration']??'',0,60)) ?></td>
                <td class="num mono"><?= formatMoney($je['total_debit']) ?></td>
                <td class="num mono"><?= formatMoney($je['total_credit']) ?></td>
                <td class="text-sm"><?= sanitize($je['by_name']??'-') ?></td>
                <td><a href="journal_view.php?id=<?= $je['id'] ?>" class="btn btn-sm btn-icon"><?= icon('eye') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('files') ?> No journal entries in this period.</div>
    <?php endif; ?>
</div>

<!-- New Journal Entry Modal -->
<div id="jeModal" class="modal">
    <div class="modal-box" style="max-width:780px;max-height:90vh;overflow-y:auto;">
        <div class="modal-header">
            <span>New Journal Entry</span>
            <button class="btn btn-icon" onclick="document.getElementById('jeModal').classList.remove('show')"><?= icon('x') ?></button>
        </div>
        <form method="POST" id="jeForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <div class="form-grid">
                <div class="form-group">
                    <label>Entry Date <span class="req">*</span></label>
                    <input type="date" name="entry_date" value="<?= date('Y-m-d') ?>" required>
                </div>
                <div class="form-group">
                    <label>Entry Type</label>
                    <select name="entry_type">
                        <option value="journal">General Journal</option>
                        <option value="payment">Payment</option>
                        <option value="receipt">Receipt</option>
                        <option value="expense">Expense</option>
                        <option value="transfer">Bank Transfer</option>
                    </select>
                </div>
                <div class="form-group full">
                    <label>Narration <span class="req">*</span></label>
                    <input type="text" name="narration" required placeholder="Describe this journal entry">
                </div>
            </div>

            <div class="divider"></div>
            <div style="font-weight:600;margin-bottom:12px;">Journal Lines (Min 2 required — Total Debit must equal Total Credit)</div>

            <div class="table-wrap">
                <table id="jeTable">
                    <thead>
                        <tr><th>Account</th><th class="text-right">Debit</th><th class="text-right">Credit</th><th>Line Note</th><th></th></tr>
                    </thead>
                    <tbody id="jeLines">
                        <tr class="je-line">
                            <td><select name="line_account[]" class="acc-select" style="width:100%;">
                                <option value="">-- Select Account --</option>
                                <?php foreach ($allAccounts as $acc): ?>
                                <option value="<?= $acc['id'] ?>"><?= sanitize($acc['account_code']) ?> - <?= sanitize($acc['account_name']) ?></option>
                                <?php endforeach; ?>
                            </select></td>
                            <td><input type="number" step="0.01" name="line_debit[]" value="0" class="text-right debit-input" oninput="updateTotals()" style="width:110px;"></td>
                            <td><input type="number" step="0.01" name="line_credit[]" value="0" class="text-right credit-input" oninput="updateTotals()" style="width:110px;"></td>
                            <td><input type="text" name="line_narration[]" placeholder="Optional" style="width:150px;"></td>
                            <td></td>
                        </tr>
                        <tr class="je-line">
                            <td><select name="line_account[]" class="acc-select" style="width:100%;">
                                <option value="">-- Select Account --</option>
                                <?php foreach ($allAccounts as $acc): ?>
                                <option value="<?= $acc['id'] ?>"><?= sanitize($acc['account_code']) ?> - <?= sanitize($acc['account_name']) ?></option>
                                <?php endforeach; ?>
                            </select></td>
                            <td><input type="number" step="0.01" name="line_debit[]" value="0" class="text-right debit-input" oninput="updateTotals()" style="width:110px;"></td>
                            <td><input type="number" step="0.01" name="line_credit[]" value="0" class="text-right credit-input" oninput="updateTotals()" style="width:110px;"></td>
                            <td><input type="text" name="line_narration[]" placeholder="Optional" style="width:150px;"></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <button type="button" class="btn btn-sm" onclick="addLine()" style="margin-top:8px;"><?= icon('plus') ?> Add Line</button>
            <button type="button" class="btn btn-sm" onclick="toggleJERow('newAccRow')" style="margin-top:8px;"><?= icon('plus') ?> Add New Account</button>
            <div id="newAccRow" style="display:none;background:var(--color-surface-2);padding:12px;border-radius:var(--radius-md);margin-top:8px;">
                <div style="font-weight:600;margin-bottom:8px;"><?= icon('files') ?> Quick-Add New Account</div>
                <div class="form-grid">
                    <div class="form-group mb-0">
                        <label class="text-sm">Account Name</label>
                        <input type="text" id="newAccName" placeholder="e.g. Office Furniture">
                    </div>
                    <div class="form-group mb-0">
                        <label class="text-sm">Type</label>
                        <select id="newAccType">
                            <option value="asset">Asset</option>
                            <option value="liability">Liability</option>
                            <option value="expense" selected>Expense</option>
                            <option value="income">Income</option>
                            <option value="equity">Equity</option>
                        </select>
                    </div>
                    <div class="form-group mb-0">
                        <label class="text-sm">Sub Type</label>
                        <select id="newAccSubtype">
                            <option value="bank">Bank</option>
                            <option value="cash">Cash</option>
                            <option value="expense" selected>Expense</option>
                            <option value="income">Income</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div class="form-group mb-0" style="align-self:flex-end;">
                        <button type="button" class="btn btn-primary btn-sm" onclick="quickAddAccount()">Create Account</button>
                        <button type="button" class="btn btn-sm" onclick="toggleJERow('newAccRow')">Cancel</button>
                    </div>
                </div>
            </div>

            <div style="background:var(--color-surface-2);border-radius:var(--radius-md);padding:12px;margin:12px 0;" class="flex-between">
                <span>Total Debit: <strong class="mono" id="totalDebit">0.00</strong></span>
                <span>Total Credit: <strong class="mono" id="totalCredit">0.00</strong></span>
                <span id="balanceStatus" style="font-weight:600;">⚖️ Enter amounts</span>
            </div>

            <div class="flex-end gap-8">
                <button type="button" class="btn" onclick="document.getElementById('jeModal').classList.remove('show')">Cancel</button>
                <button type="submit" class="btn btn-primary" id="submitJE" disabled><?= icon('check') ?> Post Journal Entry</button>
            </div>
        </form>
    </div>
</div>

<script>
const accountOptions = `<?php foreach ($allAccounts as $acc) echo "<option value='{$acc['id']}'>{$acc['account_code']} - {$acc['account_name']}</option>"; ?>`;

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

async function quickAddAccount() {
    const name    = document.getElementById('newAccName').value.trim();
    const type    = document.getElementById('newAccType').value;
    const subtype = document.getElementById('newAccSubtype').value;
    if (!name) { alert('Enter account name.'); return; }
    const fd = new FormData();
    fd.append('csrf_token', CSRF);
    fd.append('account_name', name);
    fd.append('account_type', type);
    fd.append('account_subtype', subtype);
    const r = await fetch('?ajax=quick_add_account', {method:'POST',body:fd}).then(r=>r.json());
    if (!r.success) { alert(r.error || 'Failed'); return; }
    // Add to all account dropdowns on the page
    const newOpt = `<option value="${r.id}" selected>${name} (NEW)</option>`;
    document.querySelectorAll('.acc-select').forEach(sel => {
        const opt = new Option(`${name} (NEW)`, r.id);
        sel.appendChild(opt);
    });
    document.getElementById('newAccName').value = '';
    toggleJERow('newAccRow');
    alert(`Account "${name}" created and added to the dropdowns below.`);
}

function addLine() {
    const tbody = document.getElementById('jeLines');
    const row = document.createElement('tr');
    row.className = 'je-line';
    row.innerHTML = `
        <td><select name="line_account[]" style="width:100%;"><option value="">-- Select Account --</option>${accountOptions}</select></td>
        <td><input type="number" step="0.01" name="line_debit[]" value="0" class="text-right debit-input" oninput="updateTotals()" style="width:110px;"></td>
        <td><input type="number" step="0.01" name="line_credit[]" value="0" class="text-right credit-input" oninput="updateTotals()" style="width:110px;"></td>
        <td><input type="text" name="line_narration[]" placeholder="Optional" style="width:150px;"></td>
        <td><button type="button" class="btn btn-sm btn-icon" onclick="this.closest('tr').remove();updateTotals()"><?= icon('trash') ?></button></td>`;
    tbody.appendChild(row);
}

function updateTotals() {
    let dr = 0, cr = 0;
    document.querySelectorAll('.debit-input').forEach(i => dr += parseFloat(i.value)||0);
    document.querySelectorAll('.credit-input').forEach(i => cr += parseFloat(i.value)||0);
    document.getElementById('totalDebit').textContent = dr.toFixed(2);
    document.getElementById('totalCredit').textContent = cr.toFixed(2);
    const bal = Math.abs(dr - cr) < 0.01;
    document.getElementById('balanceStatus').textContent = bal ? '✅ Balanced' : `❌ Difference: ${Math.abs(dr-cr).toFixed(2)}`;
    document.getElementById('balanceStatus').style.color = bal ? 'var(--color-success)' : 'var(--color-danger)';
    document.getElementById('submitJE').disabled = !bal || dr === 0;
}
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
