<?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';

$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();

if (!$user) {
    header('Location: login.php');
    exit();
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $card_type = $_POST['card_type'];
    $daily_limit = $_POST['daily_limit'];
    
    // Validate inputs
    if (empty($card_type) || empty($daily_limit)) {
        $message = 'Please fill in all required fields.';
        $message_type = 'error';
    } elseif (!in_array($card_type, ['Visa', 'Mastercard', 'American Express'])) {
        $message = 'Invalid card type selected.';
        $message_type = 'error';
    } elseif (!is_numeric($daily_limit) || $daily_limit <= 0) {
        $message = 'Daily limit must be a positive number.';
        $message_type = 'error';
    } elseif ($daily_limit > 50000) {
        $message = 'Daily limit cannot exceed $50,000.';
        $message_type = 'error';
    } else {
        try {
            // Generate unique card number (simplified Luhn algorithm)
            $card_number = generateCardNumber($card_type);
            
            // Generate expiry date (3 years from now)
            $expiry_date = date('Y-m-d', strtotime('+3 years'));
            
            // Generate CVV
            $cvv = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
            
            // Insert new virtual card
            $stmt = $conn->prepare("INSERT INTO virtual_cards (user_id, card_number, card_type, expiry_date, cvv, daily_limit, status) VALUES (?, ?, ?, ?, ?, ?, 'Active')");
            
            if ($stmt->execute([$user_id, $card_number, $card_type, $expiry_date, $cvv, $daily_limit])) {
                $message = 'Virtual card application submitted successfully! Your card will be activated shortly.';
                $message_type = 'success';
            } else {
                $message = 'Failed to submit card application. Please try again.';
                $message_type = 'error';
            }
        } catch (Exception $e) {
            $message = 'An error occurred. Please try again.';
            $message_type = 'error';
        }
    }
}

// Function to generate card number
function generateCardNumber($card_type) {
    $prefixes = [
        'Visa' => '4',
        'Mastercard' => '5',
        'American Express' => '3'
    ];
    
    $prefix = $prefixes[$card_type] ?? '4';
    $length = ($card_type === 'American Express') ? 15 : 16;
    
    // Generate random number
    $number = $prefix;
    for ($i = 1; $i < $length - 1; $i++) {
        $number .= rand(0, 9);
    }
    
    // Add check digit using Luhn algorithm
    $check_digit = calculateLuhnCheckDigit($number);
    $number .= $check_digit;
    
    return $number;
}

// Function to calculate Luhn check digit
function calculateLuhnCheckDigit($number) {
    $sum = 0;
    $alternate = false;
    
    for ($i = strlen($number) - 1; $i >= 0; $i--) {
        $digit = intval($number[$i]);
        
        if ($alternate) {
            $digit *= 2;
            if ($digit > 9) {
                $digit = ($digit % 10) + 1;
            }
        }
        
        $sum += $digit;
        $alternate = !$alternate;
    }
    
    return (10 - ($sum % 10)) % 10;
}

// Get user's existing cards
$stmt = $conn->prepare("SELECT COUNT(*) as card_count FROM virtual_cards WHERE user_id = ?");
$stmt->execute([$user_id]);
$card_count = $stmt->fetch()['card_count'];

