<?php
// Enable full error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session
session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

// Redirect if already logged in
if (isset($_SESSION['user_id'])) {
    header('Location: user/dashboard.php');
    exit();
}

// Initialize variables
$errors = [];
$data = [
    'full_name' => '',
    'email' => '',
    'age' => '',
    'birth_year' => '',
    'address' => '',
    'occupation' => '',
    'phone' => '',
    'id_type' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize and validate inputs
    $data['full_name'] = sanitizeInput($_POST['full_name'] ?? '');
    $data['email'] = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
    $data['password'] = $_POST['password'] ?? '';
    $data['confirm_password'] = $_POST['confirm_password'] ?? '';
    $data['age'] = (int) ($_POST['age'] ?? 0);
    $data['birth_year'] = (int) ($_POST['birth_year'] ?? 0);
    $data['address'] = sanitizeInput($_POST['address'] ?? '');
    $data['occupation'] = sanitizeInput($_POST['occupation'] ?? '');
    $data['phone'] = sanitizeInput($_POST['phone'] ?? '');
    $data['id_type'] = sanitizeInput($_POST['id_type'] ?? '');

    // Validate ID file upload
    if (!isset($_FILES['id_file']) || $_FILES['id_file']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = "Please upload a valid ID document";
    } else {
        $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
        $maxFileSize = 5 * 1024 * 1024; // 5MB
        $fileType = $_FILES['id_file']['type'];

        if (!in_array($fileType, $allowedTypes)) {
            $errors[] = "Invalid file type. Please upload JPG, PNG, or PDF files only.";
        }

        if ($_FILES['id_file']['size'] > $maxFileSize) {
            $errors[] = "File size too large. Maximum size is 5MB.";
        }
    }

    // Validate password
    if (strlen($data['password']) < 8) {
        $errors[] = "Password must be at least 8 characters long";
    }
    if (!preg_match('/[A-Z]/', $data['password'])) {
        $errors[] = "Password must contain at least one uppercase letter";
    }
    if (!preg_match('/[a-z]/', $data['password'])) {
        $errors[] = "Password must contain at least one lowercase letter";
    }
    if (!preg_match('/[0-9]/', $data['password'])) {
        $errors[] = "Password must contain at least one number";
    }
    if (!preg_match('/[!@#$%^&*]/', $data['password'])) {
        $errors[] = "Password must contain at least one special character (!@#$%^&*)";
    }

    if ($data['password'] !== $data['confirm_password']) {
        $errors[] = "Passwords do not match";
    }

    if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }

    // More flexible phone validation
    $phonePattern = '/^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{4,10}$/';
    if (!preg_match($phonePattern, $data['phone'])) {
        $errors[] = "Invalid phone number format. Please enter a valid phone number (e.g., +1234567890, 1234567890)";
    }

    if ($data['age'] < 18 || $data['age'] > 120) {
        $errors[] = "Age must be between 18 and 120";
    }

    $currentYear = (int) date('Y');
    if ($data['birth_year'] < 1900 || $data['birth_year'] > $currentYear) {
        $errors[] = "Birth year must be between 1900 and $currentYear";
    }

    $calculatedAge = $currentYear - $data['birth_year'];
    if (abs($calculatedAge - $data['age']) > 1) {
        $errors[] = "Age and birth year don't match";
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("SELECT email FROM users WHERE email = ?");
            $stmt->execute([$data['email']]);
            if ($stmt->fetch()) {
                $errors[] = "Email already registered";
            }
        } catch (PDOException $e) {
            error_log("Database error: " . $e->getMessage());
            $errors[] = "System error. Please try again later.";
        }
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("INSERT INTO users (full_name, email, password_hash, age, birth_year, address, occupation, phone, status, created_at) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())");
            $passwordHash = password_hash($data['password'], PASSWORD_DEFAULT);
            $stmt->execute([
                $data['full_name'],
                $data['email'],
                $passwordHash,
                $data['age'],
                $data['birth_year'],
                $data['address'],
                $data['occupation'],
                $data['phone']
            ]);

            $userId = $pdo->lastInsertId();

            // Handle ID file upload with better error handling
            $uploadDir = __DIR__ . '/uploads/id_verifications/';

            // Create directory if it doesn't exist with proper permissions
            if (!file_exists($uploadDir)) {
                if (!mkdir($uploadDir, 0777, true)) {
                    throw new Exception("Failed to create upload directory. Please check permissions.");
                }
                chmod($uploadDir, 0777);
            }

            // Check if directory is writable
            if (!is_writable($uploadDir)) {
                chmod($uploadDir, 0777);
                if (!is_writable($uploadDir)) {
                    throw new Exception("Upload directory is not writable. Please check permissions for: " . $uploadDir);
                }
            }

            $fileExtension = strtolower(pathinfo($_FILES['id_file']['name'], PATHINFO_EXTENSION));
            $fileName = 'id_' . $userId . '_' . time() . '.' . $fileExtension;
            $filePath = 'uploads/id_verifications/' . $fileName;
            $fullFilePath = $uploadDir . $fileName;

            if (move_uploaded_file($_FILES['id_file']['tmp_name'], $fullFilePath)) {
                chmod($fullFilePath, 0644);

                $stmt = $pdo->prepare("INSERT INTO id_verifications (user_id, id_type, id_file_path) VALUES (?, ?, ?)");
                $stmt->execute([$userId, $data['id_type'], $filePath]);
            } else {
                throw new Exception("Failed to upload ID file. Error: " . $_FILES['id_file']['error']);
            }

            $pdo->commit();

            // Set session variables and redirect to dashboard with pending status
            $_SESSION['user_id'] = $userId;
            $_SESSION['user_name'] = $data['full_name'];
            $_SESSION['user_email'] = $data['email'];
            $_SESSION['user_status'] = 'pending';

            // Redirect to user dashboard
            header('Location: user/dashboard.php?pending=1');
            exit();

        } catch (PDOException $e) {
            $pdo->rollBack();
            error_log("Registration error: " . $e->getMessage());
            $errors[] = "Registration failed: " . $e->getMessage();
        } catch (Exception $e) {
            $pdo->rollBack();
            error_log("File upload error: " . $e->getMessage());
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description"
        content="Open your Oakshire Finance account - Secure, fast, and easy registration process." />
    <title>Open Account | Oakshire Finance</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700&display=swap"
        rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --warning-orange: #f39c12;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: linear-gradient(135deg, var(--gray-50) 0%, var(--gray-100) 100%);
            min-height: 100vh;
            padding: 40px 24px;
            position: relative;
        }

        /* Animated background */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" opacity="0.03"><path fill="%230a2540" d="M10,50 L90,50 M50,10 L50,90 M30,30 L70,70 M30,70 L70,30"/></svg>') repeat;
            pointer-events: none;
            animation: drift 60s linear infinite;
            z-index: 0;
        }

        @keyframes drift {
            0% {
                background-position: 0 0;
            }

            100% {
                background-position: 1000px 1000px;
            }
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            position: relative;
            z-index: 2;
        }

        /* Header */
        .header {
            text-align: center;
            margin-bottom: 32px;
            animation: fadeInUp 0.6s ease forwards;
        }

        .logo {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            margin-bottom: 16px;
        }

        .logo-icon {
            width: 48px;
            height: 48px;
            background: var(--primary-navy);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 24px;
            color: white;
        }

        .logo-text {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.5px;
        }

        .header h1 {
            font-size: 32px;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 8px;
        }

        .header p {
            font-size: 16px;
            color: var(--gray-600);
        }

        /* Registration Card */
        .register-card {
            background: var(--white);
            border-radius: 24px;
            padding: 40px;
            box-shadow: var(--shadow-lg);
            animation: fadeInUp 0.6s ease 0.1s forwards;
            opacity: 0;
            transform: translateY(20px);
            animation: fadeInUp 0.6s ease 0.1s forwards;
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Progress Steps */
        .progress-steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 40px;
            position: relative;
        }

        .progress-steps::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background: var(--gray-200);
            z-index: 1;
        }

        .step {
            position: relative;
            z-index: 2;
            text-align: center;
            flex: 1;
        }

        .step-number {
            width: 40px;
            height: 40px;
            background: var(--gray-200);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 8px;
            font-weight: 600;
            color: var(--gray-600);
            transition: var(--transition);
        }

        .step.active .step-number {
            background: var(--primary-navy);
            color: white;
        }

        .step.completed .step-number {
            background: var(--success-green);
            color: white;
        }

        .step.completed .step-number i {
            font-size: 18px;
        }

        .step-label {
            font-size: 12px;
            color: var(--gray-600);
        }

        .step.active .step-label {
            color: var(--primary-navy);
            font-weight: 600;
        }

        /* Form Sections */
        .form-section {
            display: none;
        }

        .form-section.active {
            display: block;
            animation: fadeIn 0.4s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateX(10px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

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

        .form-group.full-width {
            grid-column: span 2;
        }

        label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 6px;
        }

        .required::after {
            content: '*';
            color: var(--error-red);
            margin-left: 4px;
        }

        input,
        select {
            width: 100%;
            padding: 12px 16px;
            font-size: 15px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            background: var(--white);
            transition: var(--transition);
            outline: none;
            color: var(--gray-800);
        }

        input:focus,
        select:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        input.error,
        select.error {
            border-color: var(--error-red);
        }

        .error-message {
            font-size: 12px;
            color: var(--error-red);
            margin-top: 4px;
            display: none;
        }

        .error-message.show {
            display: block;
        }

        /* File Upload */
        .file-upload {
            border: 2px dashed var(--gray-300);
            border-radius: 12px;
            padding: 24px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            background: var(--gray-50);
        }

        .file-upload:hover {
            border-color: var(--primary-blue);
            background: rgba(26, 77, 140, 0.02);
        }

        .file-upload i {
            font-size: 32px;
            color: var(--gray-500);
            margin-bottom: 8px;
        }

        .file-upload p {
            font-size: 13px;
            color: var(--gray-600);
        }

        .file-upload input {
            display: none;
        }

        .file-name {
            font-size: 12px;
            color: var(--success-green);
            margin-top: 8px;
            display: none;
        }

        /* Password Requirements */
        .password-requirements {
            background: var(--gray-50);
            border-radius: 12px;
            padding: 12px;
            margin-top: 8px;
            font-size: 12px;
        }

        .password-requirements p {
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--gray-700);
        }

        .requirement {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;
            color: var(--gray-600);
        }

        .requirement.valid {
            color: var(--success-green);
        }

        .requirement i {
            font-size: 12px;
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: slideIn 0.4s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-10px);
            }

            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        /* Buttons */
        .form-buttons {
            display: flex;
            justify-content: space-between;
            gap: 16px;
            margin-top: 32px;
        }

        .btn-prev,
        .btn-next,
        .btn-submit {
            padding: 12px 28px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            border: none;
        }

        .btn-prev {
            background: var(--gray-100);
            color: var(--gray-700);
        }

        .btn-prev:hover {
            background: var(--gray-200);
        }

        .btn-next,
        .btn-submit {
            background: var(--primary-navy);
            color: white;
        }

        .btn-next:hover,
        .btn-submit:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

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

        .login-link {
            text-align: center;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid var(--gray-200);
            font-size: 14px;
            color: var(--gray-600);
        }

        .login-link a {
            color: var(--primary-blue);
            text-decoration: none;
            font-weight: 600;
        }

        .login-link a:hover {
            text-decoration: underline;
        }

        .phone-hint {
            font-size: 11px;
            color: var(--gray-500);
            margin-top: 4px;
        }

        @media (max-width: 768px) {
            body {
                padding: 20px 16px;
            }

            .register-card {
                padding: 24px;
            }

            .form-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .form-group.full-width {
                grid-column: span 1;
            }

            .header h1 {
                font-size: 26px;
            }

            .step-label {
                font-size: 10px;
            }

            .step-number {
                width: 32px;
                height: 32px;
                font-size: 12px;
            }
        }

        .btn-submit.loading {
            position: relative;
            color: transparent;
        }

        .btn-submit.loading::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            top: 50%;
            left: 50%;
            margin-left: -10px;
            margin-top: -10px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>
    <link rel="stylesheet" href="assets/css/nexus-theme.css" />
