<?php
include('session_validator.php');
include('includes/db_pdo.php');

// Initialize alert arrays for toast notifications
$alert = [
    'type' => '',
    'title' => '',
    'message' => ''
];

// Get current academic year
$current_year_sql = "SELECT ay_ad FROM academic_years WHERE status = 'active' LIMIT 1";
$current_year_result = $conn->query($current_year_sql);
$current_academic_year = '';
if ($current_year_result->rowCount() > 0) {
    $current_year = $current_year_result->fetch(PDO::FETCH_ASSOC);
    $current_academic_year = $current_year['ay_ad'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate required fields
        $required_fields = ['regd_id', 'name', 'gender', 'dob', 'class_id', 'parent_name'];
        foreach ($required_fields as $field) {
            if (empty(trim($_POST[$field]))) {
                throw new Exception("Please fill all required fields.");
            }
        }
        
        $conn->beginTransaction();
        
        // Collect and sanitize form data
        $regd_id = trim($_POST['regd_id']);
        $symbol_no = trim($_POST['symbol_no'] ?? '');
        $name = trim($_POST['name']);
        $gender = $_POST['gender'];
        $dob = $_POST['dob'];
        $address = trim($_POST['address']);
        $phone = trim($_POST['phone']);
        $email = trim($_POST['email'] ?? '');
        $parent_name = trim($_POST['parent_name']);
        $parent_phone = trim($_POST['parent_phone']);
        $std_group = $_POST['std_group'] ?? '';
        $registration_no = trim($_POST['registration_no'] ?? '');
        $class_id = $_POST['class_id'];
        $section_id = $_POST['section_id'] ?? null;
        $remarks = trim($_POST['remarks'] ?? '');
        
        // Validate email if provided
        if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new Exception("Please enter a valid email address.");
        }
        
        // Validate phone numbers if provided
        if ($phone && !preg_match('/^\d{10}$/', $phone)) {
            throw new Exception("Please enter a valid 10-digit phone number.");
        }
        
        if ($parent_phone && !preg_match('/^\d{10}$/', $parent_phone)) {
            throw new Exception("Please enter a valid 10-digit parent phone number.");
        }
        
        // Check if registration ID already exists
        $check_sql = "SELECT student_id FROM students WHERE regd_id = :regd_id";
        $check_stmt = $conn->prepare($check_sql);
        $check_stmt->execute([':regd_id' => $regd_id]);
        
        if ($check_stmt->rowCount() > 0) {
            throw new Exception("Registration ID '$regd_id' already exists. Please use a different ID.");
        }
        
        // Get class information
        $class_sql = "SELECT class, class_numeric FROM classes WHERE class_id = :class_id";
        $class_stmt = $conn->prepare($class_sql);
        $class_stmt->execute([':class_id' => $class_id]);
        
        if ($class_stmt->rowCount() == 0) {
            throw new Exception("Selected class does not exist.");
        }
        
        $class_info = $class_stmt->fetch(PDO::FETCH_ASSOC);
        $class_name = $class_info['class'];
        $class_numeric = $class_info['class_numeric'];
        
        // Handle photo upload
        $photo = '';
        if (isset($_FILES['photo']) && $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
            $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
            $max_size = 2 * 1024 * 1024; // 2MB
            
            $file_type = $_FILES['photo']['type'];
            $file_size = $_FILES['photo']['size'];
            
            if (!in_array($file_type, $allowed_types)) {
                throw new Exception("Invalid file type. Only JPG, PNG, and GIF images are allowed.");
            }
            
            if ($file_size > $max_size) {
                throw new Exception("File size exceeds 2MB limit.");
            }
            
            // Generate unique filename
            $ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
            $photo = 'student_' . time() . '_' . preg_replace('/[^a-zA-Z0-9]/', '_', $regd_id) . '.' . $ext;
            $upload_path = 'uploads/students/' . $photo;
            
            // Create upload directory if it doesn't exist
            if (!is_dir('uploads/students')) {
                mkdir('uploads/students', 0755, true);
            }
            
            if (!move_uploaded_file($_FILES['photo']['tmp_name'], $upload_path)) {
                throw new Exception("Failed to upload photo. Please try again.");
            }
        }
        
        // Insert student into students table
        $student_sql = "INSERT INTO students (
            regd_id, symbol_no, name, gender, dob, address, phone, email, 
            parent_name, parent_phone, class, class_numeric, Class_id, std_group, registration_no, 
            photo, status, created_at
        ) VALUES (
            :regd_id, :symbol_no, :name, :gender, :dob, :address, :phone, :email, 
            :parent_name, :parent_phone, :class, :class_numeric, :class_id, :std_group, :registration_no, 
            :photo, 'active', NOW()
        )";
        
        $student_stmt = $conn->prepare($student_sql);
        $student_stmt->execute([
            ':regd_id' => $regd_id,
            ':symbol_no' => $symbol_no,
            ':name' => $name,
            ':gender' => $gender,
            ':dob' => $dob,
            ':address' => $address,
            ':phone' => $phone,
            ':email' => $email,
            ':parent_name' => $parent_name,
            ':parent_phone' => $parent_phone,
            ':class' => $class_name,
            ':class_numeric' => $class_numeric,
            ':class_id' => $class_id,
            ':std_group' => $std_group,
            ':registration_no' => $registration_no,
            ':photo' => $photo
        ]);
        
        $student_id = $conn->lastInsertId();
        
        // If section is selected, add to student_class_section_data
        if ($section_id && $section_id != '' && $current_academic_year) {
            // Verify section exists for this class
            $verify_section_sql = "SELECT section_id FROM sections WHERE section_id = :section_id AND class_id = :class_id";
            $verify_section_stmt = $conn->prepare($verify_section_sql);
            $verify_section_stmt->execute([':section_id' => $section_id, ':class_id' => $class_id]);
            
            if ($verify_section_stmt->rowCount() > 0) {
                $section_sql = "INSERT INTO student_class_section_data 
                               (student_id, class_id, section_id, academic_year, status, remarks, created_at, updated_at) 
                               VALUES (:student_id, :class_id, :section_id, :academic_year, 'active', :remarks, NOW(), NOW())";
                
                $section_stmt = $conn->prepare($section_sql);
                $section_stmt->execute([
                    ':student_id' => $student_id,
                    ':class_id' => $class_id,
                    ':section_id' => $section_id,
                    ':academic_year' => $current_academic_year,
                    ':remarks' => $remarks
                ]);
            }
        }
        
        $conn->commit();
        
        // Prepare success message
        $alert = [
            'type' => 'success',
            'title' => 'Success!',
            'message' => "Student <strong>$name</strong> added successfully! Registration ID: $regd_id"
        ];
        
        // Clear form data on successful submission
        if (isset($_POST) && !empty($_POST)) {
            unset($_POST);
            $_POST = array();
        }
        
    } catch (Exception $e) {
        if (isset($conn) && $conn->inTransaction()) {
            $conn->rollBack();
        }
        $alert = [
            'type' => 'error',
            'title' => 'Error!',
            'message' => $e->getMessage()
        ];
    }
}

