<?php
require_once __DIR__ . '/../config/database.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'client') {
    header('Location: ../index.php');
    exit;
}

if (($_SESSION['user_agent'] ?? '') !== ($_SERVER['HTTP_USER_AGENT'] ?? '')) {
    session_destroy();
    header('Location: ../index.php');
    exit;
}

$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
$user = $stmt->fetch();

$stmt = $pdo->prepare("SELECT * FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$account = $stmt->fetch();

$transactions = [];
if ($account) {
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE account_id = ? ORDER BY created_at DESC LIMIT 10");
    $stmt->execute([$account['id']]);
    $transactions = $stmt->fetchAll();
}

$pendingIntl = [];
if ($account) {
    $stmt = $pdo->prepare("SELECT * FROM international_transfers WHERE account_id = ? AND status = 'pending' ORDER BY created_at DESC");
    $stmt->execute([$account['id']]);
    $pendingIntl = $stmt->fetchAll();
}

$clientCards = [];
$stmt = $pdo->prepare("SELECT * FROM client_cards WHERE user_id = ? ORDER BY is_default DESC, created_at DESC LIMIT 4");
$stmt->execute([$userId]);
$clientCards = $stmt->fetchAll();

$activeInvestments = [];
$stmt = $pdo->prepare("SELECT * FROM investments WHERE user_id = ? AND status = 'active' ORDER BY maturity_date ASC LIMIT 3");
$stmt->execute([$userId]);
$activeInvestments = $stmt->fetchAll();

$pageTitle = 'Dashboard - Martin Ford Bank';
require_once __DIR__ . '/../config/header.php';
?>

<style>
:root {
    --primary: #1a3a5c;
    --primary-light: #2563eb;
    --accent: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --bg: #f0f4f8;
    --card-bg: #ffffff;
    --text: #1e293b;
    --text-muted: #64748b;
    --border: #e2e8f0;
    --shadow: 0 1px 3px rgba(0,0,0,.06), 0 1px 2px rgba(0,0,0,.04);
    --shadow-md: 0 4px 6px -1px rgba(0,0,0,.07), 0 2px 4px -2px rgba(0,0,0,.05);
    --radius: 12px;
}

body { background: var(--bg); color: var(--text); font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; }

.nav-top {
    background: var(--primary);
    padding: 0 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 60px;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 8px rgba(0,0,0,.15);
}
.nav-brand { color: #fff; text-decoration: none; font-weight: 700; font-size: 18px; display: flex; align-items: center; gap: 8px; }
.nav-brand span { color: #93c5fd; }
.nav-links { display: flex; gap: 4px; }
.nav-link {
    color: rgba(255,255,255,.7);
    text-decoration: none;
    padding: 8px 14px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 500;
    transition: all .2s;
}
.nav-link:hover, .nav-link.active { background: rgba(255,255,255,.12); color: #fff; }
.nav-link.logout { color: #fca5a5; }
.nav-link.logout:hover { background: rgba(239,68,68,.2); color: #fca5a5; }

.container { max-width: 1200px; margin: 0 auto; padding: 24px; }

.welcome-banner {
    background: linear-gradient(135deg, var(--primary), var(--primary-light));
    color: #fff;
    padding: 32px;
    border-radius: var(--radius);
    margin-bottom: 24px;
    box-shadow: var(--shadow-md);
}
.welcome-banner h2 { margin: 0 0 6px; font-size: 24px; font-weight: 700; }
.welcome-banner p { margin: 0; opacity: .8; font-size: 14px; }

.alert { padding: 14px 18px; border-radius: 10px; margin-bottom: 20px; font-size: 14px; font-weight: 500; }
.alert-warning { background: #fef3c7; color: #92400e; border: 1px solid #fde68a; }
.alert-warning a { color: var(--primary-light); font-weight: 600; }
.alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
.alert-danger { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

.grid { display: grid; gap: 20px; }
.grid-4 { grid-template-columns: repeat(4, 1fr); }
.grid-2 { grid-template-columns: repeat(2, 1fr); }
@media (max-width: 900px) { .grid-4 { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 600px) { .grid-4, .grid-2 { grid-template-columns: 1fr; } .nav-links { display: none; } }

.card {
    background: var(--card-bg);
    border-radius: var(--radius);
    border: 1px solid var(--border);
    box-shadow: var(--shadow);
    overflow: hidden;
    margin-bottom: 20px;
}
.card-header {
    padding: 20px 24px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--border);
}
.card-title { font-size: 16px; font-weight: 700; color: var(--text); }

.stat-card {
    padding: 24px;
    text-align: center;
    transition: transform .2s, box-shadow .2s;
}
.stat-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); }
.stat-value { font-size: 28px; font-weight: 800; color: var(--primary); margin-bottom: 4px; }
.stat-label { font-size: 12px; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: .5px; }

.badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: .3px;
}
.badge-success { background: #d1fae5; color: #065f46; }
.badge-warning { background: #fef3c7; color: #92400e; }
.badge-danger { background: #fee2e2; color: #991b1b; }

.btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 10px 20px;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 600;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: all .2s;
    gap: 6px;
}
.btn-primary { background: var(--primary-light); color: #fff; }
.btn-primary:hover { background: #1d4ed8; }
.btn-secondary { background: var(--bg); color: var(--text); border: 1px solid var(--border); }
.btn-secondary:hover { background: #e2e8f0; }
.btn-outline { background: transparent; color: var(--primary-light); border: 1px solid var(--primary-light); }
.btn-outline:hover { background: rgba(37,99,235,.06); }
.btn-sm { padding: 6px 14px; font-size: 12px; }
.btn-block { width: 100%; text-align: center; }
.btn-success { background: var(--accent); color: #fff; }
.btn-success:hover { background: #059669; }

table { width: 100%; border-collapse: collapse; }
thead th {
    text-align: left;
    padding: 12px 16px;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .5px;
    color: var(--text-muted);
    background: #f8fafc;
    border-bottom: 2px solid var(--border);
}
tbody td {
    padding: 14px 16px;
    font-size: 14px;
    border-bottom: 1px solid var(--border);
}
tbody tr:last-child td { border-bottom: none; }
tbody tr:hover { background: #f8fafc; }
.text-right { text-align: right; }
.text-center { text-align: center; }
.text-muted { color: var(--text-muted); }
.amount-credit { color: var(--accent); }
.amount-debit { color: var(--danger); }

.card-visual {
    border-radius: 14px;
    padding: 20px;
    color: #fff;
    position: relative;
    overflow: hidden;
    min-height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.card-visual::before {
    content: '';
    position: absolute;
    top: -30%;
    right: -20%;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: rgba(255,255,255,.08);
}
</style>

<nav class="nav-top">
    <a href="dashboard.php" class="nav-brand">
        <img src="../assets/logo.png" alt="MFB" style="height:32px;">
        Martin Ford <span>Bank</span>
    </a>
    <div class="nav-links">
        <a href="dashboard.php" class="nav-link active">Dashboard</a>
        <a href="transfer.php" class="nav-link">Transfer</a>
        <a href="international-transfer.php" class="nav-link">International</a>
        <a href="deposit.php" class="nav-link">Deposit</a>
        <a href="invest.php" class="nav-link">Invest</a>
        <a href="cards.php" class="nav-link">Cards</a>
        <a href="transactions.php" class="nav-link">History</a>
        <a href="profile.php" class="nav-link">Profile</a>
        <a href="../logout.php" class="nav-link logout">Logout</a>
    </div>
</nav>

<div class="container">
    <div class="welcome-banner">
        <h2>Welcome back, <?php echo e($user['full_name']); ?> 👋</h2>
        <p>Last login: <?php echo date('M d, Y h:i A'); ?> · Account: <?php echo e($account['account_number'] ?? 'N/A'); ?></p>
    </div>

    <?php if ($user['kyc_status'] !== 'verified'): ?>
        <div class="alert alert-warning">
            ⚠️ Your KYC verification is pending. Some features may be restricted. <a href="profile.php">Upload documents →</a>
        </div>
    <?php endif; ?>

    <div class="grid grid-4" style="margin-bottom: 24px;">
        <div class="card stat-card">
            <div class="stat-value"><?php echo formatMoney($account['balance'] ?? 0); ?></div>
            <div class="stat-label">Available Balance</div>
        </div>
        <div class="card stat-card">
            <div class="stat-value" style="font-size:20px;"><?php echo e($account['account_type'] ?? 'N/A'); ?></div>
            <div class="stat-label">Account Type</div>
        </div>
        <div class="card stat-card">
            <div class="stat-value"><?php echo count($pendingIntl); ?></div>
            <div class="stat-label">Pending Transfers</div>
        </div>
        <div class="card stat-card">
            <div class="stat-value">
                <span class="badge badge-<?php echo $user['kyc_status'] === 'verified' ? 'success' : 'warning'; ?>">
                    <?php echo ucfirst(e($user['kyc_status'])); ?>
                </span>
            </div>
            <div class="stat-label">KYC Status</div>
        </div>
    </div>

    <div class="grid grid-2" style="margin-bottom: 24px;">
        <div class="card">
            <div class="card-header">
                <div class="card-title">⚡ Quick Actions</div>
            </div>
            <div style="padding: 20px;">
                <div class="grid grid-2" style="gap: 10px;">
                    <a href="deposit.php" class="btn btn-success btn-block">💰 Deposit</a>
                    <a href="transfer.php" class="btn btn-primary btn-block">↗ Transfer</a>
                    <a href="international-transfer.php" class="btn btn-secondary btn-block">🌍 International</a>
                    <a href="invest.php" class="btn btn-secondary btn-block">📈 Invest</a>
                    <a href="transactions.php" class="btn btn-outline btn-block">📋 Statement</a>
                    <a href="profile.php" class="btn btn-outline btn-block">👤 Profile</a>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <div class="card-title">🏦 Account Details</div>
            </div>
            <div style="padding: 4px 0;">
                <table>
                    <tr><td class="text-muted">Account Number</td><td class="text-right"><strong><?php echo e($account['account_number'] ?? 'N/A'); ?></strong></td></tr>
                    <tr><td class="text-muted">Account Type</td><td class="text-right"><?php echo e($account['account_type'] ?? 'N/A'); ?></td></tr>
                    <tr><td class="text-muted">Status</td><td class="text-right"><span class="badge badge-<?php echo ($account['status'] ?? '') === 'active' ? 'success' : 'danger'; ?>"><?php echo ucfirst(e($account['status'] ?? 'N/A')); ?></span></td></tr>
                    <tr><td class="text-muted">Daily Limit</td><td class="text-right"><?php echo formatMoney($account['daily_transfer_limit'] ?? 0); ?></td></tr>
                    <tr><td class="text-muted">Member Since</td><td class="text-right"><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td></tr>
                </table>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-header">
            <div class="card-title">📊 Recent Transactions</div>
            <a href="transactions.php" class="btn btn-outline btn-sm">View All →</a>
        </div>
        <?php if (empty($transactions)): ?>
            <p class="text-center text-muted" style="padding: 40px;">No transactions yet.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Reference</th>
                        <th>Type</th>
                        <th class="text-right">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($transactions as $txn): ?>
                    <tr>
                        <td><?php echo date('M d, Y', strtotime($txn['created_at'])); ?></td>
                        <td><?php echo e($txn['description']); ?></td>
                        <td><code style="font-size:11px;background:#f1f5f9;padding:2px 6px;border-radius:4px;"><?php echo e($txn['reference']); ?></code></td>
                        <td><span class="badge badge-<?php echo $txn['type'] === 'credit' ? 'success' : 'danger'; ?>"><?php echo ucfirst(e($txn['type'])); ?></span></td>
                        <td class="text-right <?php echo $txn['type'] === 'credit' ? 'amount-credit' : 'amount-debit'; ?>">
                            <strong><?php echo ($txn['type'] === 'credit' ? '+' : '-') . formatMoney($txn['amount']); ?></strong>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <?php if (!empty($clientCards)): ?>
    <div class="card">
        <div class="card-header">
            <div class="card-title">💳 My Cards</div>
            <a href="cards.php" class="btn btn-outline btn-sm">Manage →</a>
        </div>
        <div style="padding: 20px;">
            <div class="grid grid-2" style="gap: 14px;">
                <?php
                $cardColors = [
                    'visa' => ['#1a1f71', '#2d3494'],
                    'mastercard' => ['#1a1a2e', '#e94560'],
                    'amex' => ['#003366', '#006fcf'],
                    'default' => ['#1e293b', '#334155']
                ];
                foreach ($clientCards as $ccard):
                    $colors = $cardColors[$ccard['card_brand']] ?? $cardColors['default'];
                ?>
                <div class="card-visual" style="background: linear-gradient(135deg, <?php echo $colors[0]; ?>, <?php echo $colors[1]; ?>);">
                    <?php if ($ccard['is_default']): ?>
                        <span style="position:absolute;top:12px;right:12px;background:rgba(255,255,255,.2);padding:3px 10px;border-radius:20px;font-size:10px;font-weight:600;backdrop-filter:blur(4px);">DEFAULT</span>
                    <?php endif; ?>
                    <div>
                        <div style="font-size:10px;opacity:.6;text-transform:uppercase;letter-spacing:1px;"><?php echo ucfirst(e($ccard['card_type'])); ?></div>
                        <div style="font-size:20px;font-weight:700;letter-spacing:3px;margin:12px 0;">•••• •••• •••• <?php echo e($ccard['card_last4']); ?></div>
                    </div>
                    <div style="display:flex;justify-content:space-between;font-size:12px;opacity:.8;">
                        <span><?php echo strtoupper(e($ccard['card_holder'])); ?></span>
                        <span><?php echo str_pad($ccard['exp_month'],2,'0',STR_PAD_LEFT) . '/' . substr($ccard['exp_year'],-2); ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php else: ?>
    <div class="card" style="text-align:center;padding:32px;">
        <p class="text-muted">No cards added yet. <a href="cards.php" style="color:var(--primary-light);font-weight:600;">Add a card →</a></p>
    </div>
    <?php endif; ?>

    <?php if (!empty($activeInvestments)): ?>
    <div class="card">
        <div class="card-header">
            <div class="card-title">📈 Active Investments</div>
            <a href="invest.php" class="btn btn-outline btn-sm">View All →</a>
        </div>
        <table>
            <thead>
                <tr><th>Amount</th><th>Term</th><th>Rate</th><th>Expected Return</th><th>Maturity</th></tr>
            </thead>
            <tbody>
                <?php foreach ($activeInvestments as $ainv): ?>
                <tr>
                    <td><strong><?php echo formatMoney($ainv['amount']); ?></strong></td>
                    <td><?php echo $ainv['term_months']; ?> months</td>
                    <td><span class="badge badge-success"><?php echo $ainv['rate']; ?>%</span></td>
                    <td class="amount-credit"><strong><?php echo formatMoney($ainv['expected_return']); ?></strong></td>
                    <td><?php echo date('M d, Y', strtotime($ainv['maturity_date'])); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../config/footer.php'; ?>
