<?php
require 'element/connection.php';
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Rate limiting configuration
$rate_limit = [
    'max_requests' => 3, // Maximum requests per hour
    'time_window' => 3600 // 1 hour in seconds
];

// Get user ID from session with validation
$my_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
if ($my_id === 0) {
    header('Location: login.php');
    exit();
}

// Fetch user details with prepared statement
$user_query = mysqli_prepare($conn, "SELECT * FROM users WHERE user_id = ?");
mysqli_stmt_bind_param($user_query, "i", $my_id);
mysqli_stmt_execute($user_query);
$user_result = mysqli_stmt_get_result($user_query);
$user_data = mysqli_fetch_assoc($user_result);

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

// Package definitions
$packages = [
    1 => ['name' => 'Basic Package', 'price' => 2500, 'color' => '#667eea'],
    2 => ['name' => 'Premium Package', 'price' => 3500, 'color' => '#764ba2']
];

// Check for pending request
function hasPendingRequest($conn, $user_id) {
    $check_query = mysqli_prepare($conn, "SELECT id FROM pin_request WHERE user_id = ? AND payment_status = 0");
    mysqli_stmt_bind_param($check_query, "i", $user_id);
    mysqli_stmt_execute($check_query);
    mysqli_stmt_store_result($check_query);
    $pending_count = mysqli_stmt_num_rows($check_query);
    mysqli_stmt_close($check_query);
    return $pending_count > 0;
}

// Check rate limit
function isRateLimited($conn, $user_id, $limit, $window) {
    $time_threshold = date('Y-m-d H:i:s', time() - $window);
    $check_query = mysqli_prepare($conn, "SELECT COUNT(*) as request_count FROM pin_request WHERE user_id = ? AND created_at > ?");
    mysqli_stmt_bind_param($check_query, "is", $user_id, $time_threshold);
    mysqli_stmt_execute($check_query);
    $result = mysqli_stmt_get_result($check_query);
    $row = mysqli_fetch_assoc($result);
    mysqli_stmt_close($check_query);
    return $row['request_count'] >= $limit;
}