// Get classes for dropdown
$classes_query = "SELECT class_id, class, class_numeric FROM classes WHERE status = 1 ORDER BY class_numeric";
$classes_result = $conn->query($classes_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Student</title>
    
    <!-- Stylesheets -->
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
    <script src="js/modernizr/modernizr.min.js"></script>
    
    <style>
        .compact-form .form-group {
            margin-bottom: 5px;
        }
        .compact-form label {
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 4px;
            color: #495057;
        }
        .compact-form .form-control, .compact-form .select2-container--default .select2-selection--single {
            height: 40px;
            font-size: 13px;
            padding: 6px 10px;
            border-radius: 3px;
        }
        .compact-form textarea.form-control {
            height: auto;
            min-height: 60px;
            resize: vertical;
        }
        .compact-form .form-control:focus {
            border-color: #80bdff;
            box-shadow: 0 0 0 0.15rem rgba(0,123,255,.25);
        }
        .compact-form .form-section {
            background: #fff;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 5px;
            margin-bottom: 10px;
        }
        .compact-form .form-section h6 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 6px;
            margin-bottom: 5px;
            font-size: 14px;
            font-weight: 600;
        }
        .required-field:after {
            content: " *";
            color: #e74c3c;
        }
        .input-group-text {
            padding: 6px 10px;
            font-size: 13px;
            height: 34px;
        }
        .photo-preview {
            width: 80px;
            height: 80px;
            border: 2px dashed #dee2e6;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            background: #f8f9fa;
            cursor: pointer;
            margin: 0 auto;
            position: relative;
        }
        .photo-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: cover;
        }
        .photo-preview i {
            font-size: 24px;
            color: #6c757d;
        }
        .help-text {
            font-size: 11px;
            color: #6c757d;
            margin-top: 3px;
        }
        .form-actions {
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
            padding: 12px 15px;
            margin-top: 10px;
            border-radius: 4px;
        }
        .btn-sm {
            padding: 6px 12px;
            font-size: 13px;
        }
        .stats-badge {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            color: #1976d2;
            font-size: 11px;
            padding: 3px 8px;
            border-radius: 10px;
            font-weight: 500;
        }
        .toastify {
            border-radius: 4px;
            font-family: inherit;
            font-size: 13px;
            padding: 12px 20px;
            box-shadow: 0 3px 15px rgba(0,0,0,0.1);
        }
        .toastify-success {
            background: linear-gradient(135deg, #06d6a0, #05c090);
        }
        .toastify-error {
            background: linear-gradient(135deg, #ef233c, #d90429);
        }
        .field-error {
            border-color: #e74c3c !important;
        }
        .error-message {
            font-size: 11px;
            color: #e74c3c;
            margin-top: 3px;
        }
        .form-control.is-invalid {
            border-color: #e74c3c;
        }
        .invalid-feedback {
            display: block;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255,255,255,0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            display: none;
        }
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
    </div>
    
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
                
                <div class="main-page">
                    <div class="container-fluid">
                        <!-- Page Header -->
                        <div class="row page-title-div" style="margin-bottom: 15px;">
                            <div class="col-md-8">
                                <nav aria-label="breadcrumb" style="margin-top: 5px;">
                                    <ol class="breadcrumb" style="padding: 3px 0; margin: 0; font-size: 12px;">
                                        <li class="breadcrumb-item"><a href="dashboard.php"><i class="fa fa-home"></i></a></li>
                                        <li class="breadcrumb-item"><a href="manage_students.php">Students</a></li>
                                        <li class="breadcrumb-item">Add New</li>   
                                    </ol>
                                </nav>
                            </div>

                            <div class="col-md-4 text-right">
                                <i class="fa fa-edit mr-2"></i>Student Registration Form 
                                <?php if($current_academic_year): ?>
                                <span class="stats-badge">
                                    <i class="fa fa-calendar mr-1"></i><?= $current_academic_year ?>
                                </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Main Form -->
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel" style="margin-bottom: 0;">
                                    <div class="panel-body p-3">
                                        <form method="POST" action="" id="addStudentForm" enctype="multipart/form-data" class="compact-form">
                                            <div class="row">
                                                <!-- Left Column -->
                                                <div class="col-md-6">
                                                    <!-- Basic Information -->
                                                    <div class="form-section">
                                                        <h6><i class="fa fa-user mr-2"></i>Basic Information</h6>
                                                        
                                                        <div class="form-group">
                                                            <label class="required-field">Full Name</label>
                                                            <input type="text" class="form-control" name="name" required
                                                                   placeholder="Enter full name" value="<?= isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '' ?>">
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label class="required-field">Gender</label>
                                                                    <select class="form-control" name="gender" required>
                                                                        <option value="">-- Select --</option>
                                                                        <option value="Male" <?= (isset($_POST['gender']) && $_POST['gender'] == 'Male') ? 'selected' : '' ?>>Male</option>
                                                                        <option value="Female" <?= (isset($_POST['gender']) && $_POST['gender'] == 'Female') ? 'selected' : '' ?>>Female</option>
                                                                        <option value="Other" <?= (isset($_POST['gender']) && $_POST['gender'] == 'Other') ? 'selected' : '' ?>>Other</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label class="required-field">Date of Birth</label>
                                                                    <input type="text" class="form-control" name="dob" required
                                                                           value="<?= isset($_POST['dob']) ? htmlspecialchars($_POST['dob']) : '' ?>">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Academic Information -->
                                                    <div class="form-section">
                                                        <h6><i class="fa fa-graduation-cap mr-2"></i>Academic Information</h6>
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label class="required-field">Class</label>
                                                                    <select class="form-control" id="class_id" name="class_id" required>
                                                                        <option value="">-- Select --</option>
                                                                        <?php 
                                                                        $classes_result->execute();
                                                                        while ($class = $classes_result->fetch(PDO::FETCH_ASSOC)) {
                                                                            $selected = (isset($_POST['class_id']) && $_POST['class_id'] == $class['class_id']) ? 'selected' : '';
                                                                            echo '<option value="' . $class['class_id'] . '" ' . $selected . '>' . 
                                                                                 htmlspecialchars($class['class']) . ' (G' . $class['class_numeric'] . ')</option>';
                                                                        }
                                                                        ?>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label>Section</label>
                                                                    <select class="form-control" id="section_id" name="section_id" disabled>
                                                                        <option value="">-- Select Class --</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label>Student Group</label>
                                                                    <select class="form-control" name="std_group">
                                                                        <option value="">-- None --</option>
                                                                        <option value="Science" <?= (isset($_POST['std_group']) && $_POST['std_group'] == 'Science') ? 'selected' : '' ?>>Science</option>
                                                                        <option value="Management" <?= (isset($_POST['std_group']) && $_POST['std_group'] == 'Management') ? 'selected' : '' ?>>Management</option>
                                                                        <option value="Education" <?= (isset($_POST['std_group']) && $_POST['std_group'] == 'Education') ? 'selected' : '' ?>>Education</option>
                                                                        <option value="Arts" <?= (isset($_POST['std_group']) && $_POST['std_group'] == 'Arts') ? 'selected' : '' ?>>Arts</option>
                                                                        <option value="Other" <?= (isset($_POST['std_group']) && $_POST['std_group'] == 'Other') ? 'selected' : '' ?>>Other</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label class="required-field">Registration ID</label>
                                                                    <input type="text" class="form-control" name="regd_id" required
                                                                           placeholder="83-104137-001" maxlength="20"
                                                                           value="<?= isset($_POST['regd_id']) ? htmlspecialchars($_POST['regd_id']) : '' ?>">
                                                                    <div class="help-text">Unique student ID</div>
                                                                    <div class="error-message" id="regdIdError" style="display: none;"></div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <!-- Right Column -->
                                                <div class="col-md-6">
                                                    <!-- Parent Information -->
                                                    <div class="form-section">
                                                        <h6><i class="fa fa-users mr-2"></i>Parent/Guardian Information</h6>
                                                        <div class="form-group">
                                                            <label class="required-field">Parent/Guardian Name</label>
                                                            <input type="text" class="form-control" name="parent_name" required
                                                                   placeholder="Full name of parent/guardian"
                                                                   value="<?= isset($_POST['parent_name']) ? htmlspecialchars($_POST['parent_name']) : '' ?>">
                                                        </div>
                                                        
                                                        <div class="form-group">
                                                            <label>Parent Phone</label>
                                                            <input type="tel" class="form-control" name="parent_phone"
                                                                   placeholder="98XXXXXXXX" maxlength="10"
                                                                   value="<?= isset($_POST['parent_phone']) ? htmlspecialchars($_POST['parent_phone']) : '' ?>">
                                                            <div class="error-message" id="parentPhoneError" style="display: none;"></div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Contact Information -->
                                                    <div class="form-section">
                                                        <h6><i class="fa fa-phone mr-2"></i>Contact Information</h6>
                                                        <div class="form-group">
                                                            <label>Address</label>
                                                            <textarea class="form-control" name="address" rows="2"
                                                                      placeholder="Complete address"><?= isset($_POST['address']) ? htmlspecialchars($_POST['address']) : '' ?></textarea>
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label>Phone Number</label>
                                                                    <input type="tel" class="form-control" name="phone"
                                                                           placeholder="98XXXXXXXX" maxlength="10"
                                                                           value="<?= isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : '' ?>">
                                                                    <div class="error-message" id="phoneError" style="display: none;"></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-6">
                                                                <div class="form-group">
                                                                    <label>Email Address</label>
                                                                    <input type="email" class="form-control" name="email"
                                                                           placeholder="student@example.com"
                                                                           value="<?= isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>">
                                                                    <div class="error-message" id="emailError" style="display: none;"></div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Photo & Remarks -->
                                                    <div class="form-section">
                                                        <h6><i class="fa fa-camera mr-2"></i>Additional Information</h6>
                                                        <div class="row">
                                                            <div class="col-md-4">
                                                                <div class="form-group">
                                                                    <label>Student Photo</label>
                                                                    <div class="photo-preview" onclick="document.getElementById('photo').click()">
                                                                        <i class="fa fa-camera"></i>
                                                                        <img id="photoPreview" src="" style="display: none;">
                                                                    </div>
                                                                    <input type="file" id="photo" name="photo" accept="image/*" 
                                                                           style="display: none;" onchange="previewPhoto(event)">
                                                                    <div class="help-text text-center">Max 2MB, JPG/PNG</div>
                                                                    <div class="error-message" id="photoError" style="display: none;"></div>
                                                                </div>
                                                            </div>
                                                            <div class="col-md-8">
                                                                <div class="form-group">
                                                                    <label>Remarks</label>
                                                                    <textarea class="form-control" name="remarks" rows="3"
                                                                              placeholder="Any additional notes or remarks"><?= isset($_POST['remarks']) ? htmlspecialchars($_POST['remarks']) : '' ?></textarea>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Form Actions -->
                                            <div class="form-actions text-right">
                                                <button type="submit" class="btn btn-primary btn-sm" id="submitBtn">
                                                    <i class="fa fa-save mr-1"></i> Save Student
                                                </button>
                                                <button type="reset" class="btn btn-secondary btn-sm" id="resetBtn">
                                                    <i class="fa fa-refresh mr-1"></i> Clear
                                                </button>
                                                <a href="manage_students.php" class="btn btn-outline-secondary btn-sm">
                                                    <i class="fa fa-times mr-1"></i> Cancel
                                                </a>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    <script src="js/main.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2
        $('#class_id, #section_id, select[name="gender"], select[name="std_group"]').select2({
            width: '100%',
            minimumResultsForSearch: 10
        });
        
        // Show toast notification if there's a message
        <?php if (!empty($alert['type'])): ?>
        showToast('<?php echo $alert['type']; ?>', '<?php echo $alert['title']; ?>', '<?php echo $alert['message']; ?>');
        <?php endif; ?>
        
        // Load sections when class is selected
        $('#class_id').change(function() {
            var classId = $(this).val();
            if (classId) {
                $.ajax({
                    url: 'ajax/get_sections.php',
                    type: 'GET',
                    data: { class_id: classId },
                    beforeSend: function() {
                        $('#section_id').prop('disabled', true).html('<option value="">Loading...</option>');
                    },
                    success: function(response) {
                        try {
                            const sections = JSON.parse(response);
                            let options = '<option value="">-- Select (Optional) --</option>';
                            if (sections && sections.length > 0) {
                                sections.forEach(function(section) {
                                    options += '<option value="' + section.section_id + '">' + 
                                               section.section_name + '</option>';
                                });
                                $('#section_id').html(options).prop('disabled', false);
                                
                                // Restore previously selected section if exists
                                <?php if (isset($_POST['section_id']) && $_POST['section_id']): ?>
                                $('#section_id').val('<?php echo $_POST['section_id']; ?>').trigger('change');
                                <?php endif; ?>
                            } else {
                                $('#section_id').html('<option value="">No sections available</option>').prop('disabled', false);
                            }
                        } catch(e) {
                            console.error('Error parsing sections:', e);
                            $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
                        }
                    },
                    error: function() {
                        $('#section_id').html('<option value="">Error loading sections</option>').prop('disabled', true);
                    }
                });
            } else {
                $('#section_id').html('<option value="">-- Select Class --</option>').prop('disabled', true);
            }
        });
        
        // Check if registration ID exists in real-time
        let regdIdCheckTimeout;
        $('input[name="regd_id"]').on('input', function() {
            clearTimeout(regdIdCheckTimeout);
            const $input = $(this);
            const regdId = $input.val().trim();
            const $errorDiv = $('#regdIdError');
            
            if (regdId.length >= 3) {
                regdIdCheckTimeout = setTimeout(function() {
                    $.ajax({
                        url: 'ajax/check_regd_id.php',
                        type: 'POST',
                        data: { regd_id: regdId },
                        beforeSend: function() {
                            $input.addClass('loading');
                        },
                        success: function(response) {
                            $input.removeClass('loading');
                            try {
                                const data = JSON.parse(response);
                                if (data.exists) {
                                    $input.addClass('is-invalid');
                                    $errorDiv.text('This Registration ID is already in use.').show();
                                } else {
                                    $input.removeClass('is-invalid');
                                    $errorDiv.hide();
                                }
                            } catch(e) {
                                console.error('Error checking Registration ID:', e);
                            }
                        },
                        error: function() {
                            $input.removeClass('loading');
                        }
                    });
                }, 500);
            } else {
                $errorDiv.hide();
                $input.removeClass('is-invalid');
            }
        });
        
        // Set date constraints for DOB
        var today = new Date();
        var maxDate = new Date(today.getFullYear() - 4, today.getMonth(), today.getDate());
        var minDate = new Date(today.getFullYear() - 25, today.getMonth(), today.getDate());
        
        $('input[name="dob"]').attr({
            'max': maxDate.toISOString().split('T')[0],
            'min': minDate.toISOString().split('T')[0]
        });
        
        // Phone number validation
        $('input[name="phone"]').on('input', function() {
            validatePhoneNumber(this, $('#phoneError'));
        });
        
        $('input[name="parent_phone"]').on('input', function() {
            validatePhoneNumber(this, $('#parentPhoneError'));
        });
        
        // Email validation
        $('input[name="email"]').on('blur', function() {
            validateEmail(this, $('#emailError'));
        });
        
        // Form validation on submit
        $('#addStudentForm').submit(function(e) {
            let isValid = true;
            
            // Validate required fields
            $('[required]').each(function() {
                if (!$(this).val().trim()) {
                    $(this).addClass('is-invalid');
                    isValid = false;
                } else {
                    $(this).removeClass('is-invalid');
                }
            });
            
            // Validate phone numbers if provided
            const phone = $('input[name="phone"]').val().trim();
            const parentPhone = $('input[name="parent_phone"]').val().trim();
            
            if (phone && !/^\d{10}$/.test(phone)) {
                $('#phoneError').text('Please enter a valid 10-digit phone number.').show();
                $('input[name="phone"]').addClass('is-invalid');
                isValid = false;
            }
            
            if (parentPhone && !/^\d{10}$/.test(parentPhone)) {
                $('#parentPhoneError').text('Please enter a valid 10-digit phone number.').show();
                $('input[name="parent_phone"]').addClass('is-invalid');
                isValid = false;
            }
            
            // Validate email if provided
            const email = $('input[name="email"]').val().trim();
            if (email && !validateEmailFormat(email)) {
                $('#emailError').text('Please enter a valid email address.').show();
                $('input[name="email"]').addClass('is-invalid');
                isValid = false;
            }
            
            if (!isValid) {
                e.preventDefault();
                showToast('error', 'Validation Error', 'Please fix the errors in the form.');
                return false;
            }
            
            // Show loading overlay
            $('#loadingOverlay').show();
            $('#submitBtn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin mr-1"></i> Saving...');
            
            return true;
        });
        
        // Reset form
        $('#resetBtn').click(function() {
            $('#addStudentForm')[0].reset();
            $('#section_id').html('<option value="">-- Select Class --</option>').prop('disabled', true);
            $('#photoPreview').hide().attr('src', '');
            $('.photo-preview i').show();
            $('.error-message').hide();
            $('.is-invalid').removeClass('is-invalid');
            $('#class_id').val('').trigger('change');
        });
        
        // Initialize section dropdown if class is already selected
        <?php if (isset($_POST['class_id']) && $_POST['class_id']): ?>
        $('#class_id').trigger('change');
        <?php endif; ?>
        
        // Auto-hide error messages on input
        $('input, select, textarea').on('input change', function() {
            $(this).removeClass('is-invalid');
            $(this).next('.error-message').hide();
        });
    });
    
    function validatePhoneNumber(input, errorDiv) {
        const value = $(input).val().replace(/\D/g, '');
        $(input).val(value);
        
        if (value && value.length !== 10) {
            errorDiv.text('Phone number must be 10 digits.').show();
            $(input).addClass('is-invalid');
        } else {
            errorDiv.hide();
            $(input).removeClass('is-invalid');
        }
    }
    
    function validateEmail(input, errorDiv) {
        const email = $(input).val().trim();
        if (email && !validateEmailFormat(email)) {
            errorDiv.text('Please enter a valid email address.').show();
            $(input).addClass('is-invalid');
        } else {
            errorDiv.hide();
            $(input).removeClass('is-invalid');
        }
    }
    
    function validateEmailFormat(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    function previewPhoto(event) {
        const input = event.target;
        const preview = document.getElementById('photoPreview');
        const errorDiv = document.getElementById('photoError');
        const maxSize = 2 * 1024 * 1024; // 2MB
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'];
        
        if (input.files && input.files[0]) {
            const file = input.files[0];
            
            // Validate file type
            if (!allowedTypes.includes(file.type)) {
                errorDiv.textContent = 'Only JPG, PNG, and GIF images are allowed.';
                errorDiv.style.display = 'block';
                input.value = '';
                return;
            }
            
            // Validate file size
            if (file.size > maxSize) {
                errorDiv.textContent = 'File size must be less than 2MB.';
                errorDiv.style.display = 'block';
                input.value = '';
                return;
            }
            
            errorDiv.style.display = 'none';
            
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.src = e.target.result;
                preview.style.display = 'block';
                preview.parentElement.querySelector('i').style.display = 'none';
            }
            
            reader.readAsDataURL(file);
        }
    }
    
    function showToast(type, title, message) {
        const backgroundColor = type === 'success' ? '#06d6a0' : '#ef233c';
        const icon = type === 'success' ? '✓' : '✗';
        
        Toastify({
            text: `<strong>${title}</strong><br>${message}`,
            duration: 5000,
            gravity: "top",
            position: "right",
            backgroundColor: backgroundColor,
            stopOnFocus: true,
            escapeMarkup: false,
            onClick: function() {}
        }).showToast();
    }
    
    // Hide loading overlay when page loads (in case of form submission failure)
    window.addEventListener('load', function() {
        setTimeout(function() {
            $('#loadingOverlay').hide();
            $('#submitBtn').prop('disabled', false).html('<i class="fa fa-save mr-1"></i> Save Student');
        }, 1000);
    });
    </script>
</body>
</html>