<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Registration</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;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>
        :root {
            --primary-color: #d03f4d;
            --secondary-color: #3a506b;
            --light-color: #f5f7fa;
            --dark-color: #1c2541;
        }
        body { 
            font-family: 'Roboto', sans-serif; 
            background: var(--light-color); 
            color: #333;
        }
        .header {
            background: white;
            padding: 15px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .logo-container {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .card { 
            border-radius: 15px; 
            box-shadow: 0 8px 25px rgba(0,0,0,0.1); 
            padding: 30px; 
            margin: 30px 0;
            border: none;
        }
        h2 { 
            color: var(--primary-color); 
            margin-bottom: 25px; 
            font-weight: 700; 
            text-align: center;
        }
        .form-control { 
            border-radius: 8px; 
            padding: 12px 15px;
            margin-bottom: 15px; 
            border: 1px solid #ddd;
            transition: all 0.3s;
        }
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(208, 63, 77, 0.2);
        }
        .form-label {
            font-weight: 500;
            margin-bottom: 5px;
            color: var(--secondary-color);
        }
        .btn-primary { 
            background: var(--primary-color); 
            border: none;
            border-radius: 8px; 
            padding: 12px; 
            font-weight: 600; 
            width: 100%; 
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background: #b02a37;
            transform: translateY(-2px);
        }
        .upload-container {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: border-color 0.3s;
            background: #f9f9f9;
            margin-bottom: 20px;
        }
        .upload-container:hover {
            border-color: var(--primary-color);
            background: #f0f0f0;
        }
        .upload-label { 
            display: block; 
            margin-bottom: 10px; 
            font-weight: 500; 
            color: var(--secondary-color);
        }
        .preview-img { 
            margin-top: 10px; 
            width: 120px; 
            height: 120px;
            border-radius: 50%; 
            border: 3px solid #ddd;
            object-fit: cover;
        }
        .section-title {
            color: var(--secondary-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
            margin: 25px 0 15px;
            font-weight: 600;
        }
        .required-field::after {
            content: " *";
            color: var(--primary-color);
        }
        .form-note {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: -10px;
            margin-bottom: 15px;
        }
        .alert {
            border-radius: 8px;
            padding: 12px 15px;
        }
        .password-toggle {
            position: relative;
        }
        .password-toggle-icon {
            position: absolute;
            right: 15px;
            top: 42px;
            cursor: pointer;
            color: #6c757d;
        }
        .progress {
            height: 8px;
            margin-top: 10px;
            display: none;
        }
        .upload-status {
            font-size: 0.85rem;
            margin-top: 5px;
            display: none;
        }
    </style>
</head>
<body>
<div class="header">
    <div class="container">
        <div class="logo-container">
            <img src="logo.png" alt="" width="120">
        </div>
    </div>
</div>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-10 col-lg-8">
            <div class="card">
                <h2><i class="fas fa-user-graduate me-2"></i>Student Registration</h2>

                <?php
                require __DIR__ . '/email/class.phpmailer.php';
                require __DIR__ . '/email/class.smtp.php';
                include "students/include/config.php";
                include "imagekit/vendor/autoload.php";
                
                use ImageKit\ImageKit;
                
                // Initialize ImageKit
                $imageKit = new ImageKit(
                    "public_EypymL+l9sKGk/JHnWApsJ94ybA=",
                    "private_T5LPQkxAMv70EVlUDk+RyUU3h5w=",
                    "https://ik.imagekit.io/zamastudents"
                );

                $programs = $conn->query("SELECT id, program FROM programs");
                $intakes  = $conn->query("SELECT id, intake FROM intake");

                // Process form data when form is submitted
                if ($_SERVER["REQUEST_METHOD"] == "POST") {
                    // Collect and sanitize input values
                    $studentname     = $conn->real_escape_string($_POST['studentname']);
                    $studentid       = $conn->real_escape_string($_POST['studentid']);
                    $parent_name     = $conn->real_escape_string($_POST['parent_name']);
                    $parent_mobile   = $conn->real_escape_string($_POST['parent_mobile']);
                    $parent_email    = $conn->real_escape_string($_POST['parent_email']);
                    $parent_relation = $conn->real_escape_string($_POST['parent_relation']);
                    $intake          = $conn->real_escape_string($_POST['intake']);
                    $gender          = $conn->real_escape_string($_POST['gender']);
                    $start_year      = $conn->real_escape_string($_POST['start_year']);
                    $end_year        = $conn->real_escape_string($_POST['end_year']);
                    $program         = $conn->real_escape_string($_POST['program']);
                    $mobile          = $conn->real_escape_string($_POST['mobile']);
                    $email           = $conn->real_escape_string($_POST['email']);
                    $pass            = password_hash($_POST['pass'], PASSWORD_DEFAULT);
                    $boarding_status = $conn->real_escape_string($_POST['boarding_status']);
                    $hostel_name     = $conn->real_escape_string($_POST['hostel_name']);
                    $room_number     = $conn->real_escape_string($_POST['room_number']);
                    $mode            = $conn->real_escape_string($_POST['mode']);
                    $status          = "Active"; // Default status
                    
                    // Handle file upload to ImageKit
                    $image_url = 'https://ik.imagekit.io/zamastudents/students/default.png';
                    
                    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0 && !empty($_FILES['image']['name'])) {
                        $check = getimagesize($_FILES["image"]["tmp_name"]);
                        if ($check !== false) {
                            try {
                                // Upload image using ImageKit SDK
                                $upload = $imageKit->upload([
                                    'file' => fopen($_FILES['image']['tmp_name'], 'r'),
                                    'fileName' => 'student_' . $studentid . '_' . time() . '_' . uniqid(),
                                    'folder' => '/students/',
                                    'useUniqueFileName' => true
                                ]);
                                
                                if (isset($upload->error)) {
                                    echo "<div class='alert alert-warning'><i class='fas fa-exclamation-triangle me-2'></i>Image upload failed: " . $upload->error->message . ". Using default image.</div>";
                                } else {
                                    $image_url = $upload->result->url;
                                    echo "<div class='alert alert-success'><i class='fas fa-check-circle me-2'></i>Profile image uploaded successfully to ImageKit!</div>";
                                }
                            } catch (Exception $e) {
                                echo "<div class='alert alert-warning'><i class='fas fa-exclamation-triangle me-2'></i>Image upload failed: " . $e->getMessage() . ". Using default image.</div>";
                            }
                        } else {
                            echo "<div class='alert alert-warning'><i class='fas fa-exclamation-triangle me-2'></i>Invalid image file. Using default image.</div>";
                        }
                    }

                    // Check if student ID already exists
                    $check_sql = "SELECT id FROM students WHERE studentid = ? OR email = ?";
                    $check_stmt = $conn->prepare($check_sql);
                    $check_stmt->bind_param("ss", $studentid, $email);
                    $check_stmt->execute();
                    $check_result = $check_stmt->get_result();

                    if ($check_result->num_rows > 0) {
                        echo "<div class='alert alert-danger'><i class='fas fa-exclamation-circle me-2'></i>Error: Student ID or Email already exists.</div>";
                        $check_stmt->close();
                    } else {
                        $check_stmt->close();
                        
                        // Insert new student with ImageKit URL
                        $sql = "INSERT INTO students 
                            (image, studentid, studentname, parent_name, parent_mobile, parent_email, 
                            parent_relation, intake, gender, start_year, end_year, program, 
                            mobile, email, pass, status, boarding_status, hostel_name, room_number, mode) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        
                        $stmt = $conn->prepare($sql);
                        if (!$stmt) {
                            echo "<div class='alert alert-danger'><i class='fas fa-exclamation-circle me-2'></i>Prepare failed: " . $conn->error . "</div>";
                        } else {
                            // Bind parameters for 20 columns (21 total including auto-increment id)
                            $stmt->bind_param(
                                "ssssssssssssssssssss",
                                $image_url, $studentid, $studentname, $parent_name, $parent_mobile, $parent_email, 
                                $parent_relation, $intake, $gender, $start_year, $end_year, $program, 
                                $mobile, $email, $pass, $status, $boarding_status, $hostel_name, $room_number, $mode
                            );

                            if ($stmt->execute()) {
                                $last_id = $stmt->insert_id;
                                $affected_rows = $stmt->affected_rows;
                                
                                echo "<div class='alert alert-success'><i class='fas fa-check-circle me-2'></i>Registration successful! Student ID: $studentid</div>";
                                echo "<div class='alert alert-info'><i class='fas fa-info-circle me-2'></i>Database Insert ID: $last_id, Rows affected: $affected_rows</div>";

                                // Send confirmation email with ImageKit image
                                $mail = new PHPMailer(true);
                                try {
                                    $mail->isSMTP();
                                    include "email_config.php";

                                    $mail->addAddress($email, $studentname);

                                    $mail->isHTML(true);
                                    $mail->Subject = 'Registration Successful - Unicohs University';
                                    $mail->Body    = "
                                        <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                                            <div style='text-align: center; margin-bottom: 20px;'>
                                                <img src='{$image_url}?tr=w-150,h-150,fo-face' alt='Profile Image' style='width: 150px; height: 150px; border-radius: 50%; object-fit: cover; border: 3px solid #d03f4d;'>
                                            </div>
                                            <h2 style='color: #d03f4d; text-align: center;'>Welcome to Unicohs University!</h2>
                                            <p>Dear <strong>$studentname</strong>,</p>
                                            <p>Your registration has been successfully received and your account has been created.</p>
                                            
                                            <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;'>
                                                <h4 style='color: #3a506b; margin-bottom: 10px;'>Account Details:</h4>
                                                <p><strong>Student ID:</strong> $studentid</p>
                                                <p><strong>Email:</strong> $email</p>
                                                <p><strong>Program:</strong> $program</p>
                                                <p><strong>Intake:</strong> $intake</p>
                                                <p><strong>Mode:</strong> $mode</p>
                                                <p><strong>Status:</strong> $status</p>
                                            </div>
                                            
                                            <div style='background: #fff3cd; padding: 15px; border-radius: 8px; margin: 20px 0; border: 1px solid #ffeaa7;'>
                                                <h4 style='color: #856404; margin-bottom: 10px;'>Login Instructions:</h4>
                                                <p>You can now login to your student portal using:</p>
                                                <p><strong>URL:</strong> https://yourdomain.com/students/login/</p>
                                                <p><strong>Username:</strong> Your email or student ID</p>
                                                <p><strong>Password:</strong> The password you created during registration</p>
                                            </div>
                                            
                                            <p>If you have any questions or need assistance, please contact our support team.</p>
                                            
                                            <hr style='border: none; border-top: 2px solid #eee; margin: 20px 0;'>
                                            
                                            <p style='text-align: center; color: #6c757d; font-size: 0.9em;'>
                                                Best regards,<br>
                                                <strong>Unicohs University Administration</strong>
                                            </p>
                                        </div>
                                    ";
                                    
                                    if ($mail->send()) {
                                        echo "<div class='alert alert-success'><i class='fas fa-check-circle me-2'></i>Confirmation email sent successfully!</div>";
                                    }
                                } catch (Exception $e) {
                                    echo "<div class='alert alert-warning'>Email could not be sent. Mailer Error: {$mail->ErrorInfo}</div>";
                                }
                            } else {
                                echo "<div class='alert alert-danger'><i class='fas fa-exclamation-circle me-2'></i>Error executing query: " . $stmt->error . "</div>";
                            }

                            $stmt->close();
                        }
                    }
                }
                ?>

                <form method="post" enctype="multipart/form-data" id="registrationForm">
                    <h4 class="section-title"><i class="fas fa-id-card me-2"></i>Personal Information</h4>
                    
                    <div class="text-center mb-4">
                        <label class="upload-container" for="imageInput">
                            <span class="upload-label"><i class="fas fa-cloud-upload-alt me-2"></i>Upload Profile Image</span>
                            <img id="preview" class="preview-img" src="https://ik.imagekit.io/zamastudents/students/default.png?tr=w-120,h-120,fo-face" alt="Image Preview">
                            <div class="mt-2">Click to upload or drag and drop</div>
                            <div class="form-note">JPG, PNG, GIF, or WebP. Max 5MB. Image will be stored on ImageKit CDN.</div>
                            <input hidden type="file" name="image" id="imageInput" accept="image/*" class="form-control" onchange="previewImage(event)">
                        </label>
                        <div class="progress" id="uploadProgress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
                        </div>
                        <div class="upload-status" id="uploadStatus"></div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Full Name</label>
                            <input type="text" name="studentname" placeholder="Enter your full name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label required-field">Student ID</label>
                            <input type="text" name="studentid" placeholder="Enter student ID" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Gender</label>
                            <select name="gender" class="form-control" required>
                                <option value="">-- Select Gender --</option>
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label required-field">Mobile Number</label>
                            <input type="text" name="mobile" placeholder="Enter mobile number" class="form-control" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Email Address</label>
                            <input type="email" name="email" placeholder="Enter email address" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label required-field">Mode Of Study</label>
                            <select name="mode" class="form-control" required>
                                <option value="">-- Select Mode --</option>
                                <option value="Fulltime">Fulltime</option>
                                <option value="Distance">Distance</option>
                                <option value="Online">Online</option>
                            </select>
                        </div>
                    </div>

                    <h4 class="section-title"><i class="fas fa-graduation-cap me-2"></i>Academic Information</h4>
                    
                    <div class="row">
                        <div class="col-md-6"> 
                            <label class="form-label required-field">Program</label>
                            <select name="program" required class="form-control">
                                <option value="">-- Select Program --</option>
                                <?php 
                                if ($programs) {
                                    while($row = $programs->fetch_assoc()) { ?>
                                        <option value="<?= htmlspecialchars($row['program']); ?>"><?= htmlspecialchars($row['program']); ?></option>
                                    <?php }
                                } else {
                                    echo "<option value=''>No programs found</option>";
                                }
                                ?>
                            </select> 
                        </div>            
                        
                        <div class="col-md-6"> 
                            <label class="form-label required-field">Intake</label>
                            <select name="intake" required class="form-control">
                                <option value="">-- Select Intake --</option>
                                <?php 
                                if ($intakes) {
                                    while($row = $intakes->fetch_assoc()) { ?>
                                        <option value="<?= htmlspecialchars($row['intake']); ?>"><?= htmlspecialchars($row['intake']); ?></option>
                                    <?php }
                                } else {
                                    echo "<option value=''>No intakes found</option>";
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Start Year</label>
                            <input type="number" name="start_year" placeholder="Enter start year" min="2000" max="2100" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label required-field">End Year</label>
                            <input type="number" name="end_year" placeholder="Enter end year" min="2000" max="2100" class="form-control" required>
                        </div>
                    </div>
                    
                    <h4 class="section-title"><i class="fas fa-bed me-2"></i>Boarding Information</h4>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">Boarding Status</label>
                            <select name="boarding_status" class="form-control">
                                <option value="">-- Select Status --</option>
                                <option value="Campus BH">Campus Boarding House</option>
                                <option value="Off Campus BH">Off Campus Boarding House</option>
                                <option value="Day Scholar">Day Scholar</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Hostel Name</label>
                            <input type="text" name="hostel_name" placeholder="Hostel Name (if applicable)" class="form-control">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label">Room Number</label>
                            <input type="text" name="room_number" placeholder="Enter room number" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <div class="form-note" style="margin-top: 35px;">Leave blank if not applicable</div>
                        </div>
                    </div>

                    <h4 class="section-title"><i class="fas fa-users me-2"></i>Parent/Guardian Information</h4>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Parent/Guardian Name</label>
                            <input type="text" name="parent_name" placeholder="Enter full name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label required-field">Relationship</label>
                            <select name="parent_relation" class="form-control" required>
                                <option value="">-- Select Relationship --</option>
                                <option value="Father">Father</option>
                                <option value="Mother">Mother</option>
                                <option value="Guardian">Guardian</option>
                                <option value="Wife">Wife</option>
                                <option value="Husband">Husband</option>
                                <option value="Sister">Sister</option>
                                <option value="Brother">Brother</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label required-field">Parent Mobile Number</label>
                            <input type="text" name="parent_mobile" placeholder="Enter mobile number" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Parent Email</label>
                            <input type="email" name="parent_email" placeholder="Optional" class="form-control">
                        </div>
                    </div>

                    <h4 class="section-title"><i class="fas fa-lock me-2"></i>Account Details</h4>
                    
                    <div class="row">
                        <div class="col-md-12 password-toggle">
                            <label class="form-label required-field">Password</label>
                            <input type="password" name="pass" id="password" placeholder="Create a secure password" class="form-control" required minlength="8">
                            <span class="password-toggle-icon" onclick="togglePassword()">
                                <i class="fas fa-eye" id="toggleIcon"></i>
                            </span>
                            <div class="form-note">Use at least 8 characters with a mix of letters, numbers and symbols</div>
                            <div class="password-strength mt-2">
                                <div class="progress" style="height: 5px;">
                                    <div class="progress-bar" id="passwordStrength" role="progressbar" style="width: 0%"></div>
                                </div>
                                <small id="passwordStrengthText" class="text-muted"></small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <label class="form-label required-field">Confirm Password</label>
                            <input type="password" name="confirm_pass" id="confirm_password" placeholder="Confirm your password" class="form-control" required minlength="8">
                            <div class="form-note">Please re-enter your password to confirm</div>
                            <div id="passwordMatch" class="mt-2"></div>
                        </div>
                    </div>
                    
                    <div class="form-check mt-3">
                        <input class="form-check-input" type="checkbox" id="terms" required>
                        <label class="form-check-label" for="terms">
                            I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms and Conditions</a> and <a href="#" data-bs-toggle="modal" data-bs-target="#privacyModal">Privacy Policy</a>
                        </label>
                    </div>
                    
                    <button type="submit" name="register" class="btn btn-primary mt-4" id="submitBtn">
                        <i class="fas fa-user-plus me-2"></i>Complete Registration
                    </button>
                </form>
                
                <!-- Debug: Test Database Connection -->
                <div class="mt-4">
                    <?php
                    // Test database connection and structure
                    if ($conn) {
                        echo "<div class='alert alert-info'><i class='fas fa-database me-2'></i>Database connected successfully.</div>";
                        
                        // Check students table structure
                        $result = $conn->query("DESCRIBE students");
                        if ($result) {
                            echo "<div class='alert alert-info'><i class='fas fa-table me-2'></i>Students table structure: <br><small>";
                            $columns = [];
                            while ($row = $result->fetch_assoc()) {
                                $columns[] = $row['Field'];
                                echo $row['Field'] . " (" . $row['Type'] . ")<br>";
                            }
                            echo "</small></div>";
                            echo "<div class='alert alert-info'><i class='fas fa-list me-2'></i>Total columns: " . count($columns) . "</div>";
                        } else {
                            echo "<div class='alert alert-danger'><i class='fas fa-exclamation-circle me-2'></i>Error describing students table: " . $conn->error . "</div>";
                        }
                    } else {
                        echo "<div class='alert alert-danger'><i class='fas fa-exclamation-circle me-2'></i>Database connection failed!</div>";
                    }
                    ?>
                </div>
                
                <!-- Terms Modal -->
                <div class="modal fade" id="termsModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Terms and Conditions</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <p>Terms and conditions content here...</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Privacy Modal -->
                <div class="modal fade" id="privacyModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Privacy Policy</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <p>Privacy policy content here...</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-3">
                    <p>Already have an account? <a href="students/login/index.php">Login here</a></p>
                    <p>Download <a href="https://unicohsuniversity.com/Unicohsportal.apk">Mobile App</a></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
function previewImage(event) {
    const reader = new FileReader();
    reader.onload = function() {
        const img = document.getElementById('preview');
        img.src = reader.result;
        
        // Show upload progress
        document.getElementById('uploadProgress').style.display = 'block';
        document.getElementById('uploadStatus').style.display = 'block';
        document.getElementById('uploadStatus').innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing image...';
        document.getElementById('uploadStatus').className = 'upload-status text-info';
        
        // Simulate processing
        setTimeout(() => {
            document.getElementById('uploadProgress').style.display = 'none';
            document.getElementById('uploadStatus').innerHTML = '<i class="fas fa-check-circle me-2 text-success"></i>Image ready for upload';
            document.getElementById('uploadStatus').className = 'upload-status text-success';
        }, 1000);
    }
    reader.readAsDataURL(event.target.files[0]);
}

function togglePassword() {
    const passwordInput = document.getElementById('password');
    const confirmInput = document.getElementById('confirm_password');
    const toggleIcon = document.getElementById('toggleIcon');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        confirmInput.type = 'text';
        toggleIcon.classList.remove('fa-eye');
        toggleIcon.classList.add('fa-eye-slash');
    } else {
        passwordInput.type = 'password';
        confirmInput.type = 'password';
        toggleIcon.classList.remove('fa-eye-slash');
        toggleIcon.classList.add('fa-eye');
    }
}

// Password strength checker
function checkPasswordStrength(password) {
    let strength = 0;
    let text = '';
    let color = '';
    
    if (password.length >= 8) strength++;
    if (password.match(/[a-z]+/)) strength++;
    if (password.match(/[A-Z]+/)) strength++;
    if (password.match(/[0-9]+/)) strength++;
    if (password.match(/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/)) strength++;
    
    switch(strength) {
        case 0:
        case 1:
            text = 'Very Weak';
            color = '#dc3545';
            break;
        case 2:
            text = 'Weak';
            color = '#fd7e14';
            break;
        case 3:
            text = 'Good';
            color = '#ffc107';
            break;
        case 4:
            text = 'Strong';
            color = '#28a745';
            break;
        case 5:
            text = 'Very Strong';
            color = '#20c997';
            break;
    }
    
    const percentage = (strength / 5) * 100;
    return { percentage, text, color };
}

// Password match checker
function checkPasswordMatch() {
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    const matchDiv = document.getElementById('passwordMatch');
    
    if (confirmPassword === '') {
        matchDiv.innerHTML = '';
        return;
    }
    
    if (password === confirmPassword) {
        matchDiv.innerHTML = '<i class="fas fa-check-circle text-success me-2"></i>Passwords match';
        matchDiv.className = 'text-success';
    } else {
        matchDiv.innerHTML = '<i class="fas fa-times-circle text-danger me-2"></i>Passwords do not match';
        matchDiv.className = 'text-danger';
    }
}

// Add event listeners
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('registrationForm');
    const passwordInput = document.getElementById('password');
    const confirmInput = document.getElementById('confirm_password');
    const submitBtn = document.getElementById('submitBtn');
    
    // Password strength real-time update
    passwordInput.addEventListener('input', function() {
        const strength = checkPasswordStrength(this.value);
        const strengthBar = document.getElementById('passwordStrength');
        const strengthText = document.getElementById('passwordStrengthText');
        
        strengthBar.style.width = strength.percentage + '%';
        strengthBar.style.backgroundColor = strength.color;
        strengthText.textContent = 'Strength: ' + strength.text;
        strengthText.style.color = strength.color;
        
        checkPasswordMatch();
    });
    
    // Password match real-time update
    confirmInput.addEventListener('input', checkPasswordMatch);
    
    // Form validation
    form.addEventListener('submit', function(e) {
        const password = passwordInput.value;
        const confirmPassword = confirmInput.value;
        const terms = document.getElementById('terms').checked;
        
        if (!terms) {
            e.preventDefault();
            alert('You must agree to the Terms and Conditions and Privacy Policy.');
            return false;
        }
        
        if (password !== confirmPassword) {
            e.preventDefault();
            alert('Passwords do not match. Please try again.');
            return false;
        }
        
        if (password.length < 8) {
            e.preventDefault();
            alert('Password must be at least 8 characters long.');
            return false;
        }
        
        // Show loading state
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing...';
        submitBtn.disabled = true;
    });
    
    // Image upload validation
    const imageInput = document.getElementById('imageInput');
    imageInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // Check file size (max 5MB)
            if (file.size > 5 * 1024 * 1024) {
                alert('File size must be less than 5MB');
                this.value = '';
                return;
            }
            
            // Check file type
            const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                alert('Please upload a valid image file (JPG, PNG, GIF, or WebP)');
                this.value = '';
                return;
            }
        }
    });
});

// Drag and drop functionality for image upload
const uploadContainer = document.querySelector('.upload-container');
const fileInput = document.querySelector('input[type="file"]');

uploadContainer.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadContainer.style.borderColor = '#d03f4d';
    uploadContainer.style.backgroundColor = '#f0f0f0';
});

uploadContainer.addEventListener('dragleave', () => {
    uploadContainer.style.borderColor = '#ccc';
    uploadContainer.style.backgroundColor = '#f9f9f9';
});

uploadContainer.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadContainer.style.borderColor = '#ccc';
    uploadContainer.style.backgroundColor = '#f9f9f9';
    
    if (e.dataTransfer.files.length) {
        fileInput.files = e.dataTransfer.files;
        previewImage({ target: { files: e.dataTransfer.files } });
    }
});
</script>
</body>
</html>