<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/zoho.php';
auth_require_admin();

$account_id = trim((string)($_GET['account_id'] ?? ''));
if ($account_id === '') {
    header('Location: accounting.php');
    exit;
}

$account = zoho_get_bank_account($account_id);
if (!$account) {
    $page_title = 'Bank account not found';
    require __DIR__ . '/_guard.php';
    ?>
    <section class="section"><div class="container">
        <h1>Account not found</h1>
        <p class="muted">We couldn't fetch this bank account from Zoho. It may have been deleted, or the connection may be down.</p>
        <p><a href="accounting.php" class="btn btn-outline">← Back to accounting</a></p>
    </div></section>
    <?php
    require __DIR__ . '/_footer.php';
    exit;
}

$page_title = $account['account_name'] ?? 'Bank account';
require __DIR__ . '/_guard.php';

// ── Read filter inputs ──────────────────────────────────────
$page       = max(1, (int)($_GET['page'] ?? 1));
$per        = 50;
$search     = trim((string)($_GET['q']        ?? ''));
$date_start = trim((string)($_GET['date_start'] ?? ''));
$date_end   = trim((string)($_GET['date_end']   ?? ''));

if ($date_start && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_start)) $date_start = '';
if ($date_end   && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_end))   $date_end   = '';

$tx_data = zoho_list_bank_transactions($account_id, $page, $per, [
    'search'     => $search,
    'date_start' => $date_start,
    'date_end'   => $date_end,
]);
$transactions = $tx_data['transactions'];
$has_next     = $tx_data['has_more_page'] ?? false;

$has_active_filter = ($search !== '' || $date_start !== '' || $date_end !== '');

function tx_qs_with(array $overrides): string {
    $base = $_GET;
    foreach ($overrides as $k => $v) {
        if ($v === null || $v === '') unset($base[$k]); else $base[$k] = $v;
    }
    return http_build_query($base);
}

function tx_money(float $v, string $sym = 'R'): string {
    return $sym . '&nbsp;' . number_format(abs($v), 2, '.', ',');
}
function tx_status_pill(string $st): string {
    $st = strtolower($st);
    $colors = [
        'matched'         => 'background:#dcfce7;color:#166534;',
        'manuallyadded'   => 'background:#dbeafe;color:#1e40af;',
        'categorized'     => 'background:#dcfce7;color:#166534;',
        'uncategorized'   => 'background:#fef3c7;color:#92400e;',
        'imported'        => 'background:#e5e7eb;color:#374151;',
        'excluded'        => 'background:#e5e7eb;color:#374151;',
    ];
    $style = $colors[$st] ?? 'background:#e5e7eb;color:#374151;';
    $label = ucwords(str_replace(['_','manuallyadded'], [' ','Manually added'], $st));
    return '<span style="' . $style . 'display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;">' . htmlspecialchars($label) . '</span>';
}

// Account meta for header
$balance       = (float)($account['balance'] ?? 0);
$currency_sym  = $account['currency_symbol'] ?? 'R';
$account_type  = $account['account_type'] ?? 'bank';
?>