// Handle PIN request submission with enhanced security
if (isset($_POST['submit_request']) && isset($_POST['csrf_token'])) {
    
    // Validate CSRF token
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $_SESSION['error_message'] = "Invalid security token. Please try again.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
    // Check if form was already submitted (session flag)
    elseif (isset($_SESSION['last_request_time']) && (time() - $_SESSION['last_request_time'] < 5)) {
        $_SESSION['error_message'] = "Please wait a few seconds before submitting again.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
    // Check for pending request
    elseif (hasPendingRequest($conn, $my_id)) {
        $_SESSION['error_message'] = "You already have a pending request. Please wait for it to be processed.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
    // Check rate limit
    elseif (isRateLimited($conn, $my_id, $rate_limit['max_requests'], $rate_limit['time_window'])) {
        $_SESSION['error_message'] = "You have exceeded the maximum number of requests per hour. Please try again later.";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
    else {
        // Validate and sanitize inputs
        $name = mysqli_real_escape_string($conn, trim($_POST['name']));
        $package_id = filter_var($_POST['package_id'], FILTER_VALIDATE_INT);
        $pin_quantity = filter_var($_POST['pin_quantity'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1, 'max_range' => 100]]);
        $message = mysqli_real_escape_string($conn, trim($_POST['message'] ?? ''));
        
        // Validate package exists
        if (!isset($packages[$package_id])) {
            $_SESSION['error_message'] = "Invalid package selected.";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        }
        elseif (!$pin_quantity) {
            $_SESSION['error_message'] = "Invalid quantity specified.";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit();
        }
        else {
            $package_name = $packages[$package_id]['name'];
            $package_price = $packages[$package_id]['price'];
            $total_amount = $package_price * $pin_quantity;
            
            // Handle file upload with enhanced security
            $target_dir = "uploads/payment_screenshots/";
            if (!file_exists($target_dir)) {
                mkdir($target_dir, 0755, true);
            }
            
            // Create .htaccess to protect uploads directory
            if (!file_exists($target_dir . '.htaccess')) {
                $htaccess_content = "Options -Indexes\n<FilesMatch \"\.(php|php3|php4|php5|phtml|pl|py|jsp|asp|htm|shtml|sh|cgi)\">\nOrder Deny,Allow\nDeny from all\n</FilesMatch>";
                file_put_contents($target_dir . '.htaccess', $htaccess_content);
            }
            
            $screenshot = '';
            $upload_error = '';
            
            if (isset($_FILES['payment_screenshot']) && $_FILES['payment_screenshot']['error'] == UPLOAD_ERR_OK) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime_type = finfo_file($finfo, $_FILES['payment_screenshot']['tmp_name']);
                finfo_close($finfo);
                
                $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
                $file_size = $_FILES['payment_screenshot']['size'];
                
                // Validate file type using both extension and MIME
                $extension = strtolower(pathinfo($_FILES['payment_screenshot']['name'], PATHINFO_EXTENSION));
                $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
                
                if (!in_array($mime_type, $allowed_types) || !in_array($extension, $allowed_ext)) {
                    $upload_error = "Only JPG, PNG & GIF files are allowed!";
                } elseif ($file_size > 5 * 1024 * 1024) { // 5MB max
                    $upload_error = "File size must be less than 5MB!";
                } else {
                    // Generate secure filename
                    $new_filename = bin2hex(random_bytes(16)) . '.' . $extension;
                    $screenshot = $new_filename;
                    $target_file = $target_dir . $new_filename;
                    
                    if (!move_uploaded_file($_FILES['payment_screenshot']['tmp_name'], $target_file)) {
                        $upload_error = "Failed to upload file!";
                    }
                }
            } else {
                $upload_error = "Please upload payment screenshot!";
            }
            
            if (empty($upload_error)) {
                // Check if payment_status column exists
                $check_column = mysqli_query($conn, "SHOW COLUMNS FROM pin_request LIKE 'payment_status'");
                if (mysqli_num_rows($check_column) == 0) {
                    mysqli_query($conn, "ALTER TABLE pin_request ADD COLUMN payment_status TINYINT DEFAULT 0 AFTER total_amount");
                }
                
                // Check for ip_address column
                $check_ip = mysqli_query($conn, "SHOW COLUMNS FROM pin_request LIKE 'ip_address'");
                if (mysqli_num_rows($check_ip) == 0) {
                    mysqli_query($conn, "ALTER TABLE pin_request ADD COLUMN ip_address VARCHAR(45) AFTER message");
                }
                
                // Check for user_agent column
                $check_ua = mysqli_query($conn, "SHOW COLUMNS FROM pin_request LIKE 'user_agent'");
                if (mysqli_num_rows($check_ua) == 0) {
                    mysqli_query($conn, "ALTER TABLE pin_request ADD COLUMN user_agent TEXT AFTER ip_address");
                }
                
                // Use prepared statement for insert
                $insert_query = "INSERT INTO pin_request 
                                (user_id, name, package_id, package_name, package_price, pin_quantity, total_amount, payment_status, payment_screenshot, message, ip_address, user_agent, created_at) 
                                VALUES 
                                (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW())";
                
                $stmt = mysqli_prepare($conn, $insert_query);
                $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
                $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
                
                mysqli_stmt_bind_param($stmt, "isissdsssss", 
                    $my_id, $name, $package_id, $package_name, $package_price, 
                    $pin_quantity, $total_amount, $screenshot, $message, $ip_address, $user_agent
                );
                
                if (mysqli_stmt_execute($stmt)) {
                    // Set session flag to prevent double submission
                    $_SESSION['last_request_time'] = time();
                    $_SESSION['last_request_id'] = mysqli_insert_id($conn);
                    
                    // Regenerate CSRF token to prevent reuse
                    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                    
                    // Set success message in session
                    $_SESSION['success_message'] = "PIN request submitted successfully! You will receive your PINs after payment verification.";
                    
                    // Redirect to prevent form resubmission
                    header("Location: " . $_SERVER['PHP_SELF']);
                    exit();
                } else {
                    $_SESSION['error_message'] = "Error submitting request: " . mysqli_error($conn);
                    // Delete uploaded file if database insert fails
                    if (!empty($screenshot) && file_exists($target_dir . $screenshot)) {
                        unlink($target_dir . $screenshot);
                    }
                    header("Location: " . $_SERVER['PHP_SELF']);
                    exit();
                }
                mysqli_stmt_close($stmt);
            } else {
                $_SESSION['error_message'] = $upload_error;
                header("Location: " . $_SERVER['PHP_SELF']);
                exit();
            }
        }
    }
}

// Get messages from session
$success_message = $_SESSION['success_message'] ?? null;
$error_message = $_SESSION['error_message'] ?? null;

// Clear session messages
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);

