<?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: accounts_list.php'); exit;
    }
    $action = $_POST['action'] ?? '';
    if ($action === 'save_account') {
        $code    = trim($_POST['account_code']);
        $name    = trim($_POST['account_name']);
        $type    = $_POST['account_type'];
        $subtype = $_POST['account_subtype'];
        $groupId = $_POST['group_id'] ?: null;
        $openBal = (float)($_POST['opening_balance'] ?? 0);
        $desc    = trim($_POST['description'] ?? '');
        $accId   = (int)($_POST['account_id'] ?? 0);

        if ($accId) {
            $pdo->prepare("UPDATE accounts SET account_name=?,account_type=?,account_subtype=?,group_id=?,opening_balance=?,description=? WHERE id=? AND is_system=0")
                ->execute([$name,$type,$subtype,$groupId,$openBal,$desc,$accId]);
            setFlash('success','Account updated.');
        } else {
            $pdo->prepare("INSERT INTO accounts (account_code,account_name,account_type,account_subtype,group_id,opening_balance,current_balance,description) VALUES (?,?,?,?,?,?,?,?)")
                ->execute([$code,$name,$type,$subtype,$groupId,$openBal,$openBal,$desc]);
            setFlash('success','Account created.');
        }
        header('Location: accounts_list.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: accounts_list.php'); exit;
    }
}

$filterType = $_GET['type'] ?? '';
$where = 'WHERE 1=1';
$params = [];
if ($filterType) { $where .= ' AND a.account_type=?'; $params[] = $filterType; }

$stmt = $pdo->prepare("SELECT a.*, ag.group_name FROM accounts a LEFT JOIN account_groups ag ON ag.id=a.group_id $where ORDER BY a.account_type, a.account_code");
$stmt->execute($params);
$accounts = $stmt->fetchAll();

$groups = $pdo->query("SELECT * FROM account_groups ORDER BY sort_order")->fetchAll();
$csrf = generateCSRFToken();
$pageTitle = 'Chart of Accounts';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div><div class="eyebrow">Accounts</div><h2 class="mb-0">Chart of 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>

<!-- Filter tabs -->
<div class="flex gap-8" style="margin-bottom:12px;flex-wrap:wrap;">
    <?php foreach ([''=>'All','asset'=>'Assets','liability'=>'Liabilities','equity'=>'Equity','income'=>'Income','expense'=>'Expenses'] as $val=>$label): ?>
    <a href="?type=<?= $val ?>" class="btn <?= $filterType===$val?'btn-primary':'' ?>"><?= $label ?></a>
    <?php endforeach; ?>
</div>

<div class="card">
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Code</th><th>Account Name</th><th>Type</th><th>Sub Type</th><th>Group</th><th class="text-right">Opening Bal</th><th class="text-right">Current Bal</th><th>Status</th><th>Actions</th></tr>
            </thead>
            <tbody>
            <?php
            $currentType = '';
            foreach ($accounts as $acc):
                if ($acc['account_type'] !== $currentType) {
                    $currentType = $acc['account_type'];
                    echo "<tr style='background:var(--color-surface-2);'><td colspan='9' style='font-weight:700;text-transform:uppercase;letter-spacing:1px;font-size:11px;padding:8px 12px;'>" . ucfirst($currentType) . "s</td></tr>";
                }
            ?>
            <tr>
                <td class="mono"><?= sanitize($acc['account_code']) ?></td>
                <td>
                    <strong><?= sanitize($acc['account_name']) ?></strong>
                    <?php if ($acc['is_system']): ?><span class="badge badge-muted" style="font-size:9px;">System</span><?php endif; ?>
                </td>
                <td><span class="badge"><?= ucfirst($acc['account_type']) ?></span></td>
                <td class="text-sm"><?= ucfirst(str_replace('_',' ',$acc['account_subtype'])) ?></td>
                <td class="text-sm"><?= sanitize($acc['group_name'] ?? '-') ?></td>
                <td class="num"><?= formatMoney($acc['opening_balance']) ?></td>
                <td class="num mono <?= $acc['current_balance'] < 0 ? 'text-danger' : ($acc['current_balance'] > 0 ? '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-icon btn-sm" title="Ledger"><?= icon('history') ?></a>
                        <?php if (!$acc['is_system']): ?>
                        <button class="btn btn-icon btn-sm" title="Edit" onclick='editAccount(<?= json_encode($acc) ?>)'><?= 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-icon btn-sm" 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_id" value="">
            <div class="form-grid">
                <div class="form-group">
                    <label>Account Code <span class="req">*</span></label>
                    <input type="text" name="account_code" id="f_code" required placeholder="e.g. 1011">
                </div>
                <div class="form-group">
                    <label>Account Name <span class="req">*</span></label>
                    <input type="text" name="account_name" id="f_name" required placeholder="e.g. HDFC Savings">
                </div>
                <div class="form-group">
                    <label>Account Type <span class="req">*</span></label>
                    <select name="account_type" id="f_type" onchange="filterGroups(this.value)" required>
                        <option value="asset">Asset</option>
                        <option value="liability">Liability</option>
                        <option value="equity">Equity</option>
                        <option value="income">Income</option>
                        <option value="expense">Expense</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Sub Type</label>
                    <select name="account_subtype" id="f_subtype">
                        <option value="bank">Bank</option>
                        <option value="cash">Cash</option>
                        <option value="receivable">Receivable</option>
                        <option value="payable">Payable</option>
                        <option value="stock">Stock</option>
                        <option value="fixed_asset">Fixed Asset</option>
                        <option value="credit_card">Credit Card</option>
                        <option value="loan">Loan</option>
                        <option value="capital">Capital</option>
                        <option value="sales">Sales</option>
                        <option value="purchase">Purchase</option>
                        <option value="expense">Expense</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Group</label>
                    <select name="group_id" id="f_group">
                        <option value="">-- Select Group --</option>
                        <?php foreach ($groups as $g): ?>
                        <option value="<?= $g['id'] ?>" data-type="<?= $g['group_type'] ?>"><?= sanitize($g['group_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Opening Balance</label>
                    <input type="number" step="0.01" name="opening_balance" id="f_openbal" value="0">
                </div>
                <div class="form-group full">
                    <label>Description</label>
                    <input type="text" name="description" id="f_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_id').value = '';
    document.getElementById('f_code').value = '';
    document.getElementById('f_code').readOnly = false;
    document.getElementById('f_name').value = '';
    document.getElementById('f_openbal').value = '0';
    document.getElementById('f_desc').value = '';
    document.getElementById('accModal').classList.add('show');
}
function editAccount(acc) {
    document.getElementById('accModalTitle').textContent = 'Edit Account';
    document.getElementById('f_id').value = acc.id;
    document.getElementById('f_code').value = acc.account_code;
    document.getElementById('f_code').readOnly = true;
    document.getElementById('f_name').value = acc.account_name;
    document.getElementById('f_type').value = acc.account_type;
    document.getElementById('f_subtype').value = acc.account_subtype;
    document.getElementById('f_group').value = acc.group_id || '';
    document.getElementById('f_openbal').value = acc.opening_balance;
    document.getElementById('f_desc').value = acc.description || '';
    document.getElementById('accModal').classList.add('show');
}
function closeModal() { document.getElementById('accModal').classList.remove('show'); }
function filterGroups(type) {
    document.querySelectorAll('#f_group option').forEach(opt => {
        if (!opt.value) return;
        opt.hidden = opt.dataset.type !== type;
    });
}
</script>
<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