<style>
.acct-header{
    background:#fff;
    border:1px solid var(--line);
    border-radius:8px;
    padding:1.25rem 1.5rem;
    margin-bottom:1.25rem;
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:1rem;
}
.acct-header .info h1{margin:0 0 .15rem;font-size:1.25rem;}
.acct-header .info .sub{font-size:.82rem;color:var(--ink-muted);}
.acct-header .balance-block{text-align:right;}
.acct-header .balance-block .lbl{font-size:.7rem;color:var(--ink-muted);text-transform:uppercase;letter-spacing:.05em;}
.acct-header .balance-block .val{font-size:1.6rem;font-weight:700;font-variant-numeric:tabular-nums;}
.acct-header .balance-block .val.neg{color:#991b1b;}

.tx-tbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.tx-tbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.tx-tbl th.r{text-align:right;}
.tx-tbl td{padding:.65rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
.tx-tbl td.r{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums;}
.tx-tbl tr:hover td{background:#fafaf8;}
.tx-tbl .deposit{color:#166534;font-weight:600;}
.tx-tbl .withdrawal{color:#991b1b;font-weight:600;}

.filter-bar{
    background:#fff;
    border:1px solid var(--line);
    border-radius:8px;
    padding:.85rem 1rem;
    margin-bottom:1rem;
    display:flex;
    gap:.75rem;
    align-items:flex-end;
    flex-wrap:wrap;
}
.filter-bar .field{display:flex;flex-direction:column;gap:.25rem;}
.filter-bar .field.grow{flex:1;min-width:200px;}
.filter-bar label{font-size:.7rem;color:var(--ink-muted);text-transform:uppercase;letter-spacing:.05em;}
.filter-bar input[type=text],
.filter-bar input[type=date]{padding:.4rem .55rem;border:1px solid var(--line);border-radius:6px;font-size:.85rem;background:#fff;font-family:inherit;}
.filter-bar input[type=text]{width:100%;}
.filter-bar .actions{display:flex;gap:.4rem;}
.filter-bar .clear-link{font-size:.78rem;color:var(--ink-muted);text-decoration:none;align-self:center;}
.filter-bar .clear-link:hover{color:var(--ink);}
</style>

<section class="section">
<div class="container">

<p style="margin:0 0 .75rem;font-size:.85rem;">
    <a href="accounting.php" style="color:var(--ink-muted);text-decoration:none;">← Back to accounting</a>
</p>

<!-- Account header -->
<div class="acct-header">
    <div class="info">
        <h1><?= htmlspecialchars($account['account_name'] ?? '') ?></h1>
        <div class="sub">
            <?= htmlspecialchars(ucfirst(str_replace('_',' ',(string)$account_type))) ?>
            <?php if (!empty($account['bank_name'])): ?>
                · <?= htmlspecialchars($account['bank_name']) ?>
            <?php endif; ?>
            <?php if (!empty($account['account_number'])): ?>
                · Acc <?= htmlspecialchars($account['account_number']) ?>
            <?php endif; ?>
            <?php if (!empty($account['currency_code'])): ?>
                · <?= htmlspecialchars($account['currency_code']) ?>
            <?php endif; ?>
        </div>
    </div>
    <div class="balance-block">
        <div class="lbl">Current balance</div>
        <div class="val <?= $balance < 0 ? 'neg' : '' ?>">
            <?= tx_money($balance, htmlspecialchars($currency_sym)) ?>
        </div>
    </div>
</div>

<!-- Filter bar -->
<form method="get" class="filter-bar">
    <input type="hidden" name="account_id" value="<?= htmlspecialchars($account_id) ?>">

    <div class="field grow">
        <label for="q">Search</label>
        <input type="text" id="q" name="q" value="<?= htmlspecialchars($search) ?>"
               placeholder="Description, payee, reference…" autocomplete="off">
    </div>
    <div class="field">
        <label for="date_start">From</label>
        <input type="date" id="date_start" name="date_start" value="<?= htmlspecialchars($date_start) ?>">
    </div>
    <div class="field">
        <label for="date_end">To</label>
        <input type="date" id="date_end" name="date_end" value="<?= htmlspecialchars($date_end) ?>">
    </div>
    <div class="actions">
        <button type="submit" class="btn">Apply</button>
        <?php if ($has_active_filter): ?>
            <a href="?account_id=<?= htmlspecialchars($account_id) ?>" class="clear-link">✕ Clear</a>
        <?php endif; ?>
    </div>
</form>

<?php if (empty($transactions)): ?>
    <div class="card" style="text-align:center;padding:2.5rem 1rem;">
        <p class="muted" style="margin:0 0 .5rem;font-size:1rem;">No transactions found.</p>
        <?php if ($has_active_filter): ?>
            <p class="muted" style="margin:0;font-size:.85rem;">
                Try widening your search or
                <a href="?account_id=<?= htmlspecialchars($account_id) ?>">clear the filters</a>.
            </p>
        <?php endif; ?>
    </div>
<?php else: ?>

<div class="card" style="padding:0;overflow:auto;">
    <table class="tx-tbl">
        <thead>
            <tr>
                <th>Date</th>
                <th>Description</th>
                <th>Reference</th>
                <th>Status</th>
                <th class="r">Amount</th>
                <th class="r">Running balance</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($transactions as $t):
            $type       = strtolower((string)($t['transaction_type'] ?? ''));
            $amount_abs = abs((float)($t['amount'] ?? 0));

            // Determine direction (money in vs money out from the bank account's view).
            // Primary signal: transaction_type (most explicit).
            // Fallback:       debit_or_credit (debit = money IN to the asset, credit = OUT).
            $out_types = [
                'expense', 'card_payment', 'vendor_payment', 'owner_drawings',
                'payment_refund', 'vendor_payment_refund', 'card_charge',
            ];
            $in_types = [
                'deposit', 'customer_payment', 'sales_without_invoices',
                'expense_refund', 'owner_contribution', 'interest_income',
                'other_income', 'tax_refund',
            ];

            if (in_array($type, $out_types, true)) {
                $is_deposit = false;
            } elseif (in_array($type, $in_types, true)) {
                $is_deposit = true;
            } elseif (isset($t['debit_or_credit'])) {
                // From the bank account's perspective: debit = money IN, credit = OUT.
                $is_deposit = (strtolower((string)$t['debit_or_credit']) === 'debit');
            } else {
                // No reliable signal — assume positive (better than red minus on unknowns)
                $is_deposit = true;
            }

            $amount  = $is_deposit ? $amount_abs : -$amount_abs;
            $running = isset($t['running_balance']) ? (float)$t['running_balance'] : null;
        ?>
            <tr>
                <td style="white-space:nowrap;font-size:.82rem;">
                    <?= htmlspecialchars($t['date'] ?? '') ?>
                </td>
                <td>
                    <?= htmlspecialchars($t['description'] ?? $t['payee'] ?? '—') ?>
                    <?php if (!empty($t['payee']) && !empty($t['description'])): ?>
                        <br><span class="muted" style="font-size:.78rem;"><?= htmlspecialchars($t['payee']) ?></span>
                    <?php endif; ?>
                </td>
                <td style="font-size:.82rem;color:var(--ink-muted);">
                    <?= htmlspecialchars($t['reference_number'] ?? '') ?>
                </td>
                <td>
                    <?= !empty($t['status']) ? tx_status_pill((string)$t['status']) : '' ?>
                </td>
                <td class="r <?= $is_deposit ? 'deposit' : 'withdrawal' ?>">
                    <?= $is_deposit ? '+' : '−' ?>
                    <?= tx_money($amount, htmlspecialchars($currency_sym)) ?>
                </td>
                <td class="r">
                    <?= $running !== null ? tx_money($running, htmlspecialchars($currency_sym)) : '<span class="muted">—</span>' ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Pagination -->
<div style="margin-top:1rem;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.5rem;">
    <span class="muted" style="font-size:.85rem;"><?= count($transactions) ?> result<?= count($transactions)===1?'':'s' ?> · Page <?= $page ?></span>
    <div style="display:flex;gap:.5rem;">
        <?php if ($page > 1): ?>
            <a href="?<?= htmlspecialchars(tx_qs_with(['page'=>$page-1])) ?>" class="btn btn-outline">← Previous</a>
        <?php endif; ?>
        <?php if ($has_next): ?>
            <a href="?<?= htmlspecialchars(tx_qs_with(['page'=>$page+1])) ?>" class="btn btn-outline">Next →</a>
        <?php endif; ?>
    </div>
</div>

<?php endif; ?>

</div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>