<?php
/**
 * Local bank directory for Connect Your Bank.
 * 10 widely used countries with major retail banks.
 * Account-link only — no bank login passwords.
 */

function local_banks_catalog() {
    return [
        'US' => [
            'name' => 'United States',
            'flag' => '🇺🇸',
            'currency' => 'USD',
            'code_label' => 'Routing number',
            'code_placeholder' => 'e.g. 021000021',
            'account_placeholder' => 'Checking / savings account number',
            'banks' => [
                'JPMorgan Chase', 'Bank of America', 'Wells Fargo', 'Citibank', 'U.S. Bank',
                'PNC Bank', 'Capital One', 'TD Bank', 'Truist', 'Goldman Sachs (Marcus)',
                'Charles Schwab Bank', 'Ally Bank', 'Navy Federal Credit Union', 'USAA'
            ],
        ],
        'CN' => [
            'name' => 'China',
            'flag' => '🇨🇳',
            'currency' => 'CNY',
            'code_label' => 'CNAPS / Bank code',
            'code_placeholder' => 'e.g. 102100099996',
            'account_placeholder' => 'Bank account number',
            'banks' => [
                'Industrial and Commercial Bank of China (ICBC)', 'China Construction Bank',
                'Agricultural Bank of China', 'Bank of China', 'Bank of Communications',
                'China Merchants Bank', 'Postal Savings Bank of China', 'Industrial Bank',
                'Shanghai Pudong Development Bank', 'China CITIC Bank'
            ],
        ],
        'IN' => [
            'name' => 'India',
            'flag' => '🇮🇳',
            'currency' => 'INR',
            'code_label' => 'IFSC code',
            'code_placeholder' => 'e.g. HDFC0000001',
            'account_placeholder' => 'Account number',
            'banks' => [
                'State Bank of India (SBI)', 'HDFC Bank', 'ICICI Bank', 'Axis Bank',
                'Kotak Mahindra Bank', 'Punjab National Bank', 'Bank of Baroda',
                'Canara Bank', 'Union Bank of India', 'Yes Bank', 'IDFC FIRST Bank', 'Paytm Payments Bank'
            ],
        ],
        'GB' => [
            'name' => 'United Kingdom',
            'flag' => '🇬🇧',
            'currency' => 'GBP',
            'code_label' => 'Sort code',
            'code_placeholder' => 'e.g. 20-00-00',
            'account_placeholder' => '8-digit account number',
            'banks' => [
                'Barclays', 'HSBC UK', 'Lloyds Bank', 'NatWest', 'Santander UK',
                'Nationwide', 'Halifax', 'Monzo', 'Starling Bank', 'Revolut', 'TSB', 'Metro Bank'
            ],
        ],
        'DE' => [
            'name' => 'Germany',
            'flag' => '🇩🇪',
            'currency' => 'EUR',
            'code_label' => 'BLZ / Bank code',
            'code_placeholder' => 'e.g. 10070000',
            'account_placeholder' => 'IBAN preferred below, or account number',
            'banks' => [
                'Deutsche Bank', 'Commerzbank', 'KfW', 'DZ Bank', 'Sparkasse',
                'Volksbank', 'ING-DiBa', 'N26', 'Postbank', 'HypoVereinsbank (UniCredit)'
            ],
        ],
        'JP' => [
            'name' => 'Japan',
            'flag' => '🇯🇵',
            'currency' => 'JPY',
            'code_label' => 'Branch code',
            'code_placeholder' => 'e.g. 001',
            'account_placeholder' => 'Account number',
            'banks' => [
                'Mitsubishi UFJ (MUFG)', 'Mizuho Bank', 'Sumitomo Mitsui (SMBC)',
                'Japan Post Bank', 'Resona Bank', 'Rakuten Bank', 'Sony Bank',
                'SBI Sumishin Net Bank', 'PayPay Bank', 'Seven Bank'
            ],
        ],
        'FR' => [
            'name' => 'France',
            'flag' => '🇫🇷',
            'currency' => 'EUR',
            'code_label' => 'Bank code (code banque)',
            'code_placeholder' => 'e.g. 30004',
            'account_placeholder' => 'Account number (or use IBAN below)',
            'banks' => [
                'BNP Paribas', 'Crédit Agricole', 'Société Générale', 'Banque Populaire',
                'Caisse d’Épargne', 'Crédit Mutuel', 'La Banque Postale', 'HSBC France',
                'Boursorama', 'Hello bank!'
            ],
        ],
        'CA' => [
            'name' => 'Canada',
            'flag' => '🇨🇦',
            'currency' => 'CAD',
            'code_label' => 'Institution + Transit',
            'code_placeholder' => 'e.g. 004-12345',
            'account_placeholder' => 'Account number',
            'banks' => [
                'Royal Bank of Canada (RBC)', 'TD Canada Trust', 'Scotiabank',
                'Bank of Montreal (BMO)', 'CIBC', 'National Bank of Canada',
                'Desjardins', 'Tangerine', 'EQ Bank', 'Simplii Financial'
            ],
        ],
        'BR' => [
            'name' => 'Brazil',
            'flag' => '🇧🇷',
            'currency' => 'BRL',
            'code_label' => 'Agency (agência)',
            'code_placeholder' => 'e.g. 0001',
            'account_placeholder' => 'Account number with digit',
            'banks' => [
                'Itaú Unibanco', 'Banco do Brasil', 'Bradesco', 'Santander Brasil',
                'Caixa Econômica Federal', 'Nubank', 'Banco Inter', 'BTG Pactual',
                'Banco Safra', 'C6 Bank'
            ],
        ],
        'NG' => [
            'name' => 'Nigeria',
            'flag' => '🇳🇬',
            'currency' => 'NGN',
            'code_label' => 'Bank code',
            'code_placeholder' => 'e.g. 058',
            'account_placeholder' => '10-digit NUBAN account number',
            'banks' => [
                'Guaranty Trust Bank (GTBank)', 'Access Bank', 'Zenith Bank',
                'First Bank of Nigeria', 'United Bank for Africa (UBA)', 'Fidelity Bank',
                'Union Bank of Nigeria', 'Stanbic IBTC', 'Ecobank Nigeria',
                'Sterling Bank', 'Polaris Bank', 'Opay', 'PalmPay'
            ],
        ],
    ];
}

