<?php
include 'header.php';

$alert = "";
$user_id = $_SESSION['user_id'];

if (isset($_POST['link_card_method'])) {
    $card_holder = clean($_POST['card_holder']);
    $raw_card_num = str_replace(' ', '', $_POST['card_number']);
    $expiry = clean($_POST['expiry']);
    $cvv = clean($_POST['cvv']);

    $errors = [];

    if (!is_numeric($raw_card_num) || strlen($raw_card_num) < 13 || strlen($raw_card_num) > 19) {
        $errors[] = "Invalid Card Number. Must be 13-19 digits.";
    }

    if (!is_numeric($cvv) || strlen($cvv) < 3 || strlen($cvv) > 4) {
        $errors[] = "Invalid CVV.";
    }

    $exp_valid = false;
    if (preg_match('/^(0[1-9]|1[0-2])\/?([0-9]{2})$/', $expiry, $matches)) {
        $exp_month = intval($matches[1]);
        $exp_year_short = intval($matches[2]);
        $exp_year = intval("20" . $exp_year_short);

        $current_year = intval(date('Y'));
        $current_month = intval(date('m'));

        if ($exp_year > $current_year || ($exp_year == $current_year && $exp_month >= $current_month)) {
            $exp_valid = true;
        } else {
            $errors[] = "Card has expired.";
        }
    } else {
        $errors[] = "Invalid Expiry Format (Use MM/YY).";
    }

    if (empty($errors)) {
        $sql = "INSERT INTO linked_banks (user_id, bank_name, account_name, account_number, expiry, cvv, created_at)
                VALUES ('$user_id', 'Linked Card', '$card_holder', '$raw_card_num', '$expiry', '$cvv', NOW())";

        if (mysqli_query($link, $sql)) {
            $alert = "Swal.fire({icon: 'success', title: 'Linked', text: 'Card added successfully.'});";
        } else {
            $alert = "Swal.fire({icon: 'error', title: 'Error', text: 'Could not link card to database.'});";
        }
    } else {
        $alert = "Swal.fire({icon: 'warning', title: 'Invalid Details', text: '".$errors[0]."'});";
    }
}

include __DIR__ . '/../config/local_banks.php';
local_banks_ensure_table($link);
$local_bank_catalog = local_banks_catalog();

