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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        setFlash('danger','Invalid token.'); header('Location: bank_accounts.php'); exit;
    }
    $action = $_POST['action'] ?? '';

    if ($action === 'save_account') {
        $name       = trim($_POST['account_name']);
        $subtype    = $_POST['account_subtype'];
        $bankName   = trim($_POST['bank_name'] ?? '');
        $accNo      = trim($_POST['account_number'] ?? '');
        $ifsc       = trim($_POST['ifsc_code'] ?? '');
        $openBal    = (float)($_POST['opening_balance'] ?? 0);
        $desc       = trim($_POST['description'] ?? '');
        $accType    = in_array($subtype, ['credit_card','loan']) ? 'liability' : 'asset';

        // Auto-generate account code
        $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;
        $code = $lastCode + 1;

        $groupId = match($subtype) {
            'bank'        => $pdo->query("SELECT id FROM account_groups WHERE group_name='Bank Accounts' LIMIT 1")->fetchColumn(),
            'cash'        => $pdo->query("SELECT id FROM account_groups WHERE group_name='Cash in Hand' LIMIT 1")->fetchColumn(),
            'credit_card' => $pdo->query("SELECT id FROM account_groups WHERE group_name='Credit Cards' LIMIT 1")->fetchColumn(),
            default       => null
        };

        if ($_POST['account_id'] ?? '') {
            $pdo->prepare("UPDATE accounts SET account_name=?,account_subtype=?,account_type=?,bank_name=?,account_number=?,ifsc_code=?,opening_balance=?,description=? WHERE id=?")
                ->execute([$name,$subtype,$accType,$bankName,$accNo,$ifsc,$openBal,$desc,$_POST['account_id']]);
            setFlash('success','Account updated.');
        } else {
            $pdo->prepare("INSERT INTO accounts (account_code,account_name,account_type,account_subtype,group_id,opening_balance,current_balance,bank_name,account_number,ifsc_code,description)
                           VALUES (?,?,?,?,?,?,?,?,?,?,?)")
                ->execute([$code,$name,$accType,$subtype,$groupId,$openBal,$openBal,$bankName,$accNo,$ifsc,$desc]);
            setFlash('success','Account added successfully.');
        }
        header('Location: bank_accounts.php'); exit;
    }

    if ($action === 'toggle') {
        $pdo->prepare("UPDATE accounts SET is_active=1-is_active WHERE id=? AND is_system=0")->execute([(int)$_POST['account_id']]);
        header('Location: bank_accounts.php'); exit;
    }
}

$accounts = $pdo->query("SELECT * FROM accounts WHERE account_subtype IN ('bank','cash','credit_card') ORDER BY account_code")->fetchAll();
$csrf = generateCSRFToken();
$pageTitle = 'Bank Accounts';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0">Bank & Cash Accounts</h2></div>
    <div class="flex gap-8">
        <a href="index.php" class="btn"><?= icon('arrow-left') ?> Back</a>
        <button class="btn btn-primary" onclick="openModal()"><?= icon('plus') ?> Add Account</button>
    </div>
</div>

<div class="card">
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Code</th><th>Account Name</th><th>Type</th><th>Bank</th><th>Account No</th><th>IFSC</th><th class="text-right">Opening</th><th class="text-right">Current Balance</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php foreach ($accounts as $acc): ?>
            <tr>
                <td class="mono"><?= sanitize($acc['account_code']) ?></td>
                <td><strong><?= sanitize($acc['account_name']) ?></strong></td>
                <td><span class="badge"><?= ucfirst($acc['account_subtype']) ?></span></td>
                <td><?= sanitize($acc['bank_name'] ?? '-') ?></td>
                <td class="mono"><?= sanitize($acc['account_number'] ?? '-') ?></td>
                <td class="mono"><?= sanitize($acc['ifsc_code'] ?? '-') ?></td>
                <td class="num"><?= formatMoney($acc['opening_balance']) ?></td>
                <td class="num mono <?= $acc['current_balance'] < 0 ? 'text-danger' : 'text-success' ?>">
                    <strong><?= formatMoney($acc['current_balance']) ?></strong>
                </td>
                <td><span class="badge badge-<?= $acc['is_active'] ? 'success' : 'muted' ?>"><?= $acc['is_active'] ? 'Active' : 'Inactive' ?></span></td>
                <td>
                    <div class="flex gap-4">
                        <a href="reports.php?report=ledger&account_id=<?= $acc['id'] ?>" class="btn btn-sm btn-icon" title="Statement"><?= icon('history') ?></a>
                        <?php if (!$acc['is_system']): ?>
                        <button class="btn btn-sm btn-icon" onclick="editAccount(<?= htmlspecialchars(json_encode($acc)) ?>)" title="Edit"><?= icon('edit') ?></button>
                        <form method="POST" style="display:inline;">
                            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
                            <input type="hidden" name="action" value="toggle">
                            <input type="hidden" name="account_id" value="<?= $acc['id'] ?>">
                            <button class="btn btn-sm btn-icon" title="Toggle"><?= icon('power') ?></button>
                        </form>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add/Edit Modal -->
