<?php
require 'element/connection.php';
require 'element/header.php';
require 'element/sidebar.php';

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

// Get user ID from session
$my_id = $_SESSION['user_id'];

// Fetch user details
$user_query = mysqli_query($conn, "SELECT * FROM users WHERE user_id = '$my_id'");
if (!$user_query) {
    error_log("User query error: " . mysqli_error($conn));
    $user_data = ['name' => 'User'];
} else {
    $user_data = mysqli_fetch_assoc($user_query);
}

// Initialize variables
$available_pins = [];
$pins_count = 0;
$first_available_pin = '';

// Fetch available PINs - Using pin_value column
$pins_query = mysqli_query($conn, "SELECT * FROM pin WHERE allcote_user = '$my_id' AND status = '0'");

if (!$pins_query) {
    error_log("PIN query error: " . mysqli_error($conn));
} else {
    while($pin = mysqli_fetch_assoc($pins_query)) {
        $available_pins[] = $pin;
    }
    $pins_count = count($available_pins);
    
    // Get the first available PIN - Using pin_value column
    if ($pins_count > 0) {
        $first_available_pin = $available_pins[0]['pin_value'];
    }
}

// Check for messages
$success_msg = isset($_GET['success']) ? $_GET['success'] : '';
$error_msg = isset($_GET['error']) ? $_GET['error'] : '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title><?php echo isset($user_data['name']) ? htmlspecialchars($user_data['name']) : 'User'; ?> || Member Registration</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/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">

    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

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

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --primary-color: #667eea;
        }

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

        .registration-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .form-card {
            background: white;
            border-radius: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 30px;
        }

        .form-header {
            background: var(--primary-gradient);
            color: white;
            padding: 25px 30px;
        }

        .form-header h3 {
            margin: 0;
            font-weight: 700;
            font-size: 1.5rem;
        }

        .form-body {
            padding: 30px;
        }

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

        .form-label {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 8px;
            display: block;
        }

        .form-label i {
            color: #667eea;
            margin-right: 8px;
            width: 20px;
        }

        .input-group-modern {
            position: relative;
            display: flex;
            align-items: center;
        }

        .input-icon {
            position: absolute;
            left: 15px;
            color: #94a3b8;
            font-size: 1.1rem;
            z-index: 1;
        }

        .form-control-modern {
            width: 100%;
            padding: 14px 20px 14px 45px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 1rem;
            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;
        }

        .form-control-modern:read-only {
            background-color: #f8fafc;
            cursor: not-allowed;
        }

        .pin-select-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .pin-select {
            flex: 1;
            padding: 14px 20px 14px 45px;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: white;
            cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%23647e8c' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 15px center;
            background-size: 16px;
        }

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

        .pin-select:disabled {
            background-color: #f1f5f9;
            cursor: not-allowed;
        }

        .auto-select-btn {
            padding: 14px 20px;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .auto-select-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(16, 185, 129, 0.3);
        }

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

        .pin-status-icon {
            position: absolute;
            right: 120px;
            font-size: 1.2rem;
            z-index: 1;
        }

        .pin-valid {
            color: #10b981;
        }

        .pin-invalid {
            color: #ef4444;
        }

        .pin-info-text {
            font-size: 0.85rem;
            margin-top: 5px;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .pin-stats {
            background: #f8fafc;
            border-radius: 16px;
            padding: 15px 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border: 1px solid #e2e8f0;
        }

        .pin-count {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .pin-count i {
            font-size: 24px;
            color: #667eea;
        }

        .pin-count span {
            font-weight: 700;
            font-size: 1.2rem;
            color: #1e293b;
        }

        .pin-count small {
            color: #64748b;
            font-size: 0.85rem;
        }

        .view-pins-link {
            color: #667eea;
            text-decoration: none;
            font-weight: 600;
            font-size: 0.9rem;
            padding: 8px 12px;
            border-radius: 12px;
            background: rgba(102, 126, 234, 0.1);
            transition: all 0.3s ease;
        }

        .view-pins-link:hover {
            background: rgba(102, 126, 234, 0.2);
        }

        .quick-actions {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .quick-action-btn {
            flex: 1;
            padding: 12px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            background: white;
            color: #1e293b;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            min-width: 100px;
        }

        .quick-action-btn:hover {
            border-color: #667eea;
            background: #f8fafc;
            transform: translateY(-2px);
        }

        .quick-action-btn i {
            color: #667eea;
        }

        .no-pins-message {
            background: #fff3cd;
            border: 1px solid #ffeeba;
            color: #856404;
            padding: 15px;
            border-radius: 16px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .no-pins-message i {
            font-size: 24px;
            color: #856404;
        }

        .saved-data-badge {
            background: #f1f5f9;
            border-radius: 20px;
            padding: 8px 15px;
            font-size: 0.9rem;
            color: #64748b;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 20px;
            border: 1px solid #e2e8f0;
        }

        .password-requirements {
            background: #f8fafc;
            border-radius: 12px;
            padding: 12px 15px;
            margin-top: 10px;
            font-size: 0.85rem;
            border: 1px solid #e2e8f0;
        }

        .requirement-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #64748b;
            margin-bottom: 5px;
        }

        .requirement-item.valid {
            color: #10b981;
        }

        .btn-submit {
            width: 100%;
            padding: 16px;
            border: none;
            border-radius: 16px;
            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);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            margin-top: 25px;
        }

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

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

        .success-message {
            background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
            color: #1e293b;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            border: 1px solid #a7f3d0;
        }

        .error-message {
            background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
            color: #1e293b;
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            border: 1px solid #fecaca;
        }

        /* Package Selector */
        .package-selector {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
        }

        .package-card {
            flex: 1;
            border: 2px solid #e2e8f0;
            border-radius: 16px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }

        .package-card.selected {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.1);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.2);
        }

        .package-card h4 {
            font-weight: 700;
            color: #1e293b;
        }

        .package-card .price {
            font-size: 1.8rem;
            font-weight: 800;
            color: #667eea;
            margin: 10px 0;
        }

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

        .package-card .package-badge.popular {
            background: #ec4899;
        }

        /* Aadhaar Preview */
        .aadhaar-preview {
            font-family: monospace;
            font-size: 1.2rem;
            letter-spacing: 2px;
            margin-top: 5px;
        }

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

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

        .footer {
            text-align: center;
            padding: 20px;
            color: #64748b;
        }
    </style>