$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>Apply for Virtual Card - TrustBeam 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>
        .apply-card-container {
            max-width: 800px;
            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;
        }

        .application-form {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-section h3 i {
            color: #667eea;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }

        .form-group label .required {
            color: #dc3545;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
        }

        .form-group input:focus,
        .form-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .card-type-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }

        .card-type-option {
            border: 2px solid #e0e6ed;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }

        .card-type-option:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .card-type-option.selected {
            border-color: #667eea;
            background: #f8f9ff;
        }

        .card-type-option input[type="radio"] {
            display: none;
        }

        .card-type-option .card-icon {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .card-type-option .visa {
            color: #1a1f71;
        }

        .card-type-option .mastercard {
            color: #eb001b;
        }

        .card-type-option .amex {
            color: #006fcf;
        }

        .card-type-option .card-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .card-type-option .card-description {
            font-size: 0.85rem;
            color: #5a6c7d;
        }

        .daily-limit-info {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 10px;
            font-size: 0.9rem;
            color: #5a6c7d;
        }

        .daily-limit-info i {
            color: #667eea;
            margin-right: 8px;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e0e6ed;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .card-features {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .card-features h4 {
            color: #2c3e50;
            margin: 0 0 15px 0;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .features-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .feature-item {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.9rem;
            color: #5a6c7d;
        }

        .feature-item i {
            color: #28a745;
            font-size: 1rem;
        }

        @media (max-width: 768px) {
            .apply-card-container {
                padding: 0 20px;
            }
            
            .card-type-options {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .features-grid {
                grid-template-columns: 1fr;
            }
        }
    </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 number_format($user['balance'], 0); ?></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>
        
        <!-- Left 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">TrustBeam</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 btn-profile">Profile</a>
                    <a href="logout.php" class="btn btn-logout">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>
                                <span>Dashboard</span>
                            </a>
                        </li>
                        <li>
                            <a href="transactions.php">
                                <i class="fas fa-exchange-alt"></i>
                                <span>Transactions</span>
                            </a>
                        </li>
                        <li>
                            <a href="cards.php">
                                <i class="fas fa-credit-card"></i>
                                <span>Cards</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>TRANSFERS</h3>
                    <ul>
                        <li>
                            <a href="transfer.php">
                                <i class="fas fa-paper-plane"></i>
                                <span>Transfer Funds</span>
                            </a>
                        </li>
                        <li>
                            <a href="deposit.php">
                                <i class="fas fa-arrow-down"></i>
                                <span>Deposit</span>
                            </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>
                                <span>Loan Request</span>
                            </a>
                        </li>
                        <li>
                            <a href="irs-refund.php">
                                <i class="fas fa-file-invoice-dollar"></i>
                                <span>IRS Tax Refund</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>ACCOUNT</h3>
                    <ul>
                        <li>
                            <a href="account-info.php">
                                <i class="fas fa-user-circle"></i>
                                <span>Account Info</span>
                            </a>
                        </li>
                        <li>
                            <a href="loan-history.php">
                                <i class="fas fa-history"></i>
                                <span>Loan History</span>
                            </a>
                        </li>
                        <li>
                            <a href="settings.php">
                                <i class="fas fa-cog"></i>
                                <span>Settings</span>
                            </a>
                        </li>
                        <li>
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="secure-banking">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure Banking</span>
                </div>
                <div class="version">v1.2.0</div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="dashboard-main">
            <div class="apply-card-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-credit-card"></i> Apply for Virtual Card</h1>
                        <p>Get your virtual card instantly and start making secure online purchases</p>
                    </div>
                </div>

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

                <!-- Card Features -->
                <div class="card-features">
                    <h4><i class="fas fa-star"></i> Virtual Card Benefits</h4>
                    <div class="features-grid">
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>Instant activation</span>
                        </div>
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>Secure online payments</span>
                        </div>
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>Daily spending limits</span>
                        </div>
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>Real-time transaction monitoring</span>
                        </div>
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>24/7 customer support</span>
                        </div>
                        <div class="feature-item">
                            <i class="fas fa-check"></i>
                            <span>No annual fees</span>
                        </div>
                    </div>
                </div>

                <!-- Application Form -->
                <form method="POST" class="application-form">
                    <div class="form-section">
                        <h3><i class="fas fa-credit-card"></i> Card Type Selection</h3>
                        <div class="form-group">
                            <label>Select Card Type <span class="required">*</span></label>
                            <div class="card-type-options">
                                <label class="card-type-option" for="visa">
                                    <input type="radio" id="visa" name="card_type" value="Visa" required>
                                    <div class="card-icon visa">
                                        <i class="fab fa-cc-visa"></i>
                                    </div>
                                    <div class="card-name">Visa</div>
                                    <div class="card-description">Accepted worldwide</div>
                                </label>
                                
                                <label class="card-type-option" for="mastercard">
                                    <input type="radio" id="mastercard" name="card_type" value="Mastercard" required>
                                    <div class="card-icon mastercard">
                                        <i class="fab fa-cc-mastercard"></i>
                                    </div>
                                    <div class="card-name">Mastercard</div>
                                    <div class="card-description">Global acceptance</div>
                                </label>
                                
                                <label class="card-type-option" for="amex">
                                    <input type="radio" id="amex" name="card_type" value="American Express" required>
                                    <div class="card-icon amex">
                                        <i class="fab fa-cc-amex"></i>
                                    </div>
                                    <div class="card-name">American Express</div>
                                    <div class="card-description">Premium benefits</div>
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-section">
                        <h3><i class="fas fa-dollar-sign"></i> Spending Limits</h3>
                        <div class="form-group">
                            <label for="daily_limit">Daily Spending Limit <span class="required">*</span></label>
                            <input type="number" id="daily_limit" name="daily_limit" min="100" max="50000" step="100" value="1000" required>
                            <div class="daily-limit-info">
                                <i class="fas fa-info-circle"></i>
                                Set your daily spending limit between $100 and $50,000. You can change this limit anytime after card activation.
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <a href="cards.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i>
                            Cancel
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i>
                            Apply for Card
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <script src="assets/js/main.js"></script>
    <script>
        // Card type selection handling
        document.addEventListener('DOMContentLoaded', function() {
            const cardOptions = document.querySelectorAll('.card-type-option');
            
            cardOptions.forEach(option => {
                option.addEventListener('click', function() {
                    // Remove selected class from all options
                    cardOptions.forEach(opt => opt.classList.remove('selected'));
                    
                    // Add selected class to clicked option
                    this.classList.add('selected');
                    
                    // Check the radio button
                    this.querySelector('input[type="radio"]').checked = true;
                });
            });
            
            // Set default selection
            if (document.querySelector('input[name="card_type"]:checked')) {
                document.querySelector('input[name="card_type"]:checked').closest('.card-type-option').classList.add('selected');
            }
        });
    </script>
</body>
</html>