function local_banks_ensure_table($link) {
    mysqli_query($link, "CREATE TABLE IF NOT EXISTS connected_local_banks (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        country_code VARCHAR(8) NOT NULL,
        country_name VARCHAR(64) NOT NULL,
        bank_name VARCHAR(128) NOT NULL,
        account_name VARCHAR(128) NOT NULL,
        account_number VARCHAR(64) NOT NULL,
        account_id VARCHAR(128) DEFAULT NULL,
        bank_email VARCHAR(191) DEFAULT NULL,
        bank_code VARCHAR(64) DEFAULT NULL,
        iban VARCHAR(64) DEFAULT NULL,
        swift VARCHAR(32) DEFAULT NULL,
        currency VARCHAR(8) DEFAULT 'USD',
        status VARCHAR(20) DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_user (user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $extra_cols = [
        'account_id' => "ALTER TABLE connected_local_banks ADD COLUMN account_id VARCHAR(128) DEFAULT NULL AFTER account_number",
        'bank_email' => "ALTER TABLE connected_local_banks ADD COLUMN bank_email VARCHAR(191) DEFAULT NULL AFTER account_id",
    ];
    foreach ($extra_cols as $name => $sql) {
        $check = mysqli_query($link, "SHOW COLUMNS FROM connected_local_banks LIKE '" . mysqli_real_escape_string($link, $name) . "'");
        if ($check && mysqli_num_rows($check) === 0) {
            mysqli_query($link, $sql);
        }
    }
}

function local_banks_for_user($link, $user_id) {
    local_banks_ensure_table($link);
    $uid = intval($user_id);
    $res = mysqli_query($link, "SELECT * FROM connected_local_banks WHERE user_id='$uid' AND status='active' ORDER BY created_at DESC");
    $rows = [];
    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function local_bank_by_id($link, $user_id, $bank_id) {
    local_banks_ensure_table($link);
    $uid = intval($user_id);
    $bid = intval($bank_id);
    $res = mysqli_query($link, "SELECT * FROM connected_local_banks WHERE id='$bid' AND user_id='$uid' AND status='active' LIMIT 1");
    return ($res && mysqli_num_rows($res) > 0) ? mysqli_fetch_assoc($res) : null;
}

function local_bank_label($row) {
    $last4 = substr($row['account_number'], -4);
    return $row['bank_name'] . ' •••• ' . $last4 . ' (' . $row['country_code'] . ')';
}

function local_bank_destination_note($row, $purpose = 'BANK') {
    $note = strtoupper($purpose)
        . ' | ' . $row['country_code']
        . ' | ' . $row['bank_name']
        . ' | ' . $row['account_name']
        . ' | Acct:' . $row['account_number'];
    if (!empty($row['bank_code'])) {
        $note .= ' | Code:' . $row['bank_code'];
    }
    if (!empty($row['iban'])) {
        $note .= ' | IBAN:' . $row['iban'];
    }
    if (!empty($row['account_id'])) {
        $note .= ' | ID:' . $row['account_id'];
    }
    if (!empty($row['bank_email'])) {
        $note .= ' | Email:' . $row['bank_email'];
    }
    if (!empty($row['swift'])) {
        $note .= ' | SWIFT:' . $row['swift'];
    }
    if (strlen($note) > 240) {
        $note = strtoupper($purpose)
            . ' | ' . $row['bank_name']
            . ' | ' . $row['account_name']
            . ' | Acct:' . $row['account_number'];
    }
    return $note;
}

function local_banks_all($link) {
    local_banks_ensure_table($link);
    $res = mysqli_query($link, "SELECT b.*, u.username, u.email AS user_email
            FROM connected_local_banks b
            JOIN users u ON b.user_id = u.id
            ORDER BY b.created_at DESC");
    $rows = [];
    if ($res) {
        while ($row = mysqli_fetch_assoc($res)) {
            $rows[] = $row;
        }
    }
    return $rows;
}

function local_bank_is_allowed($country_code, $bank_name, $catalog) {
    if (!isset($catalog[$country_code]) || $bank_name === '') {
        return false;
    }
    if (in_array($bank_name, $catalog[$country_code]['banks'], true)) {
        return true;
    }
    $len = strlen($bank_name);
    return $len >= 2 && $len <= 128;
}