<div id="accModal" class="modal">
    <div class="modal-box" style="max-width:560px;">
        <div class="modal-header">
            <span id="accModalTitle">Add Account</span>
            <button class="btn btn-icon" onclick="closeModal()"><?= icon('x') ?></button>
        </div>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="action" value="save_account">
            <input type="hidden" name="account_id" id="f_acc_id" value="">
            <div class="form-grid">
                <div class="form-group full">
                    <label>Account Name <span class="req">*</span></label>
                    <input type="text" name="account_name" id="f_acc_name" required placeholder="e.g. HDFC Current Account">
                </div>
                <div class="form-group">
                    <label>Account Type <span class="req">*</span></label>
                    <select name="account_subtype" id="f_acc_subtype" required>
                        <option value="bank">Bank Account</option>
                        <option value="cash">Cash / Petty Cash</option>
                        <option value="credit_card">Credit Card</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Opening Balance</label>
                    <input type="number" step="0.01" name="opening_balance" id="f_acc_openbal" value="0">
                </div>
                <div class="form-group">
                    <label>Bank Name</label>
                    <input type="text" name="bank_name" id="f_acc_bank" placeholder="e.g. HDFC Bank">
                </div>
                <div class="form-group">
                    <label>Account Number</label>
                    <input type="text" name="account_number" id="f_acc_no" placeholder="Bank account number">
                </div>
                <div class="form-group">
                    <label>IFSC Code</label>
                    <input type="text" name="ifsc_code" id="f_acc_ifsc" placeholder="e.g. HDFC0001234">
                </div>
                <div class="form-group full">
                    <label>Description</label>
                    <input type="text" name="description" id="f_acc_desc" placeholder="Optional notes">
                </div>
            </div>
            <div class="flex-end gap-8 mt-16">
                <button type="button" class="btn" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-primary"><?= icon('check') ?> Save Account</button>
            </div>
        </form>
    </div>
</div>
<script>
function openModal() {
    document.getElementById('accModalTitle').textContent = 'Add Account';
    document.getElementById('f_acc_id').value = '';
    document.getElementById('f_acc_name').value = '';
    document.getElementById('f_acc_bank').value = '';
    document.getElementById('f_acc_no').value = '';
    document.getElementById('f_acc_ifsc').value = '';
    document.getElementById('f_acc_openbal').value = '0';
    document.getElementById('f_acc_desc').value = '';
    document.getElementById('accModal').classList.add('show');
}
function editAccount(acc) {
    document.getElementById('accModalTitle').textContent = 'Edit Account';
    document.getElementById('f_acc_id').value = acc.id;
    document.getElementById('f_acc_name').value = acc.account_name;
    document.getElementById('f_acc_subtype').value = acc.account_subtype;
    document.getElementById('f_acc_bank').value = acc.bank_name || '';
    document.getElementById('f_acc_no').value = acc.account_number || '';
    document.getElementById('f_acc_ifsc').value = acc.ifsc_code || '';
    document.getElementById('f_acc_openbal').value = acc.opening_balance;
    document.getElementById('f_acc_desc').value = acc.description || '';
    document.getElementById('accModal').classList.add('show');
}
function closeModal() { document.getElementById('accModal').classList.remove('show'); }
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
