<?php
// user/dashboard.php
session_start();
require_once __DIR__ . '/../config/config.php';

// =================================================================
// 💰 CURRENCY & SETTINGS (UPDATED TO FETCH FROM USERS TABLE)
// =================================================================

// redirect if not logged in
if (empty($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = (int) $_SESSION['user_id'];

// =================================================================
// HELPER FUNCTIONS (UNCHANGED)
// =================================================================
function generateAccountNumber10() {
    // 10-digit, first digit non-zero
    $first = random_int(1,9);
    $rest = str_pad((string) random_int(0, 999999999), 9, '0', STR_PAD_LEFT);
    return (string)($first . $rest);
}
function generateRouting9() {
    return str_pad((string) random_int(0, 999999999), 9, '0', STR_PAD_LEFT);
}
function formatAcct($acct) {
    // Accepts 10 digits; format 4-3-3 
    if (preg_match('/^\d{10}$/', $acct)) {
        return preg_replace('/(\d{4})(\d{3})(\d{3})/', '$1-$2-$3', $acct);
    }
    return $acct;
}
function formatRouting($r) {
    if (preg_match('/^\d{9}$/', $r)) {
        return preg_replace('/(\d{3})(\d{3})(\d{3})/', '$1-$2-$3', $r);
    }
    return $r;
}
// This column is no longer needed on the 'accounts' table, but kept for legacy check.
// The new routing number will be on the 'users' table.
function ensureRoutingColumn(PDO $pdo) {
    try {
        $q = $pdo->prepare("SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'accounts' AND COLUMN_NAME = 'routing_number'");
        $q->execute();
        $row = $q->fetch();
        if ($row && (int)$row['cnt'] === 0) {
            $pdo->exec("ALTER TABLE accounts ADD COLUMN routing_number VARCHAR(20) NULL AFTER account_number");
        }
    } catch (PDOException $e) {
        error_log("ensureRoutingColumn error: " . $e->getMessage());
    }
}
// 💡 NEW HELPER: Ensure a routing number column on the users table
function ensureUserRoutingColumn(PDO $pdo) {
    try {
        $q = $pdo->prepare("SELECT COUNT(*) AS cnt FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'bank_routing_number'");
        $q->execute();
        $row = $q->fetch();
        if ($row && (int)$row['cnt'] === 0) {
            // Note: I'm adding a unique index for routing number to ensure uniqueness.
            $pdo->exec("ALTER TABLE users ADD COLUMN bank_routing_number VARCHAR(20) NULL UNIQUE AFTER email");
        }
    } catch (PDOException $e) {
        error_log("ensureUserRoutingColumn error: " . $e->getMessage());
    }
}
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }

// =================================================================
// CORE LOGIC (Account fetching/creation)
// =================================================================

ensureUserRoutingColumn($pdo); // Check/create the new user column first

// Fetch user basic info, currency settings, AND PERMANENT ROUTING NUMBER
try {
    $stmt = $pdo->prepare("SELECT user_id, first_name, last_name, email, currency_symbol, currency_country, bank_routing_number
                             FROM users WHERE user_id = :uid LIMIT 1");
    $stmt->execute(['uid' => $user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        header('Location: login.php');
        exit();
    }
    
    // Set currency variables from the fetched user data, with fallbacks
    $currency_symbol = $user['currency_symbol'] ?? '$';
    $country_name = $user['currency_country'] ?? 'United States';
    $user_routing_number = $user['bank_routing_number']; // Get the user's permanent routing number
    
    // 💡 NEW LOGIC: Generate and set the permanent routing number if null
    if (empty($user_routing_number)) {
        $attempts = 0; $rt = null;
        while ($attempts++ < 50) {
            $candidate = generateRouting9();
            // Check uniqueness across the USERS table now
            $q = $pdo->prepare("SELECT COUNT(*) AS cnt FROM users WHERE bank_routing_number = :rt");
            $q->execute(['rt' => $candidate]);
            if ($q->fetchColumn() == 0) { $rt = $candidate; break; }
        }
        if ($rt === null) $rt = generateRouting9(); // Fallback if 50 attempts fail (unlikely)
        
        $user_routing_number = $rt;
        
        // Update the user's record with the new permanent routing number
        $upd = $pdo->prepare("UPDATE users SET bank_routing_number = :rt WHERE user_id = :uid");
        $upd->execute(['rt' => $user_routing_number, 'uid' => $user_id]);
    }
    
} catch (PDOException $e) {
    error_log("DB error fetching user and currency/routing: " . $e->getMessage());
    // Use hardcoded fallback if DB query fails
    $currency_symbol = '$'; 
    $country_name = 'United States (Error Fallback)'; 
    $user_routing_number = '000000000';
}

// ⚠️ Note: The original ensureRoutingColumn for the 'accounts' table is now effectively deprecated
// in favor of the new 'bank_routing_number' on the 'users' table, but kept for strict code evolution.
// ensureRoutingColumn($pdo); 

// Fetch accounts for user
try {
    $stmt = $pdo->prepare("SELECT * FROM accounts WHERE user_id = :uid");
    $stmt->execute(['uid' => $user_id]);
    $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("DB error fetching accounts: " . $e->getMessage());
    $accounts = [];
}

// Auto-create initial Checking account if none exists
if (empty($accounts)) {
    // Logic for generating unique account number (only account number is needed now)
    $attempts = 0; $acct = null;
    while ($attempts++ < 50) {
        $candidate = generateAccountNumber10();
        $q = $pdo->prepare("SELECT COUNT(*) AS cnt FROM accounts WHERE account_number = :acct");
        $q->execute(['acct' => $candidate]);
        if ($q->fetchColumn() == 0) { $acct = $candidate; break; }
    }
    if ($acct === null) $acct = generateAccountNumber10();
    
    try {
        // The accounts table may still have a routing_number column from the previous version,
        // so we'll use the user's new permanent routing number for consistency.
        $ins = $pdo->prepare("INSERT INTO accounts (user_id, account_type, account_number, routing_number, balance, created_at, updated_at)
                             VALUES (:uid, :atype, :acnum, :rtnum, :bal, NOW(), NOW())");
        $ins->execute([
            'uid' => $user_id,
            'atype' => 'Checking',
            'acnum' => $acct,
            // Use the permanent user routing number here for consistency
            'rtnum' => $user_routing_number,
            'bal' => 0.00
        ]);
        // re-fetch accounts
        $stmt = $pdo->prepare("SELECT * FROM accounts WHERE user_id = :uid");
        $stmt->execute(['uid' => $user_id]);
        $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("DB error creating account: " . $e->getMessage());
    }
}

// pick primary account (first)
$primaryAccount = $accounts[0] ?? null;
$accountNumber = $primaryAccount['account_number'] ?? '—';
// 💡 Use the permanent user routing number instead of the (possibly missing/deprecated) account routing number
$routingNumber = $user_routing_number ?? '—';
$balanceRaw = (float)($primaryAccount['balance'] ?? 0.00);
$balance = $currency_symbol . number_format($balanceRaw, 2); 
$accountType = $primaryAccount['account_type'] ?? 'Checking';
$account_id = $primaryAccount['account_id'] ?? null;

// Fetch recent transactions
$transactions = [];
if ($account_id) {
    try {
        $tx = $pdo->prepare("
            SELECT t.*, a.account_number
            FROM transactions t
            JOIN accounts a ON t.account_id = a.account_id
            WHERE t.account_id = :aid
            ORDER BY t.created_at DESC
            LIMIT 10
        ");
        $tx->execute(['aid' => $account_id]);
        $transactions = $tx->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("DB error fetching transactions: " . $e->getMessage());
    }
}
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ダッシュボード — アメリカン銀行</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;800&display=swap" rel="stylesheet">
<style>
/* 🎨 COLOR & TYPOGRAPHY - UPDATED FOR RED ACCENT */
:root{
    --brand: #012A4A; /* Dark Blue */
    --accent: #B71C1C; /* Darker Red/Burgundy */
    --accent-light: #EF5350; /* Lighter Red */
    --danger: #E53935; /* Red (For withdrawals) */
    --success: #1B5E20; /* Green for deposits */
    --muted: #6B7280; /* Gray text */
    --bg: #F8FAFC; /* Light background */
    --card-radius: 12px;
    --max-width: 1200px;
    font-family: 'Roboto', system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial;
    color:#0b2540;
}
*{box-sizing:border-box}
body{
    margin:0; 
    /* Blend the new red accent into the background */
    background: linear-gradient(180deg, rgba(183,28,28,0.04), rgba(1,42,74,0.02)), var(--bg);
    min-height:100vh; 
    display:flex; 
    align-items:flex-start; 
    justify-content:center; 
    padding:24px;
}
.container{ width:100%; max-width:var(--max-width); display:grid; grid-template-columns: 280px 1fr; gap:20px; }

/* Sidebar */
.sidebar{
    background:linear-gradient(180deg, rgba(255,255,255,0.85), rgba(255,255,255,0.65));
    border-radius: var(--card-radius); padding:20px; 
    height:calc(100vh - 48px); position:sticky; top:24px;
    box-shadow: 0 6px 20px rgba(2,8,23,0.06); display:flex; flex-direction:column; gap:16px;
}
.logo{ width:44px; height:44px; border-radius:10px; background:var(--accent); display:flex; align-items:center; justify-content:center; color:white; font-weight:800; font-size:18px; }
.nav{ display:flex; flex-direction:column; gap:6px; margin-top:6px; }
.nav a, .nav button{ text-decoration:none; color:var(--brand); padding:10px 12px; border-radius:8px; font-weight:600; display:flex; align-items:center; gap:10px; transition:all .18s ease; }
.nav a:hover, .nav button:hover{ background:rgba(183,28,28,0.08); transform:translateX(4px); }
.small{ font-size:13px; color:var(--muted); }

/* Main area */
.main{ display:flex; flex-direction:column; gap:18px; }
/* Top bar */
.topbar{ display:flex; justify-content:space-between; align-items:center; gap:12px; }
.search{ flex:1; display:flex; gap:12px; align-items:center; }
.search input{ width:100%; padding:12px 14px; border-radius:10px; border:1px solid rgba(2,8,23,0.06); background:white; font-size:14px; }
.actions{ display:flex; gap:12px; align-items:center; }
.btn{ padding:10px 14px; border-radius:10px; border:0; cursor:pointer; font-weight:600; transition: all 0.2s ease; }
/* Primary button uses the new red accent */
.btn-primary{ background:linear-gradient(90deg,var(--accent),var(--accent-light)); color:white; box-shadow: 0 4px 12px rgba(183,28,28,0.18); }
.btn-primary:hover{ transform: translateY(-2px); box-shadow: 0 6px 15px rgba(183,28,28,0.25); }
.btn-ghost{ background:transparent; color:var(--brand); border:1px solid rgba(2,8,23,0.06); }

/* Grid cards */
.grid{ display:grid; grid-template-columns: 1fr 360px; gap:18px; }
.card{ background:white; padding:18px; border-radius:12px; box-shadow: 0 8px 30px rgba(2,8,23,0.04); }
.account-card{ display:flex; flex-direction:column; gap:14px; position:relative; overflow:hidden; }
.account-top{ display:flex; justify-content:space-between; align-items:flex-start; }
.acct-num{ font-size:20px; font-weight:700; color:var(--brand); }
.meta{ color:var(--muted); font-size:13px; }
/* Chip uses the new accent */
.chip{ background:linear-gradient(90deg, rgba(183,28,28,0.08), rgba(1,42,74,0.04)); padding:8px 12px; border-radius:10px; font-weight:700; color:var(--accent); font-size:14px; }
.small-muted{ color:var(--muted); font-size:13px; }

/* Transactions */
.txn{ display:flex; justify-content:space-between; gap:12px; align-items:center; padding:10px 0; border-bottom:1px dashed rgba(2,8,23,0.04); }
.txn:last-child{ border-bottom:none; }
.txn-amount-pos { color: var(--success); font-weight: 600; } 
.txn-amount-neg { color: var(--danger); font-weight: 600; }

/* Quick actions grid */
.quick{ display:grid; grid-template-columns: repeat(3,1fr); gap:10px; }
.quick .btn{ padding:12px; border-radius:10px; font-weight:700; }

/* Utility Styles for Copy button and Notice */
/* Copy button uses the new accent */
.copy-btn{ background:transparent; border:0; color:var(--accent); cursor:pointer; font-weight:700; padding:6px 8px; border-radius:8px; transition: color 0.2s ease; }
.copy-btn:hover { color: var(--brand); }
/* Notice uses the new accent */
.notice{ background:linear-gradient(90deg, rgba(183,28,28,0.06), rgba(1,42,74,0.03)); padding:12px; border-radius:10px; color:var(--brand); font-weight:600; border-left: 4px solid var(--accent); }

/* 📱 FULL MOBILE RESPONSIVENESS (Original CSS preserved and enforced) */
@media (max-width: 980px){
    /* 1. Tablet View: Single Column Layout */
    .container{ grid-template-columns: 1fr; padding:12px; }
    .sidebar{ 
        position:relative; 
        height:auto; 
        top:0; 
        order:2; /* Move sidebar below main content */
        width: 100%;
        display: block; /* Disable flex-column to manage internal layout on mobile */
    }
    .grid{ grid-template-columns: 1fr; }
    
    /* Adapt Sidebar for tablet/mobile: horizontal menu */
    .sidebar > div:first-child { margin-bottom: 15px; }
    .nav { 
        flex-direction: row; 
        flex-wrap: wrap; 
        gap: 8px;
        border-top: 1px solid rgba(2,8,23,0.08); 
        padding-top: 15px; 
        margin-top: 15px;
    }
    .nav a, .nav button { flex: 1 1 120px; justify-content: center; text-align: center; }
}

@media (max-width: 520px){
    /* 2. Small Mobile View */
    body { padding: 12px; }

    /* Topbar stacking and search bar full width */
    .topbar { flex-wrap: wrap; }
    .search { order: 3; flex: 0 0 100%; margin-top: 10px; } 
    .actions { order: 2; margin-left: auto; }
    
    /* Account Card Stacking */
    .account-top { flex-direction: column; align-items: flex-start; gap: 10px; }
    .account-top > div:last-child { 
        text-align: left !important; 
        margin-top: 5px; 
        width: 100%; /* Ensure balance takes full width */
        border-top: 1px dashed rgba(2,8,23,0.06);
        padding-top: 10px;
    }
    .account-card .acct-num { font-size: 18px; }
    
    /* Quick Actions stacking */
    .quick{ grid-template-columns: repeat(2,1fr); }
    .btn { font-size: 13px; padding: 8px 10px; }
    
    /* Sidebar bottom elements adjustment */
    .sidebar > div:last-child { margin-top: 15px; }
    .sidebar .nav { border-bottom: 1px solid rgba(2,8,23,0.08); padding-bottom: 15px; }
}
</style>
</head>
<body>
<div class="container" role="application" aria-label="User dashboard">
    <aside class="sidebar" aria-label="Navigation">
        <div style="display:flex; gap:12px; align-items:center;">
            <div class="logo">AM</div>
            <div>
                <div style="font-weight:800; color:var(--brand);">アメリカン銀行</div>
                <div class="small">個人向けバンキング</div>
            </div>
        </div>

        <nav class="nav" aria-label="Main navigation">
             <button class="btn btn-primary" style="color: white;" onclick="document.getElementById('acct-heading').scrollIntoView({behavior:'smooth'})">アカウントダッシュボード</button>
             <a href="profile.php">プロフィール</a>
             <a href="atm_card.php">ATMカード</a>
             <a href="">有効化</a> 
        </nav>

        <div style="margin-top:auto;">
            <div class="small-muted" style="font-weight: 700;">国/通貨:</div>
            <div style="font-weight: 600; color: var(--brand); margin-top: 4px;">
                <?= e($country_name); ?> (<?= e($currency_symbol); ?>)
            </div>

            <div style="display:flex; gap:8px; margin-top:12px;">
                <button class="btn btn-ghost" onclick="window.location.href='jalogin.php'">ログアウト</button>
            </div>
            <p class="small-muted" style="margin-top:12px;">© <?= date('Y'); ?> アメリカン銀行</p>
        </div>
    </aside>

    <main class="main">
        <div class="topbar">
            <div class="search" role="search">
                <input type="search" placeholder="Search transactions, payments, help..." aria-label="Search">
                <button class="btn btn-primary" style="flex-shrink: 0;">検索</button>
            </div>
            <div class="actions">
                <button class="btn btn-ghost" title="Notifications">🔔</button>
                <button class="btn btn-primary" onclick="window.location.href='transfer.php'">新規振込</button>
            </div>
        </div>

        <div class="grid" role="region" aria-label="Account overview">
            <section class="card account-card" aria-labelledby="acct-heading">
                <div class="account-top">
                    <div>
                        <div class="meta"><?= e($accountType) ?></div>
                        <div id="acct-heading" class="acct-num"><?= e(formatAcct($accountNumber)) ?></div>
                        <div class="meta" style="margin-top:6px;">Routing: <span style="font-weight:700; color:var(--brand)"><?= e(formatRouting($routingNumber)) ?></span></div>
                    </div>
                    <div style="text-align:right;">
                        <div class="small-muted">Available balance</div>
                        <div style="font-size:22px; font-weight:800; color:var(--brand);"><?= e($balance) ?></div> 
                        <div style="margin-top:8px;">
                            <button class="copy-btn" data-copy="<?= e($accountNumber) ?>" title="Copy account">Copy Account</button>
                            <button class="copy-btn" data-copy="<?= e($routingNumber) ?>" title="Copy routing">Copy Routing</button>
                        </div>
                    </div>
                </div>

                <div style="display:flex; gap:12px; flex-wrap:wrap; margin-top:8px;">
                    <div class="chip">Debit • Visa</div>
                    <div class="chip">Online Banking</div>
                    <div class="chip">eStatements</div>
                </div>

                <div style="margin-top:12px;">
                    <div class="small-muted">Recent activity</div>
                    <div style="margin-top:12px;">
                        <?php if (empty($transactions)): ?>
                            <div class="small-muted">No recent transactions</div>
                        <?php else: ?>
                            <?php foreach ($transactions as $t): 
                                $title = $t['description'] ?? $t['narration'] ?? $t['type'] ?? 'Activity';
                                $title = str_replace(
                                    '{BALANCE ADJUSTED BY ADMIN}', 
                                    '{BALANCE}',
                                    $title
                                );
                                $title = e($title);
                                $amount = (float)($t['amount'] ?? 0.0);
                                $sign = (strtolower($t['type']) === 'deposit') ? '+' : '-';
                                $colorClass = ($sign === '+') ? 'txn-amount-pos' : 'txn-amount-neg';
                                $fmtAmt = $sign . e($currency_symbol) . number_format(abs($amount), 2);
                                $when = e(date('M j, Y', strtotime($t['created_at'] ?? 'now')));
                            ?>
                                <div class="txn" role="article" aria-label="<?= $title ?>">
                                    <div>
                                        <strong><?= $title ?></strong>
                                        <div class="small-muted"><?= $when ?></div>
                                    </div>
                                    <div class="<?= $colorClass ?>"><?= $fmtAmt ?></div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </section>

            <aside>
                <div class="card" id="transfer" aria-labelledby="quick-actions">
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <div id="quick-actions" style="font-weight:800; color:var(--brand)">クイックアクション</div>
                        <div class="small-muted">安全 • 高速</div>
                    </div>

                    <div style="margin-top:12px;" class="quick" role="toolbar" aria-label="Quick actions">
                        <button class="btn btn-ghost" onclick="window.location.href='transfer.php'">振込</button>
                        <button class="btn btn-ghost" onclick="window.location.href='profile.php'">プロフィール</button>
                        <button class="btn btn-ghost" onclick="window.location.href='atm_card.php'">ATMカード</button>
                        <button class="btn btn-ghost" onclick="window.location.href='transaction_history.php'">取引履歴</button>
                        <button class="btn btn-ghost" onclick="window.location.href='support.php'">サポート</button>
                        <button class="btn btn-ghost" onclick="window.location.href='#'">有効化</button>
                    </div>

                    <div style="margin-top:14px;">
                        <div class="notice">口座番号およびルーティング番号はお客様の口座に永久的に割り当てられています。安全に保管してください。</div>
                        <div style="display:flex; gap:8px; margin-top:12px;">
                            <button class="btn btn-primary" id="download-btn">情報をダウンロード</button>
                        </div>
                    </div>

                    <div style="margin-top:12px;" class="small-muted">
                        ルーティング番号は9桁です。口座番号は安全のため一部伏せられています。
                    </div>
                </div>

                <div class="card" style="margin-top:18px;">
                    <div style="font-weight:800; color:var(--brand)">セキュリティ</div>
                    <div class="small-muted" style="margin-top:10px;">二要素認証が有効になっています</div>
                </div>
            </aside>
        </div>

    </main>
</div>

<script>
// copy buttons
document.querySelectorAll('.copy-btn').forEach(btn=>{
    btn.addEventListener('click', async ()=>{
        // Cleans up any formatting (dashes) before copying
        const txt = btn.getAttribute('data-copy').replace(/-/g, ''); 
        try{
            await navigator.clipboard.writeText(txt);
            const old = btn.textContent;
            btn.textContent = 'Copied';
            setTimeout(()=>btn.textContent = old, 1400);
        }catch(e){
            alert('Copy failed. Number: ' + txt);
        }
    });
});

// 💡 ENHANCEMENT: Download basic info (including balance and currency)
document.getElementById('download-btn').addEventListener('click', ()=>{
    const acct = `<?= addslashes($accountNumber) ?>`;
    const rt = `<?= addslashes($routingNumber) ?>`;
    const bal = `<?= addslashes(number_format($balanceRaw, 2)) ?>`; // Use raw balance for clean text file
    const sym = `<?= addslashes($currency_symbol) ?>`;
    const type = `<?= addslashes($accountType) ?>`;
    
    const content = 
        `--- American Bank Account Information ---\n` +
        `Account Type: ${type}\n` +
        `Account Number: ${acct}\n` +
        `Routing Number: ${rt}\n` +
        `Current Balance: ${sym}${bal}\n` +
        `Date Generated: <?= addslashes(date('c')) ?>\n` +
        `-----------------------------------\n`;
        
    const blob = new Blob([content], {type:'text/plain'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; 
    a.download = 'American Bank_Account_Info_' + type.replace(/\s/g, '_') + '.txt'; 
    document.body.appendChild(a); 
    a.click();
    a.remove(); 
    URL.revokeObjectURL(url);
});
</script>
</body>
</html>