</head>

<body>
    <div class="container">
        <div class="header">
            <a href="index.php" class="logo">
                <div class="logo-icon">
                    <i class="fas fa-building-columns"></i>
                </div>
                <span class="logo-text">Oakshire Finance</span>
            </a>
            <h1>Open an Account</h1>
            <p>Join thousands of satisfied customers who trust Oakshire Finance</p>
        </div>

        <div class="register-card">
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <div>
                        <?php foreach ($errors as $error): ?>
                            <p><?= htmlspecialchars($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>

            <form method="POST" id="registerForm" enctype="multipart/form-data">
                <!-- Progress Steps -->
                <div class="progress-steps">
                    <div class="step active" data-step="1">
                        <div class="step-number">1</div>
                        <div class="step-label">Personal Info</div>
                    </div>
                    <div class="step" data-step="2">
                        <div class="step-number">2</div>
                        <div class="step-label">Contact Details</div>
                    </div>
                    <div class="step" data-step="3">
                        <div class="step-number">3</div>
                        <div class="step-label">Verification</div>
                    </div>
                    <div class="step" data-step="4">
                        <div class="step-number">4</div>
                        <div class="step-label">Security</div>
                    </div>
                </div>

                <!-- Section 1: Personal Info -->
                <div class="form-section active" data-section="1">
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label class="required">Full Name</label>
                            <input type="text" name="full_name" id="full_name"
                                value="<?= htmlspecialchars($data['full_name']) ?>" required>
                            <div class="error-message" id="full_name_error">Please enter your full name</div>
                        </div>
                        <div class="form-group">
                            <label class="required">Age</label>
                            <input type="number" name="age" id="age" min="18" max="120"
                                value="<?= htmlspecialchars($data['age']) ?>" required>
                            <div class="error-message" id="age_error">Age must be 18 or above</div>
                        </div>
                        <div class="form-group">
                            <label class="required">Birth Year</label>
                            <input type="number" name="birth_year" id="birth_year" min="1900" max="<?= date('Y') ?>"
                                value="<?= htmlspecialchars($data['birth_year']) ?>" required>
                            <div class="error-message" id="birth_year_error">Please enter a valid birth year</div>
                        </div>
                        <div class="form-group full-width">
                            <label class="required">Address</label>
                            <input type="text" name="address" id="address"
                                value="<?= htmlspecialchars($data['address']) ?>" required>
                            <div class="error-message" id="address_error">Please enter your address</div>
                        </div>
                    </div>
                </div>

                <!-- Section 2: Contact Details -->
                <div class="form-section" data-section="2">
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label class="required">Email Address</label>
                            <input type="email" name="email" id="email" value="<?= htmlspecialchars($data['email']) ?>"
                                required>
                            <div class="error-message" id="email_error">Please enter a valid email address</div>
                        </div>
                        <div class="form-group full-width">
                            <label class="required">Phone Number</label>
                            <input type="tel" name="phone" id="phone" placeholder="+1234567890"
                                value="<?= htmlspecialchars($data['phone']) ?>" required>
                            <div class="phone-hint">Format: +1234567890, 1234567890, or 123-456-7890</div>
                            <div class="error-message" id="phone_error">Please enter a valid phone number</div>
                        </div>
                        <div class="form-group full-width">
                            <label class="required">Occupation</label>
                            <input type="text" name="occupation" id="occupation"
                                value="<?= htmlspecialchars($data['occupation']) ?>" required>
                            <div class="error-message" id="occupation_error">Please enter your occupation</div>
                        </div>
                    </div>
                </div>

                <!-- Section 3: Verification -->
                <div class="form-section" data-section="3">
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label class="required">ID Type</label>
                            <select name="id_type" id="id_type" required>
                                <option value="">Select ID Type</option>
                                <option value="passport" <?= $data['id_type'] === 'passport' ? 'selected' : '' ?>>Passport
                                </option>
                                <option value="drivers_license" <?= $data['id_type'] === 'drivers_license' ? 'selected' : '' ?>>Driver's License</option>
                                <option value="national_id" <?= $data['id_type'] === 'national_id' ? 'selected' : '' ?>>
                                    National ID Card</option>
                                <option value="student_id" <?= $data['id_type'] === 'student_id' ? 'selected' : '' ?>>
                                    Student ID</option>
                                <option value="other" <?= $data['id_type'] === 'other' ? 'selected' : '' ?>>Other
                                    Government ID</option>
                            </select>
                            <div class="error-message" id="id_type_error">Please select an ID type</div>
                        </div>
                        <div class="form-group full-width">
                            <label class="required">Upload ID Document</label>
                            <div class="file-upload" id="fileUpload">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>Click to upload or drag and drop</p>
                                <p style="font-size: 11px; margin-top: 4px;">JPG, PNG, or PDF (Max 5MB)</p>
                                <input type="file" name="id_file" id="id_file" accept=".jpg,.jpeg,.png,.pdf" required>
                            </div>
                            <div class="file-name" id="fileName"></div>
                            <div class="error-message" id="id_file_error">Please upload your ID document</div>
                        </div>
                    </div>
                </div>

                <!-- Section 4: Security -->
                <div class="form-section" data-section="4">
                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label class="required">Password</label>
                            <input type="password" name="password" id="password" required>
                            <div class="error-message" id="password_error">Please enter a valid password</div>
                            <div class="password-requirements">
                                <p>Password must contain:</p>
                                <div class="requirement" id="req-length"><i class="fas fa-circle"></i> At least 8
                                    characters</div>
                                <div class="requirement" id="req-upper"><i class="fas fa-circle"></i> Uppercase letter
                                    (A-Z)</div>
                                <div class="requirement" id="req-lower"><i class="fas fa-circle"></i> Lowercase letter
                                    (a-z)</div>
                                <div class="requirement" id="req-number"><i class="fas fa-circle"></i> Number (0-9)
                                </div>
                                <div class="requirement" id="req-special"><i class="fas fa-circle"></i> Special
                                    character (!@#$%^&*)</div>
                            </div>
                        </div>
                        <div class="form-group full-width">
                            <label class="required">Confirm Password</label>
                            <input type="password" name="confirm_password" id="confirm_password" required>
                            <div class="error-message" id="confirm_error">Passwords do not match</div>
                        </div>
                    </div>
                </div>

                <!-- Form Navigation Buttons -->
                <div class="form-buttons">
                    <button type="button" class="btn-prev" id="prevBtn" style="display: none;">Previous</button>
                    <button type="button" class="btn-next" id="nextBtn">Next</button>
                    <button type="submit" class="btn-submit" id="submitBtn" style="display: none;">Submit
                        Application</button>
                </div>
            </form>

            <div class="login-link">
                Already have an account? <a href="login.php">Sign in</a>
            </div>
        </div>
    </div>

    <script>
        // Multi-step form navigation
        let currentStep = 1;
        const totalSteps = 4;

        const sections = document.querySelectorAll('.form-section');
        const steps = document.querySelectorAll('.step');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const submitBtn = document.getElementById('submitBtn');

        function updateSteps() {
            sections.forEach((section, index) => {
                if (index + 1 === currentStep) {
                    section.classList.add('active');
                } else {
                    section.classList.remove('active');
                }
            });

            steps.forEach((step, index) => {
                const stepNum = index + 1;
                if (stepNum < currentStep) {
                    step.classList.add('completed');
                    step.classList.remove('active');
                    step.querySelector('.step-number').innerHTML = '<i class="fas fa-check"></i>';
                } else if (stepNum === currentStep) {
                    step.classList.add('active');
                    step.classList.remove('completed');
                    step.querySelector('.step-number').innerHTML = stepNum;
                } else {
                    step.classList.remove('active', 'completed');
                    step.querySelector('.step-number').innerHTML = stepNum;
                }
            });

            if (currentStep === 1) {
                prevBtn.style.display = 'none';
            } else {
                prevBtn.style.display = 'block';
            }

            if (currentStep === totalSteps) {
                nextBtn.style.display = 'none';
                submitBtn.style.display = 'block';
            } else {
                nextBtn.style.display = 'block';
                submitBtn.style.display = 'none';
            }
        }

        function validateStep(step) {
            const currentSection = document.querySelector(`.form-section[data-section="${step}"]`);
            const inputs = currentSection.querySelectorAll('input, select');
            let isValid = true;

            inputs.forEach(input => {
                if (input.required && !input.value.trim()) {
                    isValid = false;
                    const errorDiv = document.getElementById(`${input.id}_error`);
                    if (errorDiv) errorDiv.classList.add('show');
                    input.classList.add('error');
                } else {
                    const errorDiv = document.getElementById(`${input.id}_error`);
                    if (errorDiv) errorDiv.classList.remove('show');
                    input.classList.remove('error');
                }
            });

            if (step === 1) {
                const age = document.getElementById('age').value;
                const birthYear = document.getElementById('birth_year').value;
                const currentYear = new Date().getFullYear();

                if (age && birthYear) {
                    const calculatedAge = currentYear - parseInt(birthYear);
                    if (Math.abs(calculatedAge - parseInt(age)) > 1) {
                        isValid = false;
                        document.getElementById('age_error').textContent = 'Age doesn\'t match birth year';
                        document.getElementById('age_error').classList.add('show');
                    }
                }
            }

            if (step === 4) {
                const password = document.getElementById('password').value;
                const confirm = document.getElementById('confirm_password').value;

                if (password !== confirm) {
                    isValid = false;
                    document.getElementById('confirm_error').classList.add('show');
                }

                const isStrong = validatePasswordStrength(password);
                if (!isStrong) {
                    isValid = false;
                }
            }

            return isValid;
        }

        function validatePasswordStrength(password) {
            const requirements = {
                length: password.length >= 8,
                upper: /[A-Z]/.test(password),
                lower: /[a-z]/.test(password),
                number: /[0-9]/.test(password),
                special: /[!@#$%^&*]/.test(password)
            };

            document.getElementById('req-length').classList.toggle('valid', requirements.length);
            document.getElementById('req-upper').classList.toggle('valid', requirements.upper);
            document.getElementById('req-lower').classList.toggle('valid', requirements.lower);
            document.getElementById('req-number').classList.toggle('valid', requirements.number);
            document.getElementById('req-special').classList.toggle('valid', requirements.special);

            return Object.values(requirements).every(v => v === true);
        }

        nextBtn.addEventListener('click', () => {
            if (validateStep(currentStep)) {
                currentStep++;
                updateSteps();
            }
        });

        prevBtn.addEventListener('click', () => {
            if (currentStep > 1) {
                currentStep--;
                updateSteps();
            }
        });

        // Real-time password validation
        const passwordInput = document.getElementById('password');
        const confirmInput = document.getElementById('confirm_password');

        if (passwordInput) {
            passwordInput.addEventListener('input', () => {
                validatePasswordStrength(passwordInput.value);
                if (confirmInput.value) {
                    if (passwordInput.value === confirmInput.value) {
                        document.getElementById('confirm_error').classList.remove('show');
                    } else {
                        document.getElementById('confirm_error').classList.add('show');
                    }
                }
            });
        }

        if (confirmInput) {
            confirmInput.addEventListener('input', () => {
                if (passwordInput.value === confirmInput.value) {
                    document.getElementById('confirm_error').classList.remove('show');
                } else {
                    document.getElementById('confirm_error').classList.add('show');
                }
            });
        }

        // File upload handling
        const fileInput = document.getElementById('id_file');
        const fileUpload = document.getElementById('fileUpload');
        const fileName = document.getElementById('fileName');

        if (fileInput) {
            fileUpload.addEventListener('click', () => {
                fileInput.click();
            });

            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    const file = e.target.files[0];
                    fileName.textContent = `Selected: ${file.name}`;
                    fileName.style.display = 'block';
                    document.getElementById('id_file_error').classList.remove('show');
                } else {
                    fileName.style.display = 'none';
                }
            });
        }

        // Real-time validation for inputs
        const allInputs = document.querySelectorAll('input, select');
        allInputs.forEach(input => {
            input.addEventListener('input', () => {
                if (input.value.trim()) {
                    const errorDiv = document.getElementById(`${input.id}_error`);
                    if (errorDiv) errorDiv.classList.remove('show');
                    input.classList.remove('error');
                }
            });
        });

        // Age and birth year validation
        const ageInput = document.getElementById('age');
        const birthYearInput = document.getElementById('birth_year');
        const currentYear = new Date().getFullYear();

        if (ageInput && birthYearInput) {
            birthYearInput.addEventListener('input', () => {
                if (birthYearInput.value) {
                    const calculatedAge = currentYear - parseInt(birthYearInput.value);
                    if (calculatedAge >= 18 && calculatedAge <= 120) {
                        ageInput.value = calculatedAge;
                    }
                }
            });
        }

        // Phone number real-time validation
        const phoneInput = document.getElementById('phone');
        if (phoneInput) {
            phoneInput.addEventListener('input', () => {
                const phonePattern = /^[\+]?[(]?[0-9]{1,4}[)]?[-\s\.]?[(]?[0-9]{1,4}[)]?[-\s\.]?[0-9]{4,10}$/;
                if (phoneInput.value && !phonePattern.test(phoneInput.value)) {
                    document.getElementById('phone_error').classList.add('show');
                } else {
                    document.getElementById('phone_error').classList.remove('show');
                }
            });
        }

        // Form submission loading state
        const registerForm = document.getElementById('registerForm');
        const submitButton = document.getElementById('submitBtn');

        if (registerForm) {
            registerForm.addEventListener('submit', () => {
                submitButton.classList.add('loading');
                submitButton.disabled = true;
            });
        }

        // Initialize
        updateSteps();
    </script>
</body>

</html>