// Fetch user's PIN requests with prepared statement
$requests_query = mysqli_prepare($conn, "SELECT * FROM pin_request WHERE user_id = ? ORDER BY id DESC LIMIT 50");
mysqli_stmt_bind_param($requests_query, "i", $my_id);
mysqli_stmt_execute($requests_query);
$requests_result = mysqli_stmt_get_result($requests_query);

// Check for pending request status
$has_pending = hasPendingRequest($conn, $my_id);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">
    <title><?php echo htmlspecialchars($user_data['name']); ?> || PIN Request</title>
    
    <!-- Favicons -->
    <link href="../img/logo/logo22222.png" rel="icon">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">

    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">
    <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.snow.css" rel="stylesheet">
    <link href="assets/vendor/quill/quill.bubble.css" rel="stylesheet">
    <link href="assets/vendor/remixicon/remixicon.css" rel="stylesheet">
    <link href="assets/vendor/simple-datatables/style.css" rel="stylesheet">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --success-gradient: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            --warning-gradient: linear-gradient(135deg, #fad0c4 0%, #ffd1ff 100%);
            --danger-gradient: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            --primary-color: #667eea;
            --secondary-color: #764ba2;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
        }

        /* Modern Card Design */
        .modern-card {
            background: white;
            border-radius: 24px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            border: none;
            transition: all 0.3s ease;
            overflow: hidden;
            margin-bottom: 25px;
        }

        .modern-card:hover {
            box-shadow: 0 30px 60px rgba(102, 126, 234, 0.15);
        }

        .card-header-modern {
            padding: 25px 30px;
            background: var(--primary-gradient);
            color: white;
            border-bottom: none;
        }

        .card-header-modern h5 {
            margin: 0;
            font-weight: 700;
            font-size: 1.3rem;
            letter-spacing: 0.5px;
        }

        /* Package Cards */
        .package-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .package-card {
            background: white;
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            cursor: pointer;
            border: 2px solid transparent;
            position: relative;
            overflow: hidden;
        }

        .package-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.15);
        }

        .package-card.selected {
            border-color: #667eea;
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
        }

        .package-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 15px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
            background: #667eea;
            color: white;
        }

        .package-icon {
            width: 70px;
            height: 70px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            font-size: 30px;
            color: white;
        }

        .package-name {
            font-size: 1.3rem;
            font-weight: 700;
            margin-bottom: 10px;
        }

        .package-price {
            font-size: 2rem;
            font-weight: 800;
            margin-bottom: 15px;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .package-price small {
            font-size: 0.9rem;
            font-weight: 400;
            color: #64748b;
        }

        .package-features {
            list-style: none;
            padding: 0;
            margin: 20px 0;
        }

        .package-features li {
            padding: 8px 0;
            color: #475569;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .package-features i {
            color: #10b981;
        }

        /* Quantity Selector */
        .quantity-selector {
            display: flex;
            align-items: center;
            gap: 15px;
            background: #f8fafc;
            padding: 10px;
            border-radius: 50px;
            margin: 20px 0;
        }

        .quantity-btn {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            border: none;
            background: white;
            color: #667eea;
            font-size: 1.3rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }

        .quantity-btn:hover {
            background: var(--primary-gradient);
            color: white;
            transform: scale(1.1);
        }

        .quantity-input {
            width: 80px;
            text-align: center;
            border: none;
            background: transparent;
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }

        .quantity-input:focus {
            outline: none;
        }

        /* Total Amount */
        .total-amount-box {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border-radius: 20px;
            padding: 20px;
            margin: 20px 0;
            text-align: center;
        }

        .total-label {
            color: #64748b;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .total-value {
            font-size: 3rem;
            font-weight: 800;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* Request Button */
        .request-btn {
            width: 100%;
            padding: 18px;
            border: none;
            border-radius: 50px;
            background: var(--primary-gradient);
            color: white;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
            margin-top: 20px;
        }

        .request-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 15px 30px rgba(102, 126, 234, 0.4);
        }

        .request-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        /* Modal Styles */
        .payment-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .payment-modal.show {
            opacity: 1;
            visibility: visible;
        }

        .modal-content-modern {
            background: white;
            border-radius: 30px;
            max-width: 500px;
            width: 90%;
            padding: 40px;
            position: relative;
            transform: scale(0.9);
            transition: all 0.3s ease;
            max-height: 90vh;
            overflow-y: auto;
        }

        .payment-modal.show .modal-content-modern {
            transform: scale(1);
        }

        .modal-close {
            position: absolute;
            top: 20px;
            right: 20px;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #94a3b8;
        }

        .timer-circle {
            width: 120px;
            height: 120px;
            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: 2.5rem;
            font-weight: 700;
            box-shadow: 0 20px 40px rgba(102, 126, 234, 0.3);
        }

        .payment-details {
            background: #f8fafc;
            border-radius: 20px;
            padding: 20px;
            margin: 20px 0;
        }

        .payment-row {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            border-bottom: 1px solid #e2e8f0;
        }

        .payment-row:last-child {
            border-bottom: none;
        }

        .upload-area {
            border: 2px dashed #cbd5e1;
            border-radius: 16px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 20px 0;
        }

        .upload-area:hover {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }

        .upload-area i {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 15px;
        }

        .file-preview {
            max-width: 100%;
            max-height: 200px;
            border-radius: 12px;
            margin-top: 15px;
        }

        /* Table Styles */
        .table-container {
            background: white;
            border-radius: 24px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.05);
            overflow-x: auto;
        }

        .status-badge {
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-approved {
            background: #d4edda;
            color: #155724;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        /* Animations */
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-slide {
            animation: slideIn 0.5s ease forwards;
        }

        @keyframes countdown {
            0% { transform: scale(1); }
            50% { transform: scale(1.1); }
            100% { transform: scale(1); }
        }

        .countdown-animation {
            animation: countdown 1s infinite;
        }

        .form-control-modern {
            width: 100%;
            padding: 14px 20px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control-modern:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
            outline: none;
        }

        .custom-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .custom-table thead th {
            padding: 15px 20px;
            font-size: 0.9rem;
            font-weight: 700;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border: none;
            background: #f8fafc;
        }

        .custom-table tbody tr {
            background: white;
            border-radius: 16px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.03);
            transition: all 0.3s ease;
        }

        .custom-table tbody td {
            padding: 20px;
            vertical-align: middle;
            border: none;
        }

        .badge-custom {
            padding: 6px 15px;
            border-radius: 30px;
            font-size: 0.85rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
    </style>
</head>

<body>

    <!-- Header -->
    <?php include 'element/header.php'; ?>
    
    <!-- Sidebar -->
    <?php include 'element/sidebar.php'; ?>

    <main id="main" class="main">
        <div class="pagetitle">
            <h1>PIN Request</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">PIN Request</li>
                </ol>
            </nav>
        </div>

        <!-- Alert Messages -->
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show animate-slide" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo htmlspecialchars($success_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show animate-slide" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- PIN Request Form -->
            <div class="col-xl-5 col-lg-5 col-md-12 col-12">
                <div class="modern-card">
                    <div class="card-header-modern">
                        <h5><i class="fas fa-ticket-alt me-2"></i> Request New E-PINs</h5>
                    </div>
                    <div class="card-body p-4">
                        <!-- Package Selection -->
                        <label class="form-label fw-bold mb-3">Select Package</label>
                        <div class="package-grid">
                            <?php foreach ($packages as $id => $package): ?>
                            <div class="package-card" onclick="selectPackage(<?php echo $id; ?>)" id="package-<?php echo $id; ?>">
                                <div class="package-badge">Popular</div>
                                <div class="package-icon" style="background: <?php echo $package['color']; ?>">
                                    <i class="fas <?php echo $id == 1 ? 'fa-box' : 'fa-crown'; ?>"></i>
                                </div>
                                <h3 class="package-name"><?php echo $package['name']; ?></h3>
                                <div class="package-price">
                                    ₹<?php echo number_format($package['price']); ?>
                                    <small>/PIN</small>
                                </div>
                                <ul class="package-features">
                                    <li><i class="fas fa-check-circle"></i> Instant PIN Generation</li>
                                    <li><i class="fas fa-check-circle"></i> Lifetime Validity</li>
                                    <li><i class="fas fa-check-circle"></i> Transferable</li>
                                </ul>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <!-- Quantity Selector -->
                        <label class="form-label fw-bold mb-3">Number of PINs</label>
                        <div class="quantity-selector">
                            <button type="button" class="quantity-btn" onclick="updateQuantity(-1)">-</button>
                            <input type="number" class="quantity-input" id="pinQuantity" value="1" min="1" max="100" readonly>
                            <button type="button" class="quantity-btn" onclick="updateQuantity(1)">+</button>
                        </div>

                        <!-- Total Amount -->
                        <div class="total-amount-box">
                            <div class="total-label">Total Amount Payable</div>
                            <div class="total-value" id="totalAmount">₹0</div>
                        </div>

                        <!-- Request Button -->
                        <button class="request-btn" onclick="openPaymentModal()" <?php echo $has_pending ? 'disabled' : ''; ?>>
                            <i class="fas fa-paper-plane me-2"></i> Proceed to Request
                        </button>
                        <?php if ($has_pending): ?>
                        <p class="text-warning text-center mt-2">
                            <i class="fas fa-exclamation-triangle"></i> You have a pending request
                        </p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Request History -->
            <div class="col-xl-7 col-lg-7 col-md-12 col-12">
                <div class="modern-card">
                    <div class="card-header-modern">
                        <h5><i class="fas fa-history me-2"></i> Request History</h5>
                    </div>
                    <div class="card-body p-4">
                        <div class="table-container">
                            <table class="table custom-table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Package</th>
                                        <th>Quantity</th>
                                        <th>Total Amount</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($requests_result && mysqli_num_rows($requests_result) > 0): ?>
                                        <?php while ($request = mysqli_fetch_assoc($requests_result)): ?>
                                            <?php 
                                            $package_color = isset($packages[$request['package_id']]) ? $packages[$request['package_id']]['color'] : '#667eea';
                                            $payment_status = isset($request['payment_status']) ? intval($request['payment_status']) : 0;
                                            ?>
                                        <tr>
                                            <td>#<?php echo htmlspecialchars($request['id']); ?></td>
                                            <td>
                                                <span class="badge-custom" style="background: <?php echo $package_color; ?>20; color: <?php echo $package_color; ?>">
                                                    <?php echo htmlspecialchars($request['package_name']); ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($request['pin_quantity']); ?></td>
                                            <td><strong>₹<?php echo number_format($request['total_amount'], 2); ?></strong></td>
                                            <td><?php echo date('d M Y', strtotime($request['created_at'])); ?></td>
                                            <td>
                                                <?php if ($payment_status == 0): ?>
                                                    <span class="status-badge status-pending">
                                                        <i class="fas fa-clock"></i> Pending
                                                    </span>
                                                <?php elseif ($payment_status == 1): ?>
                                                    <span class="status-badge status-approved">
                                                        <i class="fas fa-check-circle"></i> Approved
                                                    </span>
                                                <?php else: ?>
                                                    <span class="status-badge status-rejected">
                                                        <i class="fas fa-times-circle"></i> Rejected
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center py-4">
                                                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                                                <p class="text-muted">No requests found</p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- Payment Modal -->
    <div class="payment-modal" id="paymentModal">
        <div class="modal-content-modern">
            <button class="modal-close" onclick="closePaymentModal()">&times;</button>
            
            <h3 class="text-center mb-4">Complete Your Payment</h3>
            
            <!-- Timer -->
            <div class="timer-circle" id="timer">05:00</div>
            <p class="text-center text-muted mb-4">Complete payment within 5 minutes</p>
            
            <!-- Payment Details -->
            <div class="payment-details">
                <div class="payment-row">
                    <span>Package:</span>
                    <span class="fw-bold" id="modalPackage">Basic Package</span>
                </div>
                <div class="payment-row">
                    <span>Quantity:</span>
                    <span class="fw-bold" id="modalQuantity">1 PIN</span>
                </div>
                <div class="payment-row">
                    <span>Amount:</span>
                    <span class="fw-bold text-primary" id="modalAmount">₹2,500</span>
                </div>
            </div>
            
            <!-- Upload Area -->
            <form method="POST" enctype="multipart/form-data" id="paymentForm">
                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                <input type="hidden" name="user_id" value="<?php echo $my_id; ?>">
                <input type="hidden" name="name" value="<?php echo htmlspecialchars($user_data['name']); ?>">
                <input type="hidden" name="package_id" id="hiddenPackageId" value="1">
                <input type="hidden" name="pin_quantity" id="hiddenQuantity" value="1">
                <input type="hidden" name="message" id="hiddenMessage" value="">
                
                <label class="form-label fw-bold">Upload Payment Screenshot</label>
                <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p class="mb-2">Click to upload or drag and drop</p>
                    <p class="text-muted small">PNG, JPG, GIF up to 5MB</p>
                    <input type="file" id="fileInput" name="payment_screenshot" accept="image/jpeg,image/png,image/gif" style="display: none;" required>
                    <img id="filePreview" class="file-preview" style="display: none;">
                </div>
                
                <!-- Message (Optional) -->
                <textarea class="form-control-modern mt-3" name="message" placeholder="Add any notes (optional)" rows="2" maxlength="500"></textarea>
                
                <!-- Submit Button -->
                <button type="submit" name="submit_request" class="request-btn mt-4" 
                        <?php echo $has_pending ? 'disabled' : ''; ?>>
                    <i class="fas fa-check-circle me-2"></i> Submit Request
                </button>
            </form>
        </div>
    </div>

    <!-- Footer -->
    <footer id="footer" class="footer">
        <div class="copyright">
            &copy; Copyright <strong><span>Healthy Life Mission</span></strong>. All Rights Reserved
        </div>
    </footer>

    <a href="#" class="back-to-top d-flex align-items-center justify-content-center">
        <i class="bi bi-arrow-up-short"></i>
    </a>

    <!-- Vendor JS Files -->
    <script src="assets/vendor/jquery/jquery-3.6.0.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/js/main.js"></script>

    <!-- Main JavaScript -->
    <script>
    // Global variables
    let selectedPackage = 1;
    let pinQuantity = 1;
    let timerInterval = null;
    let timeLeft = 300;
    
    // Package data
    const packagePrices = {
        1: 2500,
        2: 3500
    };
    
    const packageNames = {
        1: 'Basic Package',
        2: 'Premium Package'
    };
    
    // Select package
    function selectPackage(packageId) {
        selectedPackage = packageId;
        
        document.querySelectorAll('.package-card').forEach(card => {
            card.classList.remove('selected');
        });
        
        const selectedCard = document.getElementById(`package-${packageId}`);
        if (selectedCard) {
            selectedCard.classList.add('selected');
        }
        
        updateTotal();
    }
    
    // Update quantity
    function updateQuantity(change) {
        const quantityInput = document.getElementById('pinQuantity');
        let newValue = parseInt(quantityInput.value) + change;
        
        if (newValue >= 1 && newValue <= 100) {
            pinQuantity = newValue;
            quantityInput.value = newValue;
            updateTotal();
        }
    }
    
    // Update total
    function updateTotal() {
        const total = packagePrices[selectedPackage] * pinQuantity;
        document.getElementById('totalAmount').textContent = '₹' + total.toLocaleString('en-IN');
    }
    
    // Open modal
    function openPaymentModal() {
        <?php if ($has_pending): ?>
        alert('You have a pending request. Please wait for it to be processed.');
        return;
        <?php endif; ?>
        
        document.getElementById('modalPackage').textContent = packageNames[selectedPackage];
        document.getElementById('modalQuantity').textContent = pinQuantity + ' PIN' + (pinQuantity > 1 ? 's' : '');
        document.getElementById('modalAmount').textContent = '₹' + (packagePrices[selectedPackage] * pinQuantity).toLocaleString('en-IN');
        document.getElementById('hiddenPackageId').value = selectedPackage;
        document.getElementById('hiddenQuantity').value = pinQuantity;
        
        resetTimer();
        document.getElementById('paymentModal').classList.add('show');
        document.body.style.overflow = 'hidden';
        startTimer();
    }
    
    // Close modal
    function closePaymentModal() {
        document.getElementById('paymentModal').classList.remove('show');
        document.body.style.overflow = 'auto';
        if (timerInterval) clearInterval(timerInterval);
    }
    
    // Timer functions
    function startTimer() {
        timeLeft = 300;
        updateTimerDisplay();
        if (timerInterval) clearInterval(timerInterval);
        
        timerInterval = setInterval(function() {
            timeLeft--;
            updateTimerDisplay();
            if (timeLeft <= 0) {
                clearInterval(timerInterval);
                closePaymentModal();
                alert('Payment time expired! Please try again.');
            }
        }, 1000);
    }
    
    function updateTimerDisplay() {
        const minutes = Math.floor(timeLeft / 60);
        const seconds = timeLeft % 60;
        const timerElement = document.getElementById('timer');
        timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        if (timeLeft <= 60) {
            timerElement.classList.add('countdown-animation');
            timerElement.style.background = 'linear-gradient(135deg, #f5576c 0%, #f093fb 100%)';
        }
    }
    
    function resetTimer() {
        if (timerInterval) clearInterval(timerInterval);
        timeLeft = 300;
        const timerElement = document.getElementById('timer');
        timerElement.classList.remove('countdown-animation');
        timerElement.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
        timerElement.textContent = '05:00';
    }
    
    // File upload preview
    document.getElementById('fileInput')?.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        if (file.size > 5 * 1024 * 1024) {
            alert('File size must be less than 5MB!');
            e.target.value = '';
            return;
        }
        
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (!validTypes.includes(file.type)) {
            alert('Only JPG, PNG & GIF files are allowed!');
            e.target.value = '';
            return;
        }
        
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('filePreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
            document.querySelector('.upload-area p').textContent = file.name;
        };
        reader.readAsDataURL(file);
    });
    
    // Close modal on outside click
    document.getElementById('paymentModal')?.addEventListener('click', function(e) {
        if (e.target === this) closePaymentModal();
    });
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        selectPackage(1);
    });
    </script>

</body>
</html>