</head>

<body>

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

    <div class="registration-container">
        <!-- Success/Error Messages -->
        <?php if ($success_msg): ?>
            <div class="success-message animate-slide">
                <i class="fas fa-check-circle fa-2x"></i>
                <div>
                    <h5 class="mb-1">Registration Successful!</h5>
                    <p class="mb-0"><?php echo htmlspecialchars(urldecode($success_msg)); ?></p>
                </div>
                <button class="btn-close ms-auto" onclick="this.parentElement.remove()" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if ($error_msg): ?>
            <div class="error-message animate-slide">
                <i class="fas fa-exclamation-circle fa-2x"></i>
                <div>
                    <h5 class="mb-1">Registration Failed</h5>
                    <p class="mb-0"><?php echo htmlspecialchars(urldecode($error_msg)); ?></p>
                </div>
                <button class="btn-close ms-auto" onclick="this.parentElement.remove()" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Registration Form -->
        <div class="form-card animate-slide">
            <div class="form-header">
                <h3><i class="fas fa-user-plus me-2"></i>New Member Registration</h3>
                <p class="mb-0">Fill in all the details below</p>
            </div>
            <div class="form-body">
                <!-- PIN Stats -->
                <div class="pin-stats">
                    <div class="pin-count">
                        <i class="fas fa-ticket-alt"></i>
                        <div>
                            <span><?php echo $pins_count; ?></span>
                            <small>Available PINs</small>
                        </div>
                    </div>
                    <a href="pin.php" class="view-pins-link">
                        View My PINs <i class="fas fa-arrow-right ms-1"></i>
                    </a>
                </div>

                <!-- No PINs Available Message -->
                <?php if ($pins_count == 0): ?>
                <div class="no-pins-message">
                    <i class="fas fa-exclamation-triangle"></i>
                    <div>
                        <strong>No PINs Available!</strong>
                        <p class="mb-0 small">You don't have any unused PINs. Please purchase PINs first.</p>
                    </div>
                </div>
                <?php endif; ?>

                

                <!-- Auto PIN Selection Info -->
                <?php if ($pins_count > 0 && $first_available_pin): ?>
                <div class="saved-data-badge">
                    <i class="fas fa-magic"></i>
                    <span>Auto-selected first available PIN</span>
                    <button type="button" class="btn btn-sm btn-outline-primary ms-2" onclick="selectRandomPin()" title="Select random PIN">
                        <i class="fas fa-random"></i> Random
                    </button>
                </div>
                <?php endif; ?>

                <!-- Package Selector -->
                <div class="package-selector">
                    <div class="package-card selected" data-package="2500" onclick="selectPackage(this, 2500)">
                        <span class="package-badge">Starter</span>
                        <i class="fas fa-box fa-2x text-primary mb-2"></i>
                        <h4>Starter Package</h4>
                        <div class="price">₹2,500</div>
                        <p class="text-muted small">EMS Foot Massager + Detox Patch + Anti-Radiation Chip + Magnetic Door Mat + Tulsi Drops</p>
                    </div>
                    <div class="package-card" data-package="3500" onclick="selectPackage(this, 3500)">
                        <span class="package-badge popular">Popular</span>
                        <i class="fas fa-crown fa-2x text-warning mb-2"></i>
                        <h4>Pro Package</h4>
                        <div class="price">₹3,500</div>
                        <p class="text-muted small">Alkaline Water Jug + Anti-Radiation Chip + EMS Foot Massager + Tulsi Drops + Detox Patch</p>
                    </div>
                </div>

                <form method="POST" action="element/process_registration.php" id="registrationForm">
                    <!-- Sponsor ID -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-user-tie"></i>Sponsor ID</label>
                        <div class="input-group-modern">
                            <i class="fas fa-id-card input-icon"></i>
                            <input type="text" class="form-control-modern" name="sponsor_id" 
                                   value="<?php echo htmlspecialchars($my_id); ?>" readonly>
                        </div>
                    </div>

                    <!-- Package ID (hidden) -->
                    <input type="hidden" name="package_id" id="package_id" value="2500">

                    <!-- E-PIN with Auto Select -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-ticket-alt"></i>E-PIN <span class="text-danger">*</span></label>
                        <div class="pin-select-wrapper">
                            <i class="fas fa-key input-icon"></i>
                            <?php if ($pins_count > 0): ?>
                            <select class="pin-select" id="pin" name="pin" required onchange="validatePIN(this.value)">
                                <option value="">Select a PIN</option>
                                <?php foreach ($available_pins as $index => $pin): ?>
                                <option value="<?php echo htmlspecialchars($pin['pin_value']); ?>" 
                                    <?php echo ($index === 0) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($pin['pin_value']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <button type="button" class="auto-select-btn" onclick="autoSelectPin()">
                                <i class="fas fa-bolt"></i> Auto
                            </button>
                            <?php else: ?>
                            <input type="text" class="form-control-modern" id="pin" name="pin" 
                                   placeholder="No PINs available" value="" disabled>
                            <button type="button" class="auto-select-btn" disabled>
                                <i class="fas fa-bolt"></i> Auto
                            </button>
                            <?php endif; ?>
                            <span class="pin-status-icon" id="pinStatus"></span>
                        </div>
                        <div class="pin-info-text" id="pinMessage">
                            <?php if ($pins_count > 0 && $first_available_pin): ?>
                            <span style="color: #10b981;">
                                <i class="fas fa-check-circle"></i> PIN selected: <?php echo htmlspecialchars($first_available_pin); ?>
                            </span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Full Name -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-user"></i>Full Name <span class="text-danger">*</span></label>
                        <div class="input-group-modern">
                            <i class="fas fa-signature input-icon"></i>
                            <input type="text" class="form-control-modern" id="name" name="name" 
                                   placeholder="Enter member's full name" required
                                   oninput="this.value = this.value.toUpperCase()">
                        </div>
                    </div>

                    <!-- Email -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-envelope"></i>Email</label>
                        <div class="input-group-modern">
                            <i class="fas fa-at input-icon"></i>
                            <input type="email" class="form-control-modern" id="email" name="email" 
                                   placeholder="Enter email address (optional)">
                        </div>
                    </div>

                    <!-- Mobile -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-phone-alt"></i>Mobile <span class="text-danger">*</span></label>
                        <div class="input-group-modern">
                            <i class="fas fa-mobile-alt input-icon"></i>
                            <input type="tel" class="form-control-modern" id="phone" name="phone" 
                                   placeholder="10 digit mobile number" required
                                   pattern="[0-9]{10}" maxlength="10"
                                   oninput="this.value = this.value.replace(/[^0-9]/g, '')">
                        </div>
                    </div>

                    <!-- Aadhaar Number (New Field) -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-id-card"></i>Aadhaar Number <span class="text-danger">*</span></label>
                        <div class="input-group-modern">
                            <i class="fas fa-id-card input-icon"></i>
                            <input type="text" class="form-control-modern" id="aadhaar" name="aadhaar" 
                                   placeholder="12 digit Aadhaar number" required
                                   pattern="[0-9]{12}" maxlength="12"
                                   oninput="this.value = this.value.replace(/[^0-9]/g, ''); formatAadhaar(this.value)">
                        </div>
                        <div id="aadhaarPreview" class="aadhaar-preview"></div>
                        <small class="text-muted">Enter 12 digit Aadhaar number</small>
                    </div>

                    <!-- Password -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-lock"></i>Password <span class="text-danger">*</span></label>
                        <div class="input-group-modern">
                            <i class="fas fa-key input-icon"></i>
                            <input type="password" class="form-control-modern" id="password" name="password" 
                                   placeholder="Create password" required
                                   onkeyup="validatePassword()" autocomplete="new-password">
                        </div>
                    </div>

                    <!-- Confirm Password -->
                    <div class="form-group">
                        <label class="form-label"><i class="fas fa-check-circle"></i>Confirm Password <span class="text-danger">*</span></label>
                        <div class="input-group-modern">
                            <i class="fas fa-check-circle input-icon"></i>
                            <input type="password" class="form-control-modern" id="confirm_password" 
                                   name="confirm_password" placeholder="Confirm password" required
                                   onkeyup="validatePasswordMatch()" autocomplete="new-password">
                        </div>
                        <div id="passwordMatchMessage" class="pin-info-text"></div>
                    </div>

                    <!-- Password Requirements -->
                    <div class="password-requirements">
                        <div class="requirement-item" id="req-length">
                            <i class="fas fa-circle"></i> At least 6 characters
                        </div>
                        <div class="requirement-item" id="req-match">
                            <i class="fas fa-circle"></i> Passwords match
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <button type="submit" name="user_registration" class="btn-submit" id="submitBtn" <?php echo $pins_count == 0 ? 'disabled' : ''; ?>>
                        <i class="fas fa-user-plus"></i>
                        <span><?php echo $pins_count == 0 ? 'No PINs Available' : 'Register Member'; ?></span>
                    </button>
                </form>
            </div>
        </div>
    </div>
</main>

<!-- Footer -->
<footer id="footer" class="footer">
    
</footer>

<!-- Bootstrap JS -->
<script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

<script>
// Form validation variables
var pinValid = false;
var passwordValid = false;
var passwordsMatch = false;

// Package selection
function selectPackage(element, price) {
    document.querySelectorAll('.package-card').forEach(card => {
        card.classList.remove('selected');
    });
    element.classList.add('selected');
    document.getElementById('package_id').value = price;
}

// Aadhaar formatting
function formatAadhaar(value) {
    const preview = document.getElementById('aadhaarPreview');
    if (value.length === 12) {
        const formatted = value.replace(/(\d{4})(\d{4})(\d{4})/, '$1 $2 $3');
        preview.innerHTML = '<i class="fas fa-id-card text-primary me-2"></i>' + formatted;
    } else {
        preview.innerHTML = '';
    }
}

// PIN Validation Function
function validatePIN(pin) {
    const pinStatus = document.getElementById('pinStatus');
    const pinMessage = document.getElementById('pinMessage');
    
    if (!pin || pin.length < 4) {
        if (pinStatus) pinStatus.innerHTML = '';
        if (pinMessage) pinMessage.innerHTML = '';
        pinValid = false;
        return;
    }

    fetch('element/validate_pin.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'pin=' + encodeURIComponent(pin)
    })
    .then(response => response.json())
    .then(result => {
        if (result.valid) {
            if (pinStatus) pinStatus.innerHTML = '<i class="fas fa-check-circle pin-valid"></i>';
            if (pinMessage) pinMessage.innerHTML = '<span style="color: #10b981;"><i class="fas fa-check-circle"></i> Valid PIN</span>';
            pinValid = true;
            
            // If PIN has package_id, auto-select package
            if (result.package_id && result.package_id > 0) {
                const packageCards = document.querySelectorAll('.package-card');
                packageCards.forEach(card => {
                    const price = card.getAttribute('data-package');
                    if (parseInt(price) === result.package_id) {
                        selectPackage(card, result.package_id);
                    }
                });
            }
        } else {
            if (pinStatus) pinStatus.innerHTML = '<i class="fas fa-times-circle pin-invalid"></i>';
            if (pinMessage) pinMessage.innerHTML = '<span style="color: #ef4444;"><i class="fas fa-exclamation-circle"></i> ' + result.message + '</span>';
            pinValid = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        if (pinStatus) pinStatus.innerHTML = '<i class="fas fa-exclamation-triangle pin-invalid"></i>';
        if (pinMessage) pinMessage.innerHTML = '<span style="color: #ef4444;">Error validating PIN</span>';
        pinValid = false;
    });
}

// Auto Select PIN Function
function autoSelectPin() {
    const pinSelect = document.getElementById('pin');
    if (pinSelect && pinSelect.options.length > 1) {
        pinSelect.selectedIndex = 1;
        validatePIN(pinSelect.value);
        showNotification('Auto-selected first available PIN', 'success');
    } else {
        showNotification('No PINs available', 'error');
    }
}

// Select Random PIN
function selectRandomPin() {
    const pinSelect = document.getElementById('pin');
    if (pinSelect && pinSelect.options.length > 1) {
        const randomIndex = Math.floor(Math.random() * (pinSelect.options.length - 1)) + 1;
        pinSelect.selectedIndex = randomIndex;
        validatePIN(pinSelect.value);
        showNotification('Random PIN selected', 'success');
    }
}

// Save form data to localStorage
function saveFormData() {
    const formData = {
        name: document.getElementById('name').value,
        email: document.getElementById('email').value,
        phone: document.getElementById('phone').value,
        aadhaar: document.getElementById('aadhaar').value,
        password: document.getElementById('password').value,
        confirm_password: document.getElementById('confirm_password').value,
        package_id: document.getElementById('package_id').value,
        timestamp: new Date().toISOString()
    };
    
    localStorage.setItem('registrationDraft', JSON.stringify(formData));
    showNotification('Draft saved successfully!', 'success');
}

// Load form data from localStorage
function loadFormData() {
    const savedData = localStorage.getItem('registrationDraft');
    
    if (savedData) {
        try {
            const formData = JSON.parse(savedData);
            
            document.getElementById('name').value = formData.name || '';
            document.getElementById('email').value = formData.email || '';
            document.getElementById('phone').value = formData.phone || '';
            document.getElementById('aadhaar').value = formData.aadhaar || '';
            document.getElementById('password').value = formData.password || '';
            document.getElementById('confirm_password').value = formData.confirm_password || '';
            
            // Format Aadhaar preview
            if (formData.aadhaar && formData.aadhaar.length === 12) {
                formatAadhaar(formData.aadhaar);
            }
            
            // Select package
            if (formData.package_id) {
                const packageCards = document.querySelectorAll('.package-card');
                packageCards.forEach(card => {
                    const price = card.getAttribute('data-package');
                    if (parseInt(price) === parseInt(formData.package_id)) {
                        selectPackage(card, formData.package_id);
                    }
                });
            }
            
            // Re-run validations
            validatePassword();
            validatePasswordMatch();
            
            showNotification('Draft loaded successfully!', 'success');
        } catch (e) {
            console.error('Error loading draft:', e);
            showNotification('Error loading draft', 'error');
        }
    } else {
        showNotification('No saved draft found', 'error');
    }
}

// Clear form data and localStorage
function clearFormData() {
    if (confirm('Clear all form data?')) {
        document.getElementById('registrationForm').reset();
        localStorage.removeItem('registrationDraft');
        
        // Reset PIN selection to first available
        const pinSelect = document.getElementById('pin');
        if (pinSelect && pinSelect.options.length > 1) {
            pinSelect.selectedIndex = 1;
            validatePIN(pinSelect.value);
        }
        
        // Reset package to starter
        const starterCard = document.querySelector('.package-card[data-package="2500"]');
        if (starterCard) {
            selectPackage(starterCard, 2500);
        }
        
        // Reset Aadhaar preview
        document.getElementById('aadhaarPreview').innerHTML = '';
        
        // Reset validation
        document.getElementById('passwordMatchMessage').innerHTML = '';
        document.getElementById('req-length').innerHTML = '<i class="fas fa-circle"></i> At least 6 characters';
        document.getElementById('req-match').innerHTML = '<i class="fas fa-circle"></i> Passwords match';
        document.getElementById('req-length').style.color = '#64748b';
        document.getElementById('req-match').style.color = '#64748b';
        
        showNotification('Form cleared', 'success');
    }
}

// Password Validation
function validatePassword() {
    const password = document.getElementById('password').value;
    const reqLength = document.getElementById('req-length');
    
    if (password.length >= 6) {
        reqLength.innerHTML = '<i class="fas fa-check-circle" style="color: #10b981;"></i> At least 6 characters ✓';
        reqLength.style.color = '#10b981';
        passwordValid = true;
    } else {
        reqLength.innerHTML = '<i class="fas fa-circle"></i> At least 6 characters';
        reqLength.style.color = '#64748b';
        passwordValid = false;
    }
    
    validatePasswordMatch();
}

// Password Match Validation
function validatePasswordMatch() {
    const password = document.getElementById('password').value;
    const confirm = document.getElementById('confirm_password').value;
    const reqMatch = document.getElementById('req-match');
    const message = document.getElementById('passwordMatchMessage');
    
    if (confirm.length > 0) {
        if (password === confirm) {
            reqMatch.innerHTML = '<i class="fas fa-check-circle" style="color: #10b981;"></i> Passwords match ✓';
            reqMatch.style.color = '#10b981';
            message.innerHTML = '<span style="color: #10b981;"><i class="fas fa-check-circle"></i> Passwords match</span>';
            passwordsMatch = true;
        } else {
            reqMatch.innerHTML = '<i class="fas fa-circle"></i> Passwords match';
            reqMatch.style.color = '#64748b';
            message.innerHTML = '<span style="color: #ef4444;"><i class="fas fa-times-circle"></i> Passwords do not match</span>';
            passwordsMatch = false;
        }
    } else {
        reqMatch.innerHTML = '<i class="fas fa-circle"></i> Passwords match';
        reqMatch.style.color = '#64748b';
        message.innerHTML = '';
        passwordsMatch = false;
    }
}

// Form Submission
document.getElementById('registrationForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const pinSelect = document.getElementById('pin');
    if (!pinSelect || !pinSelect.value) {
        showNotification('Please select a PIN', 'error');
        if (pinSelect) pinSelect.focus();
        return;
    }
    
    if (!pinValid) {
        showNotification('Please enter a valid PIN', 'error');
        document.getElementById('pin').focus();
        return;
    }
    
    // Validate Aadhaar
    const aadhaar = document.getElementById('aadhaar').value;
    if (aadhaar.length !== 12) {
        showNotification('Aadhaar number must be 12 digits', 'error');
        document.getElementById('aadhaar').focus();
        return;
    }
    
    if (!passwordValid) {
        showNotification('Password must be at least 6 characters', 'error');
        document.getElementById('password').focus();
        return;
    }
    
    if (!passwordsMatch) {
        showNotification('Passwords do not match', 'error');
        document.getElementById('confirm_password').focus();
        return;
    }
    
    // Clear draft after successful submission
    localStorage.removeItem('registrationDraft');
    
    this.submit();
});

// Show Notification
function showNotification(message, type) {
    Swal.fire({
        toast: true,
        position: 'top-end',
        icon: type === 'success' ? 'success' : 'error',
        title: message,
        showConfirmButton: false,
        timer: 3000
    });
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    console.log('Registration page loaded');
    
    // Auto-select first PIN if available
    const pinSelect = document.getElementById('pin');
    if (pinSelect && pinSelect.options.length > 1) {
        // Auto-validate the selected PIN
        setTimeout(() => {
            validatePIN(pinSelect.value);
        }, 500);
    }
    
    // Try to load saved draft
    const savedData = localStorage.getItem('registrationDraft');
    if (savedData) {
        setTimeout(() => {
            Swal.fire({
                title: 'Saved Draft Found',
                text: 'Would you like to load your saved draft?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, load it',
                cancelButtonText: 'No, start fresh'
            }).then((result) => {
                if (result.isConfirmed) {
                    loadFormData();
                }
            });
        }, 500);
    }
});
</script>

</body>
</html>