<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: login.php');
    exit();
}

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

$database = new Database();
$conn = $database->getConnection();

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Check if user exists, if not redirect to login
if (!$user) {
    session_destroy();
    header('Location: login.php');
    exit();
}

// Get user's virtual cards
$stmt = $conn->prepare("SELECT * FROM virtual_cards WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$virtual_cards = $stmt->fetchAll();

// Handle card actions
$card_message = '';
$card_error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'request_card':
                // Generate card details
                $card_number = '4' . str_pad(mt_rand(100000000000000, 999999999999999), 15, '0', STR_PAD_LEFT);
                $cvv = str_pad(mt_rand(100, 999), 3, '0', STR_PAD_LEFT);
                $expiry_month = str_pad(mt_rand(1, 12), 2, '0', STR_PAD_LEFT);
                $expiry_year = date('Y') + mt_rand(1, 5);
                $expiry_date = $expiry_month . '/' . $expiry_year;
                
                try {
                    $stmt = $conn->prepare("INSERT INTO virtual_cards (
                        user_id, card_number, card_type, expiry_date, cvv, 
                        daily_limit, status
                    ) VALUES (?, ?, 'Visa', ?, ?, 1000.00, 'Active')");
                    
                    $stmt->execute([$user_id, $card_number, $expiry_date, $cvv]);
                    
                    $card_message = "Virtual card created successfully!";
                    
                    // Refresh cards list
                    $stmt = $conn->prepare("SELECT * FROM virtual_cards WHERE user_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$user_id]);
                    $virtual_cards = $stmt->fetchAll();
                    
                } catch (Exception $e) {
                    $card_error = "Failed to create virtual card. Please try again.";
                }
                break;
                
            case 'block_card':
                $card_id = $_POST['card_id'];
                $stmt = $conn->prepare("UPDATE virtual_cards SET status = 'Blocked', updated_at = NOW() WHERE id = ? AND user_id = ?");
                $stmt->execute([$card_id, $user_id]);
                
                if ($stmt->rowCount() > 0) {
                    $card_message = "Card blocked successfully!";
                    // Refresh cards list
                    $stmt = $conn->prepare("SELECT * FROM virtual_cards WHERE user_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$user_id]);
                    $virtual_cards = $stmt->fetchAll();
                } else {
                    $card_error = "Failed to block card.";
                }
                break;
                
            case 'unblock_card':
                $card_id = $_POST['card_id'];
                $stmt = $conn->prepare("UPDATE virtual_cards SET status = 'Active', updated_at = NOW() WHERE id = ? AND user_id = ?");
                $stmt->execute([$card_id, $user_id]);
                
                if ($stmt->rowCount() > 0) {
                    $card_message = "Card unblocked successfully!";
                    // Refresh cards list
                    $stmt = $conn->prepare("SELECT * FROM virtual_cards WHERE user_id = ? ORDER BY created_at DESC");
                    $stmt->execute([$user_id]);
                    $virtual_cards = $stmt->fetchAll();
                } else {
                    $card_error = "Failed to unblock card.";
                }
                break;
        }
    }
}

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Virtual Cards - <?php echo htmlspecialchars($siteName); ?> Credit</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .cards-container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .page-header .header-content h1 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header .header-content h1 i {
            color: #667eea;
        }

        .page-header .header-content p {
            color: #5a6c7d;
            margin: 0;
            font-size: 1.1rem;
        }

        .cards-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .overview-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
            text-align: center;
        }

        .overview-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            color: white;
            font-size: 1.5rem;
        }

        .overview-content h3 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .overview-number {
            color: #667eea;
            font-size: 1.8rem;
            font-weight: 700;
            margin: 0;
        }

        .cards-section {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .cards-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f8f9fa;
        }

        .cards-header h2 {
            color: #2c3e50;
            margin: 0;
            font-size: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .cards-header h2 i {
            color: #667eea;
        }

        .btn-request-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn-request-card:hover {
            transform: translateY(-2px);
        }

        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
            gap: 25px;
        }

        .card-item {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            padding: 25px;
            color: white;
            position: relative;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
        }

        .card-item::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            pointer-events: none;
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .card-type {
            font-size: 1.1rem;
            font-weight: 600;
            opacity: 0.9;
        }

        .card-status {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
        }

        .card-status.active {
            background: rgba(40, 167, 69, 0.2);
            color: #28a745;
            border: 1px solid rgba(40, 167, 69, 0.3);
        }

        .card-status.blocked {
            background: rgba(220, 53, 69, 0.2);
            color: #dc3545;
            border: 1px solid rgba(220, 53, 69, 0.3);
        }

        .card-number {
            font-size: 1.4rem;
            font-weight: 600;
            margin-bottom: 20px;
            letter-spacing: 2px;
            font-family: 'Courier New', monospace;
        }

        .card-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 25px;
        }

        .card-detail {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .card-detail-label {
            font-size: 0.85rem;
            opacity: 0.8;
            font-weight: 500;
        }

        .card-detail-value {
            font-size: 1rem;
            font-weight: 600;
        }

        .card-actions {
            display: flex;
            gap: 10px;
        }

        .btn-card-action {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            background: rgba(255,255,255,0.1);
            color: white;
            font-size: 0.9rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .btn-card-action:hover {
            background: rgba(255,255,255,0.2);
            border-color: rgba(255,255,255,0.5);
        }

        .btn-card-action.danger:hover {
            background: rgba(220, 53, 69, 0.3);
            border-color: #dc3545;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: #dee2e6;
        }

        .empty-state h3 {
            font-size: 1.3rem;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .empty-state p {
            font-size: 1rem;
            margin: 0 0 20px 0;
        }

        /* Mobile responsive */
        @media (max-width: 768px) {
            .cards-overview {
                grid-template-columns: 1fr;
            }
            
            .cards-grid {
                grid-template-columns: 1fr;
            }
            
            .card-details {
                grid-template-columns: 1fr;
                gap: 10px;
            }
            
            .card-actions {
                flex-direction: column;
            }
            
            .card-number {
                font-size: 1.2rem;
                letter-spacing: 1px;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
            <div class="user-profile-sidebar">
                <div class="user-avatar-sidebar">
                    <?php if ($user['profile_photo']): ?>
                        <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                    <?php else: ?>
                        <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn-profile">
                        <i class="fas fa-user"></i> Profile
                    </a>
                    <a href="logout.php" class="btn-logout">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>Main Menu</h3>
                    <ul>
                        <li><a href="dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
                        <li><a href="transactions.php"><i class="fas fa-exchange-alt"></i> Transactions</a></li>
                        <li><a href="transfer.php"><i class="fas fa-paper-plane"></i> Transfer Funds</a></li>
                        <li><a href="cards.php" class="active"><i class="fas fa-credit-card"></i> Cards</a></li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>Services</h3>
                    <ul>
                        <li><a href="loan-request.php"><i class="fas fa-hand-holding-usd"></i> Loan Request</a></li>
                        <li><a href="loan-history.php"><i class="fas fa-history"></i> Loan History</a></li>
                        <li><a href="irs-refund.php"><i class="fas fa-file-invoice-dollar"></i> IRS Refund</a></li>
                        <li><a href="apply-card.php"><i class="fas fa-id-card"></i> Apply for Card</a></li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="support-info">
                    <h4>Need Help?</h4>
                    <p>Contact our 24/7 support team</p>
                    <a href="mailto:support@trustbeamcredit.com" class="support-link">
                        <i class="fas fa-envelope"></i> support@trustbeamcredit.com
                    </a>
                </div>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="dashboard-main">
            <div class="cards-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-credit-card"></i> Virtual Cards</h1>
                        <p>Manage your virtual cards for secure online transactions</p>
                    </div>
                </div>

                <!-- Messages -->
                <?php if ($card_message): ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        <?php echo htmlspecialchars($card_message); ?>
                    </div>
                <?php endif; ?>

                <?php if ($card_error): ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo htmlspecialchars($card_error); ?>
                    </div>
                <?php endif; ?>

                <!-- Cards Overview -->
                <div class="cards-overview">
                    <div class="overview-card">
                        <div class="overview-icon">
                            <i class="fas fa-credit-card"></i>
                        </div>
                        <div class="overview-content">
                            <h3>Total Cards</h3>
                            <div class="overview-number"><?php echo count($virtual_cards); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="overview-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="overview-content">
                            <h3>Active Cards</h3>
                            <div class="overview-number"><?php echo count(array_filter($virtual_cards, function($card) { return $card['status'] === 'Active'; })); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="overview-icon">
                            <i class="fas fa-ban"></i>
                        </div>
                        <div class="overview-content">
                            <h3>Blocked Cards</h3>
                            <div class="overview-number"><?php echo count(array_filter($virtual_cards, function($card) { return $card['status'] === 'Blocked'; })); ?></div>
                        </div>
                    </div>
                </div>

                <!-- Cards Section -->
                <div class="cards-section">
                    <div class="cards-header">
                        <h2><i class="fas fa-list"></i> Your Cards</h2>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="request_card">
                            <button type="submit" class="btn-request-card">
                                <i class="fas fa-plus"></i> Request New Card
                            </button>
                        </form>
                    </div>

                    <?php if (empty($virtual_cards)): ?>
                        <div class="empty-state">
                            <i class="fas fa-credit-card"></i>
                            <h3>No Cards Available</h3>
                            <p>You don't have any virtual cards yet. Request your first card to get started.</p>
                        </div>
                    <?php else: ?>
                        <div class="cards-grid">
                            <?php foreach ($virtual_cards as $card): ?>
                                <div class="card-item">
                                    <div class="card-header">
                                        <div class="card-type"><?php echo htmlspecialchars($card['card_type']); ?></div>
                                        <div class="card-status <?php echo strtolower($card['status']); ?>">
                                            <?php echo htmlspecialchars($card['status']); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="card-number">
                                        <?php echo substr($card['card_number'], 0, 4) . ' ' . substr($card['card_number'], 4, 4) . ' ' . substr($card['card_number'], 8, 4) . ' ' . substr($card['card_number'], 12, 4); ?>
                                    </div>
                                    
                                    <div class="card-details">
                                        <div class="card-detail">
                                            <span class="card-detail-label">Expiry Date</span>
                                            <span class="card-detail-value"><?php echo htmlspecialchars($card['expiry_date']); ?></span>
                                        </div>
                                        <div class="card-detail">
                                            <span class="card-detail-label">CVV</span>
                                            <span class="card-detail-value"><?php echo htmlspecialchars($card['cvv']); ?></span>
                                        </div>
                                        <div class="card-detail">
                                            <span class="card-detail-label">Daily Limit</span>
                                            <span class="card-detail-value"><?php echo formatCurrency($card['daily_limit'], $_SESSION['currency'] ?? '$'); ?></span>
                                        </div>
                                        <div class="card-detail">
                                            <span class="card-detail-label">Created</span>
                                            <span class="card-detail-value"><?php echo date('M d, Y', strtotime($card['created_at'])); ?></span>
                                        </div>
                                    </div>
                                    
                                    <div class="card-actions">
                                        <?php if ($card['status'] === 'Active'): ?>
                                            <form method="POST" style="flex: 1;">
                                                <input type="hidden" name="action" value="block_card">
                                                <input type="hidden" name="card_id" value="<?php echo $card['id']; ?>">
                                                <button type="submit" class="btn-card-action danger">
                                                    <i class="fas fa-ban"></i> Block
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <form method="POST" style="flex: 1;">
                                                <input type="hidden" name="action" value="unblock_card">
                                                <input type="hidden" name="card_id" value="<?php echo $card['id']; ?>">
                                                <button type="submit" class="btn-card-action">
                                                    <i class="fas fa-check"></i> Unblock
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile menu toggle
        document.addEventListener('DOMContentLoaded', function() {
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');
            const sidebar = document.querySelector('.dashboard-sidebar');
            const overlay = document.getElementById('sidebarOverlay');

            mobileMenuToggle.addEventListener('click', function() {
                sidebar.classList.toggle('active');
                overlay.classList.toggle('active');
            });

            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            });
        });
    </script>
    <script src="assets/js/logout-confirmation.js"></script>
</body>
</html>