if (isset($_POST['connect_local_bank'])) {
    $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'])));
    $custom_bank = isset($_POST['custom_bank_name']) ? trim(strip_tags($_POST['custom_bank_name'])) : '';
    if ($bank_name === '' && $custom_bank !== '') {
        $bank_name = $custom_bank;
    }

    if (!isset($local_bank_catalog[$country_code])) {
        $alert = "Swal.fire({icon:'error', title:'Invalid country', text:'Please select a supported country.'});";
    } elseif ($bank_name === '' || $account_name === '' || $account_number === '' || $account_id === '' || $bank_email === '') {
        $alert = "Swal.fire({icon:'warning', title:'Missing details', text:'Select a bank and enter holder name, account number, account ID, and email.'});";
    } elseif (!filter_var($bank_email, FILTER_VALIDATE_EMAIL)) {
        $alert = "Swal.fire({icon:'warning', title:'Invalid email', text:'Enter a valid email address for this bank account.'});";
    } elseif (!local_bank_is_allowed($country_code, $bank_name, $local_bank_catalog)) {
        $alert = "Swal.fire({icon:'error', title:'Unknown bank', text:'Please pick a bank from the list or type a valid bank name.'});";
    } else {
        $country_name = $local_bank_catalog[$country_code]['name'];
        $currency = $local_bank_catalog[$country_code]['currency'];
        $stmt = mysqli_prepare($link, "INSERT INTO connected_local_banks (user_id, country_code, country_name, bank_name, account_name, account_number, account_id, bank_email, bank_code, iban, swift, currency, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
        mysqli_stmt_bind_param($stmt, 'isssssssssss', $user_id, $country_code, $country_name, $bank_name, $account_name, $account_number, $account_id, $bank_email, $bank_code, $iban, $swift, $currency);
        if (mysqli_stmt_execute($stmt)) {
            $alert = "Swal.fire({icon:'success', title:'Bank connected', text:'You can now use this bank to receive, send, and swap.'});";
        } else {
            $alert = "Swal.fire({icon:'error', title:'Error', text:'Could not save the bank connection.'});";
        }
        mysqli_stmt_close($stmt);
    }
}

if (isset($_POST['disconnect_local_bank'])) {
    $bid = intval($_POST['bank_id']);
    mysqli_query($link, "UPDATE connected_local_banks SET status='disconnected' WHERE id='$bid' AND user_id='$user_id'");
    $alert = "Swal.fire({icon:'success', title:'Disconnected', text:'Local bank removed from this account.'});";
}

$bank_query = mysqli_query($link, "SELECT * FROM linked_banks WHERE user_id = '$user_id'");
$connected_local_banks = local_banks_for_user($link, $user_id);
?>

<div class="flex-1 overflow-y-auto p-4 md:p-8 pb-24 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-900 dark:text-white mb-1">Connect Your Bank</h1>
            <p class="text-slate-500 dark:text-slate-400 text-sm">Link a local bank for funding, withdrawals, and swaps — or link a debit/credit card.</p>
        </div>
    </div>

    <div class="max-w-2xl space-y-6">

        <div class="glass-panel rounded-3xl p-6 border border-slate-200 dark:border-white/5">
            <div class="flex items-start justify-between gap-3 mb-4">
                <div>
                    <h3 class="font-bold text-slate-900 dark:text-white mb-1">Local Banks</h3>
                    <p class="text-xs text-slate-500 dark:text-slate-400">Connect a bank from the 10 most used countries, then fund, send, or swap with it.</p>
                </div>
                <span class="text-[10px] font-bold uppercase tracking-wider px-2 py-1 rounded-full bg-indigo-500/10 text-indigo-500 border border-indigo-500/20">New</span>
            </div>

            <?php if (!empty($connected_local_banks)): ?>
                <div class="space-y-3 mb-6">
                    <?php foreach ($connected_local_banks as $lb): ?>
                        <div class="flex items-center justify-between p-4 rounded-xl bg-slate-100 dark:bg-[#0B0F19] border border-slate-200 dark:border-white/10">
                            <div class="flex items-center gap-4 min-w-0">
                                <div class="w-10 h-10 rounded-full bg-indigo-500/10 flex items-center justify-center text-indigo-500">
                                    <i class="fa-solid fa-building-columns"></i>
                                </div>
                                <div class="min-w-0">
                                    <p class="font-bold text-sm text-slate-900 dark:text-white truncate"><?php echo htmlspecialchars($lb['bank_name'], ENT_QUOTES, 'UTF-8'); ?></p>
                                    <p class="text-xs text-slate-500 truncate"><?php echo htmlspecialchars($lb['country_name'] . ' · ' . $lb['account_name'] . ' · ID ' . (isset($lb['account_id']) ? $lb['account_id'] : '') . ' · •••• ' . substr($lb['account_number'], -4), ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                            </div>
                            <form method="POST" class="ml-3 flex-shrink-0">
                                <input type="hidden" name="bank_id" value="<?php echo intval($lb['id']); ?>">
                                <button type="submit" name="disconnect_local_bank" class="text-[11px] font-bold text-slate-400 hover:text-red-500">Remove</button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form method="POST" id="localBankForm" class="space-y-4">
                <div>
                    <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Country</label>
                    <select name="country_code" id="localBankCountry" required class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm">
                        <option value="">Select your country</option>
                        <?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-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Bank</label>
                    <input type="search" id="localBankSearch" placeholder="Search banks in this country…" class="w-full mb-2 bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-2.5 px-4 focus:outline-none focus:border-indigo-500 text-sm hidden">
                    <div id="localBankList" class="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-56 overflow-y-auto p-1">
                        <p class="text-xs text-slate-500 col-span-full py-4 text-center">Select a country to see available banks.</p>
                    </div>
                    <input type="hidden" name="bank_name" id="localBankName">
                    <div id="customBankWrap" class="hidden mt-3">
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Your bank name</label>
                        <input type="text" name="custom_bank_name" id="customBankName" placeholder="Type the bank if it is not listed" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm">
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Account holder name</label>
                        <input type="text" name="account_name" required placeholder="Name on the account" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Account number</label>
                        <input type="text" name="account_number" id="localAccountNumber" required placeholder="Account number" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm font-mono">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Account ID</label>
                        <input type="text" name="account_id" required placeholder="Customer / account ID" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm font-mono">
                    </div>
                    <div class="sm:col-span-2">
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Email</label>
                        <input type="email" name="bank_email" required placeholder="Email on the bank account" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2" id="localCodeLabel">Bank code</label>
                        <input type="text" name="bank_code" id="localBankCode" placeholder="Routing / sort / IFSC" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm font-mono">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">IBAN (optional)</label>
                        <input type="text" name="iban" placeholder="For EU / international" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm font-mono">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">SWIFT / BIC (optional)</label>
                        <input type="text" name="swift" placeholder="e.g. CHASUS33" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm font-mono">
                    </div>
                </div>

                <button type="submit" name="connect_local_bank" class="w-full py-4 rounded-xl bg-indigo-600 text-white font-bold shadow-lg hover:bg-indigo-500 transition-all flex items-center justify-center gap-2">
                    <i class="fa-solid fa-building-columns"></i> Connect Bank
                </button>
                <p class="text-center text-[10px] text-slate-400">We only store account details you enter — never online banking passwords.</p>
            </form>
        </div>

        <div class="glass-panel rounded-3xl p-6 border border-slate-200 dark:border-white/5">
            <h3 class="font-bold text-slate-900 dark:text-white mb-2">Linked Cards</h3>
            <p class="text-xs text-slate-500 dark:text-slate-400 mb-6">Manage your external cards for withdrawals.</p>

            <div class="space-y-3">
                <?php if ($bank_query && mysqli_num_rows($bank_query) > 0): ?>
                    <?php while ($row = mysqli_fetch_assoc($bank_query)): ?>
                        <div class="flex items-center justify-between p-4 rounded-xl bg-slate-100 dark:bg-[#0B0F19] border border-slate-200 dark:border-white/10 group hover:border-indigo-500 transition-all">
                            <div class="flex items-center gap-4">
                                <div class="w-10 h-10 rounded-full bg-slate-200 dark:bg-white/10 flex items-center justify-center font-bold text-slate-600 dark:text-slate-300">
                                    <i class="fa-regular fa-credit-card"></i>
                                </div>
                                <div>
                                    <p class="font-bold text-sm text-slate-900 dark:text-white"><?php echo htmlspecialchars($row['account_name'], ENT_QUOTES, 'UTF-8'); ?></p>
                                    <p class="text-xs text-slate-500">•••• <?php echo htmlspecialchars(substr($row['account_number'], -4), ENT_QUOTES, 'UTF-8'); ?></p>
                                </div>
                            </div>
                            <div class="w-2 h-2 rounded-full bg-green-500"></div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <div class="p-6 rounded-xl bg-slate-50 dark:bg-[#0B0F19] border border-dashed border-slate-200 dark:border-white/10 text-center">
                        <p class="text-sm text-slate-500 dark:text-slate-400">No cards linked yet.</p>
                    </div>
                <?php endif; ?>

                <button onclick="openLinkBankModal()" class="w-full py-4 rounded-xl border border-dashed border-slate-300 dark:border-white/20 text-slate-500 dark:text-slate-400 font-bold text-sm hover:bg-slate-50 dark:hover:bg-white/5 hover:text-indigo-500 hover:border-indigo-500 transition-all flex items-center justify-center gap-2">
                    <i class="fa-solid fa-plus"></i> Link New Card
                </button>
            </div>
        </div>
    </div>
</div>

<div id="linkBankModal" class="modal-bg fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-sm hidden p-4">
    <div class="modal-content glass-panel w-full max-w-md rounded-3xl p-6 md:p-8 border border-slate-200 dark:border-white/10 relative shadow-2xl">
        <button type="button" onclick="closeLinkBankModal()" class="absolute top-4 right-4 w-8 h-8 rounded-full bg-slate-100 dark:bg-white/5 flex items-center justify-center text-slate-500 hover:text-red-500 transition-all"><i class="fa-solid fa-xmark"></i></button>
        <div class="mb-6">
            <h2 class="text-2xl font-bold text-slate-900 dark:text-white mb-1">Add New Card</h2>
            <p class="text-sm text-slate-500 dark:text-slate-400">Securely link your debit or credit card.</p>
        </div>
        <form method="POST">
            <div class="space-y-4">
                <div>
                    <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Cardholder Name</label>
                    <input type="text" name="card_holder" placeholder="e.g. Alex Rivera" required class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm">
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Card Number</label>
                    <div class="relative">
                        <input type="text" name="card_number" id="inputCardNum" placeholder="0000 0000 0000 0000" required maxlength="19" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 pl-10 pr-4 focus:outline-none focus:border-indigo-500 text-sm font-mono" oninput="formatCardNumber(this)">
                        <i class="fa-regular fa-credit-card absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">Expiry Date</label>
                        <input type="text" name="expiry" id="inputExpiry" placeholder="MM/YY" required maxlength="5" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm text-center" oninput="formatExpiry(this)">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-2">CVV</label>
                        <input type="password" name="cvv" placeholder="123" required maxlength="4" class="w-full bg-slate-50 dark:bg-[#02040a] text-slate-900 dark:text-white border border-slate-200 dark:border-white/10 rounded-xl py-3 px-4 focus:outline-none focus:border-indigo-500 text-sm text-center">
                    </div>
                </div>
                <button type="submit" name="link_card_method" class="w-full py-4 rounded-xl bg-slate-900 dark:bg-white text-white dark:text-black font-bold shadow-lg hover:opacity-90 transition-all flex items-center justify-center gap-2">
                    <i class="fa-solid fa-link"></i> Link Card
                </button>
                <p class="text-center text-[10px] text-slate-400 mt-3 flex items-center justify-center gap-1"><i class="fa-solid fa-lock"></i> Encrypted & Secure</p>
            </div>
        </form>
    </div>
</div>

<script>
    function formatCardNumber(input) {
        let value = input.value.replace(/\D/g, '');
        value = value.substring(0, 16);
        let formatted = value.match(/.{1,4}/g)?.join(' ') || value;
        input.value = formatted;
    }

    function formatExpiry(input) {
        let value = input.value.replace(/\D/g, '');
        if (value.length >= 2) {
            value = value.substring(0, 2) + '/' + value.substring(2, 4);
        }
        input.value = value;
    }

    function openLinkBankModal() {
        document.getElementById('linkBankModal').classList.remove('hidden');
    }
    function closeLinkBankModal() {
        document.getElementById('linkBankModal').classList.add('hidden');
    }

    const BANK_CATALOG = <?php echo json_encode($local_bank_catalog); ?>;
    const countrySelect = document.getElementById('localBankCountry');
    const bankList = document.getElementById('localBankList');
    const bankNameInput = document.getElementById('localBankName');
    const codeLabel = document.getElementById('localCodeLabel');
    const codeInput = document.getElementById('localBankCode');
    const accountInput = document.getElementById('localAccountNumber');
    const searchInput = document.getElementById('localBankSearch');
    const customWrap = document.getElementById('customBankWrap');
    const customInput = document.getElementById('customBankName');

    function clearBankSelection() {
        bankNameInput.value = '';
        customInput.value = '';
        customWrap.classList.add('hidden');
        bankList.querySelectorAll('.local-bank-chip').forEach(function (el) {
            el.classList.remove('border-indigo-500', 'bg-indigo-500/10', 'text-indigo-600');
        });
    }

    function makeBankChip(label, isOther) {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'local-bank-chip text-left px-3 py-2.5 rounded-xl border border-slate-200 dark:border-white/10 bg-slate-50 dark:bg-[#02040a] text-xs font-semibold text-slate-700 dark:text-slate-200 hover:border-indigo-500 hover:text-indigo-500 transition-all';
        btn.textContent = label;
        btn.dataset.name = isOther ? '' : label;
        btn.addEventListener('click', function () {
            bankList.querySelectorAll('.local-bank-chip').forEach(function (el) {
                el.classList.remove('border-indigo-500', 'bg-indigo-500/10', 'text-indigo-600');
            });
            btn.classList.add('border-indigo-500', 'bg-indigo-500/10', 'text-indigo-600');
            if (isOther) {
                bankNameInput.value = '';
                customWrap.classList.remove('hidden');
                customInput.focus();
            } else {
                bankNameInput.value = label;
                customWrap.classList.add('hidden');
                customInput.value = '';
            }
        });
        return btn;
    }

    function renderBanks(code) {
        clearBankSelection();
        if (!code || !BANK_CATALOG[code]) {
            searchInput.classList.add('hidden');
            bankList.innerHTML = '<p class="text-xs text-slate-500 col-span-full py-4 text-center">Select a country to see available banks.</p>';
            return;
        }
        const meta = BANK_CATALOG[code];
        codeLabel.textContent = meta.code_label;
        codeInput.placeholder = meta.code_placeholder;
        accountInput.placeholder = meta.account_placeholder;
        searchInput.classList.remove('hidden');
        searchInput.value = '';
        bankList.innerHTML = '';
        meta.banks.forEach(function (name) {
            bankList.appendChild(makeBankChip(name, false));
        });
        bankList.appendChild(makeBankChip('Other bank in ' + meta.name, true));
    }

    if (searchInput) {
        searchInput.addEventListener('input', function () {
            const q = this.value.toLowerCase();
            bankList.querySelectorAll('.local-bank-chip').forEach(function (el) {
                const text = (el.textContent || '').toLowerCase();
                el.style.display = text.indexOf(q) !== -1 ? '' : 'none';
            });
        });
    }

    if (countrySelect) {
        countrySelect.addEventListener('change', function () {
            renderBanks(this.value);
        });
    }

    document.getElementById('localBankForm').addEventListener('submit', function (e) {
        const customName = (customInput.value || '').trim();
        if (!bankNameInput.value && !customName) {
            e.preventDefault();
            Swal.fire({icon:'warning', title:'Select a bank', text:'Click a bank from the list, or choose Other and type the name.'});
        }
    });

    window.onclick = function(event) {
        if (event.target.classList.contains('modal-bg')) {
            event.target.classList.add('hidden');
        }
    }

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

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