<?php
session_start();
require_once 'config/database.php';
require_once 'includes/site_settings.php';
require_once 'includes/image_utils.php';

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';

// Check if admission is currently open
$admission_open = false;
$admission_message = '';
$admission_dates = null;
$dates_set = false;
$available_classes = [];

try {
    // Try to get admission publish dates
    // First check for class-specific dates
    $stmt = $pdo->prepare("SELECT apd.*, c.name as class_name, c.section as class_section FROM admission_publish_dates apd LEFT JOIN classes c ON apd.class_id = c.id WHERE apd.is_active = 1 AND apd.class_id IS NOT NULL ORDER BY apd.id DESC");
    $stmt->execute();
    $class_specific_dates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Then get global dates (for all classes)
    $stmt = $pdo->prepare("SELECT * FROM admission_publish_dates WHERE is_active = 1 AND class_id IS NULL ORDER BY id DESC LIMIT 1");
    $stmt->execute();
    $global_dates = $stmt->fetch();
    
    // Build list of available classes
    if (!empty($class_specific_dates)) {
        foreach ($class_specific_dates as $date) {
            $class_name = $date['class_name'] . ($date['class_section'] ? ' - ' . $date['class_section'] : '');
            $available_classes[] = [
                'class_id' => $date['class_id'],
                'class_name' => $class_name,
                'start_date' => $date['start_date'],
                'end_date' => $date['end_date']
            ];
        }
    }
    
    // If we have class-specific dates, show them in the message
    if (!empty($available_classes)) {
        $class_list = [];
        foreach ($available_classes as $class_info) {
            $class_list[] = $class_info['class_name'];
        }
        $admission_message = 'ভর্তি আবেদন নিম্নলিখিত ক্লাসগুলির জন্য চলছে: ' . implode(', ', $class_list);
        $dates_set = true;
    } else if ($global_dates) {
        // Use global dates if no class-specific dates
        $admission_dates = $global_dates;
        $dates_set = true;
        $current_date = date('Y-m-d');
        $start_date = $admission_dates['start_date'];
        $end_date = $admission_dates['end_date'];
        
        if ($current_date < $start_date) {
            $admission_open = false;
            $admission_message = 'ভর্তি আবেদন ' . date('d/m/Y', strtotime($start_date)) . ' তারিখ থেকে শুরু হবে।';
        } elseif ($current_date > $end_date) {
            $admission_open = false;
            $admission_message = 'ভর্তি আবেদনের সময় শেষ হয়ে গেছে। শেষ তারিখ ছিল ' . date('d/m/Y', strtotime($end_date)) . '।';
        } else {
            $admission_open = true;
            $admission_message = 'ভর্তি আবেদন চলছে।';
        }
    } else {
        // No dates set - show specific message
        $admission_open = false;
        $admission_message = 'এখন পর্যন্ত কোন ভর্তি আবেদনের তারিখ নির্ধারণ করা হয়নি। অনুগ্রহ করে পরে আবার চেষ্টা করুন।';
    }
} catch (Exception $e) {
    // If table doesn't exist or other error, continue with admission closed
    $admission_open = false;
    $admission_message = 'এখন পর্যন্ত কোন ভর্তি আবেদনের তারিখ নির্ধারণ করা হয়নি। অনুগ্রহ করে পরে আবার চেষ্টা করুন।';
}

// Initialize variables
$success_message = '';
$error_message = '';
$classes = [];

// Check if student_id is passed from teacher's page
$student_data = null;
$student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;

if ($student_id > 0) {
    try {
        // Get student data to pre-fill the form
        $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
        $stmt->execute([$student_id]);
        $student_data = $stmt->fetch();
    } catch (Exception $e) {
        // If there's an error, continue without pre-filling
        $student_data = null;
    }
}

// Get active classes for the application form
try {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name ASC");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $error_message = 'ক্লাস তালিকা আনতে সমস্যা হয়েছে।';
}

// Get academic sessions for dropdown
$sessions = [];
try {
    $stmt = $pdo->query("SELECT id, name FROM academic_sessions WHERE status = 'active' ORDER BY is_current DESC, start_date DESC");
    $sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // If sessions table doesn't exist or has issues, we'll use the text field approach
    $sessions = [];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if admission is open before processing
    $class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : 0;
    
    // Check if the selected class has an active admission date
    if ($class_id) {
        $class_admission_open = false;
        $current_date = date('Y-m-d');
        
        // First check if there are class-specific active dates
        if (!empty($available_classes)) {
            foreach ($available_classes as $class_info) {
                if ($class_info['class_id'] == $class_id) {
                    $start_date = $class_info['start_date'];
                    $end_date = $class_info['end_date'];
                    
                    if ($current_date >= $start_date && $current_date <= $end_date) {
                        $class_admission_open = true;
                        break;
                    }
                }
            }
        }
        
        // If no class-specific dates, check global dates
        if (!$class_admission_open && $admission_open) {
            $class_admission_open = true;
        }
        
        if (!$class_admission_open) {
            $error_message = 'নির্বাচিত ক্লাসের জন্য ভর্তি আবেদন বন্ধ রয়েছে। অনুগ্রহ করে অন্য ক্লাস নির্বাচন করুন বা পরে আবার চেষ্টা করুন।';
        }
    } else if (!$admission_open && empty($available_classes)) {
        $error_message = $admission_message;
    }
    
    if (empty($error_message)) {
        try {
            // Collect form data
            $first_name = isset($_POST['first_name']) ? trim($_POST['first_name']) : '';
            $last_name = isset($_POST['last_name']) ? trim($_POST['last_name']) : '';
            $father_name = isset($_POST['father_name']) ? trim($_POST['father_name']) : '';
            $mother_name = isset($_POST['mother_name']) ? trim($_POST['mother_name']) : '';
            $date_of_birth = isset($_POST['date_of_birth']) ? $_POST['date_of_birth'] : '';
            $gender = isset($_POST['gender']) ? $_POST['gender'] : '';
            $religion = isset($_POST['religion']) ? $_POST['religion'] : ''; // Add religion field
            $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
            $father_phone = isset($_POST['father_phone']) ? trim($_POST['father_phone']) : '';
            $email = isset($_POST['email']) ? trim($_POST['email']) : '';
            $address = isset($_POST['address']) ? trim($_POST['address']) : '';
            $class_id = isset($_POST['class_id']) ? (int)$_POST['class_id'] : 0;
            $previous_school = isset($_POST['previous_school']) ? trim($_POST['previous_school']) : '';
            $previous_class = isset($_POST['previous_class']) ? trim($_POST['previous_class']) : '';
            $applying_session_id = isset($_POST['applying_session_id']) ? (int)$_POST['applying_session_id'] : 0;
            $applying_group = isset($_POST['applying_group']) ? trim($_POST['applying_group']) : '';
            $blood_group = isset($_POST['blood_group']) ? trim($_POST['blood_group']) : '';
            $selected_subjects = isset($_POST['subjects']) ? $_POST['subjects'] : []; // Add subject selection
            
            // Validate required fields
            if (empty($first_name) || empty($father_name) || empty($mother_name) || empty($date_of_birth) || 
                empty($gender) || empty($religion) || empty($phone) || empty($class_id)) { // Add religion to validation
                $error_message = 'অনুগ্রহ করে সব প্রয়োজনীয় তথ্য পূরণ করুন।';
            } else {
                // Handle photo upload
                $photo_path = '';
                if (isset($_FILES['student_photo']) && $_FILES['student_photo']['error'] == 0) {
                    $upload_dir = 'uploads/student_photos/';
                    
                    // Compress and validate the uploaded image
                    $result = validate_and_compress_image($_FILES['student_photo'], $upload_dir, 100);
                    
                    if ($result['success']) {
                        $photo_path = $result['path'];
                    } else {
                        $error_message = $result['error'];
                    }
                }
                
                // Check if email already exists
                if (empty($error_message) && !empty($email)) {
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM admission_applications WHERE email = ? AND status != 'rejected'");
                    $stmt->execute([$email]);
                    if ($stmt->fetchColumn() > 0) {
                        $error_message = 'এই ইমেইলটি ইতিমধ্যে ব্যবহার করা হয়েছে।';
                    }
                }
                
                // Check if phone already exists
                if (empty($error_message)) {
                    $stmt = $pdo->prepare("SELECT COUNT(*) FROM admission_applications WHERE phone = ? AND status != 'rejected'");
                    $stmt->execute([$phone]);
                    if ($stmt->fetchColumn() > 0) {
                        $error_message = 'এই ফোন নম্বরটি ইতিমধ্যে ব্যবহার করা হয়েছে।';
                    }
                }
                
                // If no errors, insert application
                if (empty($error_message)) {
                    // Insert application with the correct table structure
                    $stmt = $pdo->prepare("
                        INSERT INTO admission_applications 
                        (first_name, last_name, father_name, mother_name, date_of_birth, gender, religion, blood_group,
                         phone, father_phone, email, present_address, permanent_address, applying_for_class_id, previous_school, previous_class,
                         application_no, password, status, photo_path, applying_for_session, applying_for_group, created_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                    ");
                    
                    // Generate application number
                    $application_no = 'APP' . date('Y') . rand(10000, 99999);
                    
                    $result = $stmt->execute([
                        $first_name, $last_name, $father_name, $mother_name, $date_of_birth, $gender, $religion, $blood_group,
                        $phone, $father_phone, $email, $address, $address, $class_id, $previous_school, $previous_class, 
                        $application_no, '123456', 'pending', $photo_path, $applying_session_id, $applying_group
                    ]);
                    
                    if ($result) {
                        // Redirect to receipt page
                        header("Location: admission_receipt.php?application_no=" . $application_no);
                        exit();
                    } else {
                        $error_message = 'আবেদন জমা দিতে সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন।';
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Admission application error: " . $e->getMessage());
            $error_message = 'আবেদন জমা দিতে সমস্যা হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন। [Error: ' . $e->getMessage() . ']';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php if ($student_data): ?>
            <?php echo htmlspecialchars($student_data['first_name'] . ' ' . $student_data['last_name']); ?> - ভর্তি আবেদন
        <?php else: ?>
            ভর্তি আবেদন - <?php echo htmlspecialchars($site_name); ?>
        <?php endif; ?>
    </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif;
            background: #f5f7fa; 
        }
        
        .application-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: #fff;
            padding: 2rem 0;
            margin-bottom: 2rem;
            border-bottom: 3px solid #F42A41;
        }
        
        .application-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,103,71,0.15);
            border: 1px solid #e0e0e0;
            margin-bottom: 2rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #006747;
        }
        
        .btn-submit {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
            font-weight: 600;
            padding: 12px 30px;
        }
        
        .btn-submit:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 103, 71, 0.4);
        }
        
        .section-title {
            color: #006747;
            border-bottom: 2px solid #F42A41;
            padding-bottom: 10px;
            margin-bottom: 20px;
            font-weight: 700;
        }
        
        .form-control:focus,
        .form-select:focus {
            border-color: #006747;
            box-shadow: 0 0 0 0.25rem rgba(0, 103, 71, 0.15);
        }
        
        @media (max-width: 768px) {
            .application-header h1 {
                font-size: 1.8rem;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="application-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1><i class="fas fa-user-plus"></i> 
                        <?php if ($student_data): ?>
                            <?php echo htmlspecialchars($student_data['first_name'] . ' ' . $student_data['last_name']); ?> এর জন্য ভর্তি আবেদন
                        <?php else: ?>
                            ভর্তি আবেদন - <?php echo htmlspecialchars($site_name); ?>
                        <?php endif; ?>
                    </h1>
                </div>
                <div class="col-md-4 text-end">
                    <?php 
                    // Check if user is a teacher who came from student list
                    $is_teacher = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'teacher';
                    $came_from_student_list = isset($_GET['student_id']) && (int)$_GET['student_id'] > 0;
                    if ($is_teacher && $came_from_student_list): ?>
                        <a href="teachers/dashboard.php" class="btn btn-light">
                            <i class="fas fa-arrow-left"></i> ড্যাশবোর্ডে ফিরে যান
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($student_data): ?>
            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-info-circle"></i> 
                আপনি <strong><?php echo htmlspecialchars($student_data['first_name'] . ' ' . $student_data['last_name']); ?></strong> এর জন্য ভর্তি আবেদন ফরম পূরণ করছেন। 
                অনুগ্রহ করে প্রয়োজনীয় তথ্য যাচাই করুন এবং আবেদন জমা দিন।
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!$admission_open && $admission_message): ?>
            <div class="alert alert-warning alert-dismissible fade show" role="alert">
                <i class="fas fa-info-circle"></i> <?php echo $admission_message; ?>
                <?php if ($admission_dates): ?>
                    <br><strong>শিক্ষাবর্ষ:</strong> <?php echo htmlspecialchars($admission_dates['academic_year']); ?>
                    <br><strong>আবেদনের সময়কাল:</strong> <?php echo date('d/m/Y', strtotime($admission_dates['start_date'])); ?> থেকে <?php echo date('d/m/Y', strtotime($admission_dates['end_date'])); ?> পর্যন্ত
                <?php elseif (!empty($available_classes)): ?>
                    <br><strong>ভর্তি চলছে নিম্নলিখিত ক্লাসগুলির জন্য:</strong>
                    <ul>
                        <?php foreach ($available_classes as $class_info): ?>
                            <li><?php echo htmlspecialchars($class_info['class_name']); ?> (<?php echo date('d/m/Y', strtotime($class_info['start_date'])); ?> থেকে <?php echo date('d/m/Y', strtotime($class_info['end_date'])); ?> পর্যন্ত)</li>
                        <?php endforeach; ?>
                    </ul>
                <?php elseif ($dates_set === false): ?>
                    <br><strong>দ্রষ্টব্য:</strong> ভর্তি আবেদনের তারিখ নির্ধারণ করা হয়নি।
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <?php if ($admission_open || !empty($available_classes)): ?>
            <div class="application-card">
                <div class="card-body p-4">
                    <form method="POST" action="" enctype="multipart/form-data">
                        <!-- Personal Information Section -->
                        <h4 class="section-title"><i class="fas fa-user"></i> ব্যক্তিগত তথ্য</h4>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="first_name" class="form-label">নাম (ইংরেজিতে) *</label>
                                <input type="text" class="form-control" id="first_name" name="first_name" value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : (isset($student_data['first_name']) ? htmlspecialchars($student_data['first_name']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="last_name" class="form-label">নাম (বাংলায়)</label>
                                <input type="text" class="form-control" id="last_name" name="last_name" value="<?php echo isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : (isset($student_data['last_name']) ? htmlspecialchars($student_data['last_name']) : ''); ?>">
                            </div>
                            
                            <div class="col-md-6">
                                <label for="father_name" class="form-label">পিতার নাম *</label>
                                <input type="text" class="form-control" id="father_name" name="father_name" value="<?php echo isset($_POST['father_name']) ? htmlspecialchars($_POST['father_name']) : (isset($student_data['father_name']) ? htmlspecialchars($student_data['father_name']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="mother_name" class="form-label">মাতার নাম *</label>
                                <input type="text" class="form-control" id="mother_name" name="mother_name" value="<?php echo isset($_POST['mother_name']) ? htmlspecialchars($_POST['mother_name']) : (isset($student_data['mother_name']) ? htmlspecialchars($student_data['mother_name']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="date_of_birth" class="form-label">জন্ম তারিখ *</label>
                                <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="<?php echo isset($_POST['date_of_birth']) ? htmlspecialchars($_POST['date_of_birth']) : (isset($student_data['date_of_birth']) ? htmlspecialchars($student_data['date_of_birth']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="religion" class="form-label">ধর্ম *</label>
                                <select class="form-select" id="religion" name="religion" required>
                                    <option value="">নির্বাচন করুন</option>
                                    <option value="islam" <?php echo (isset($_POST['religion']) && $_POST['religion'] == 'islam') ? 'selected' : (isset($student_data['religion']) && $student_data['religion'] == 'islam' ? 'selected' : ''); ?>>ইসলাম</option>
                                    <option value="hinduism" <?php echo (isset($_POST['religion']) && $_POST['religion'] == 'hinduism') ? 'selected' : (isset($student_data['religion']) && $student_data['religion'] == 'hinduism' ? 'selected' : ''); ?>>হিন্দু</option>
                                    <option value="buddhism" <?php echo (isset($_POST['religion']) && $_POST['religion'] == 'buddhism') ? 'selected' : (isset($student_data['religion']) && $student_data['religion'] == 'buddhism' ? 'selected' : ''); ?>>বৌদ্ধ</option>
                                    <option value="christianity" <?php echo (isset($_POST['religion']) && $_POST['religion'] == 'christianity') ? 'selected' : (isset($student_data['religion']) && $student_data['religion'] == 'christianity' ? 'selected' : ''); ?>>খ্রিস্টান</option>
                                    <option value="other" <?php echo (isset($_POST['religion']) && $_POST['religion'] == 'other') ? 'selected' : (isset($student_data['religion']) && $student_data['religion'] == 'other' ? 'selected' : ''); ?>>অন্যান্য</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="gender" class="form-label">লিঙ্গ *</label>
                                <select class="form-select" id="gender" name="gender" required>
                                    <option value="">নির্বাচন করুন</option>
                                    <option value="male" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'male') ? 'selected' : (isset($student_data['gender']) && $student_data['gender'] == 'male' ? 'selected' : ''); ?>>পুরুষ</option>
                                    <option value="female" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'female') ? 'selected' : (isset($student_data['gender']) && $student_data['gender'] == 'female' ? 'selected' : ''); ?>>মহিলা</option>
                                    <option value="other" <?php echo (isset($_POST['gender']) && $_POST['gender'] == 'other') ? 'selected' : (isset($student_data['gender']) && $student_data['gender'] == 'other' ? 'selected' : ''); ?>>অন্যান্য</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="blood_group" class="form-label">রক্তের গ্রুপ</label>
                                <select class="form-select" id="blood_group" name="blood_group">
                                    <option value="">নির্বাচন করুন</option>
                                    <option value="A+" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'A+') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'A+' ? 'selected' : ''); ?>>A+</option>
                                    <option value="A-" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'A-') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'A-' ? 'selected' : ''); ?>>A-</option>
                                    <option value="B+" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'B+') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'B+' ? 'selected' : ''); ?>>B+</option>
                                    <option value="B-" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'B-') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'B-' ? 'selected' : ''); ?>>B-</option>
                                    <option value="O+" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'O+') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'O+' ? 'selected' : ''); ?>>O+</option>
                                    <option value="O-" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'O-') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'O-' ? 'selected' : ''); ?>>O-</option>
                                    <option value="AB+" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'AB+') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'AB+' ? 'selected' : ''); ?>>AB+</option>
                                    <option value="AB-" <?php echo (isset($_POST['blood_group']) && $_POST['blood_group'] == 'AB-') ? 'selected' : (isset($student_data['blood_group']) && $student_data['blood_group'] == 'AB-' ? 'selected' : ''); ?>>AB-</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="phone" class="form-label">ছাত্র/ছাত্রীর ফোন নম্বর *</label>
                                <input type="tel" class="form-control" id="phone" name="phone" value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : (isset($student_data['phone']) ? htmlspecialchars($student_data['phone']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="father_phone" class="form-label">পিতা/অভিভাবকের ফোন নম্বর *</label>
                                <input type="tel" class="form-control" id="father_phone" name="father_phone" value="<?php echo isset($_POST['father_phone']) ? htmlspecialchars($_POST['father_phone']) : (isset($student_data['guardian_phone']) ? htmlspecialchars($student_data['guardian_phone']) : ''); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="email" class="form-label">ইমেইল (ঐচ্ছিক)</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : (isset($student_data['email']) ? htmlspecialchars($student_data['email']) : ''); ?>">
                            </div>
                            
                            <div class="col-md-12">
                                <label for="address" class="form-label">ঠিকানা</label>
                                <textarea class="form-control" id="address" name="address" rows="3"><?php echo isset($_POST['address']) ? htmlspecialchars($_POST['address']) : (isset($student_data['address']) ? htmlspecialchars($student_data['address']) : ''); ?></textarea>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="student_photo" class="form-label">ছাত্র/ছাত্রীর ছবি (ঐচ্ছিক)</label>
                                <input type="file" class="form-control" id="student_photo" name="student_photo" accept="image/*" onchange="checkFileSize(this)">
                                <div class="form-text">JPG, JPEG, PNG বা GIF ফাইল, স্বয়ংক্রিয়ভাবে ১০০ KB এ কম্প্রেস করা হবে</div>
                                <div id="photo-preview-container"></div>
                            </div>
                        </div>
                        
                        <!-- Academic Information Section -->
                        <h4 class="section-title mt-4"><i class="fas fa-graduation-cap"></i> শিক্ষাগত তথ্য</h4>
                        
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="class_id" class="form-label">ভর্তি করতে ইচ্ছুক ক্লাস *</label>
                                <select class="form-select" id="class_id" name="class_id" required>
                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                    <?php foreach ($classes as $class): ?>
                                        <option value="<?php echo $class['id']; ?>" <?php echo (isset($_POST['class_id']) && $_POST['class_id'] == $class['id']) ? 'selected' : (isset($student_data['class_id']) && $student_data['class_id'] == $class['id'] ? 'selected' : ''); ?>>
                                            <?php echo htmlspecialchars($class['name'] . ($class['section'] ? ' - ' . $class['section'] : '')); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="applying_session_id" class="form-label">সেশন *</label>
                                <?php if (!empty($sessions)): ?>
                                    <select class="form-select" id="applying_session_id" name="applying_session_id" required>
                                        <option value="">সেশন নির্বাচন করুন</option>
                                        <?php foreach ($sessions as $session): ?>
                                            <option value="<?php echo $session['id']; ?>" <?php echo (isset($_POST['applying_session_id']) && $_POST['applying_session_id'] == $session['id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($session['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                <?php else: ?>
                                    <input type="text" class="form-control" id="applying_session_id" name="applying_session_id" value="<?php echo isset($_POST['applying_session_id']) ? htmlspecialchars($_POST['applying_session_id']) : (isset($student_data['session']) ? htmlspecialchars($student_data['session']) : ''); ?>" placeholder="উদাহরণ: 2025-2026" required>
                                <?php endif; ?>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="applying_group" class="form-label">গ্রুপ (ঐচ্ছিক)</label>
                                <select class="form-select" id="applying_group" name="applying_group">
                                    <option value="">গ্রুপ নির্বাচন করুন</option>
                                    <option value="Science" <?php echo (isset($_POST['applying_group']) && $_POST['applying_group'] == 'Science') ? 'selected' : (isset($student_data['group_name']) && $student_data['group_name'] == 'Science' ? 'selected' : ''); ?>>Science</option>
                                    <option value="Arts" <?php echo (isset($_POST['applying_group']) && $_POST['applying_group'] == 'Arts') ? 'selected' : (isset($student_data['group_name']) && $student_data['group_name'] == 'Arts' ? 'selected' : ''); ?>>Arts</option>
                                    <option value="Commerce" <?php echo (isset($_POST['applying_group']) && $_POST['applying_group'] == 'Commerce') ? 'selected' : (isset($student_data['group_name']) && $student_data['group_name'] == 'Commerce' ? 'selected' : ''); ?>>Commerce</option>
                                    <option value="General" <?php echo (isset($_POST['applying_group']) && $_POST['applying_group'] == 'General') ? 'selected' : (isset($student_data['group_name']) && $student_data['group_name'] == 'General' ? 'selected' : ''); ?>>General</option>
                                </select>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="previous_class" class="form-label">পূর্ববর্তী ক্লাস (ঐচ্ছিক)</label>
                                <input type="text" class="form-control" id="previous_class" name="previous_class" value="<?php echo isset($_POST['previous_class']) ? htmlspecialchars($_POST['previous_class']) : ''; ?>" placeholder="উদাহরণ: পঞ্চম শ্রেণী">
                            </div>
                            
                            <div class="col-md-12">
                                <label for="previous_school" class="form-label">পূর্ববর্তী স্কুল (ঐচ্ছিক)</label>
                                <input type="text" class="form-control" id="previous_school" name="previous_school" value="<?php echo isset($_POST['previous_school']) ? htmlspecialchars($_POST['previous_school']) : ''; ?>" placeholder="পূর্ববর্তী স্কুলের নাম">
                            </div>
                        </div>
                        
                        <!-- Subject Selection Section -->
                        <div id="subjectSelectionSection" style="display: none;">
                            <h4 class="section-title mt-4"><i class="fas fa-book"></i> বিষয় নির্বাচন</h4>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i> 
                                নিচের বিষয়গুলো থেকে আপনার পছন্দের বিষয়গুলো নির্বাচন করুন
                            </div>
                            <div id="subjectsContainer" class="row g-3">
                                <!-- Subjects will be loaded here dynamically -->
                            </div>
                        </div>
                        
                        <!-- Submission Section -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle"></i> 
                                    <strong>দ্রষ্টব্য:</strong> আপনার আবেদন জমা দেওয়ার পর আমাদের টিম আপনার সাথে যোগাযোগ করবে। 
                                    অনুগ্রহ করে সঠিক তথ্য প্রদান করুন।
                                </div>
                                
                                <div class="text-center">
                                    <button type="submit" class="btn btn-submit">
                                        <i class="fas fa-paper-plane"></i> আবেদন জমা দিন
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        <?php else: ?>
            <div class="text-center py-5">
                <i class="fas fa-calendar-times fa-5x text-muted mb-3"></i>
                <h4>ভর্তি আবেদন বন্ধ রয়েছে</h4>
                <p class="text-muted"><?php echo $admission_message; ?></p>
                <?php 
                // Check if user is a teacher who came from student list
                $is_teacher = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'teacher';
                $came_from_student_list = isset($_GET['student_id']) && (int)$_GET['student_id'] > 0;
                $redirect_url = $is_teacher && $came_from_student_list ? 'teachers/dashboard.php' : 'index.php';
                $redirect_text = $is_teacher && $came_from_student_list ? 'ড্যাশবোর্ডে ফিরে যান' : 'হোমপেজে ফিরে যান';
                ?>
                <a href="<?php echo $redirect_url; ?>" class="btn btn-primary">
                    <i class="fas fa-arrow-left"></i> <?php echo $redirect_text; ?>
                </a>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set max date to today for date of birth
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('date_of_birth').setAttribute('max', today);
            
            // Class selection change handler
            const classSelect = document.getElementById('class_id');
            if (classSelect) {
                classSelect.addEventListener('change', function() {
                    const classId = this.value;
                    const subjectSection = document.getElementById('subjectSelectionSection');
                    const subjectsContainer = document.getElementById('subjectsContainer');
                    
                    if (classId) {
                        // Show loading indicator
                        subjectSection.style.display = 'block';
                        subjectsContainer.innerHTML = '<div class="col-12 text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>';
                        
                        // Fetch subjects for the selected class
                        fetch('get_class_subjects.php?class_id=' + classId)
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    if (data.subjects && data.subjects.length > 0) {
                                        let subjectHtml = '';
                                        data.subjects.forEach((subject, index) => {
                                            subjectHtml += `
                                                <div class="col-md-4">
                                                    <div class="form-check">
                                                        <input class="form-check-input subject-checkbox" type="checkbox" name="subjects[]" value="\${subject.subject_id}" id="subject_\${subject.subject_id}">
                                                        <label class="form-check-label" for="subject_\${subject.subject_id}">
                                                            \${subject.name} (\${subject.code})
                                                        </label>
                                                    </div>
                                                </div>
                                            `;
                                        });
                                        subjectsContainer.innerHTML = subjectHtml;
                                        
                                        // Check if any subjects were previously selected (for form resubmission)
                                        const selectedSubjects = <?php echo json_encode(isset($_POST['subjects']) ? $_POST['subjects'] : []); ?>;
                                        if (selectedSubjects.length > 0) {
                                            selectedSubjects.forEach(subjectId => {
                                                const checkbox = document.querySelector(`input[name="subjects[]"][value="\${subjectId}"]`);
                                                if (checkbox) {
                                                    checkbox.checked = true;
                                                }
                                            });
                                        }
                                    } else {
                                        subjectsContainer.innerHTML = '<div class="col-12"><div class="alert alert-warning">এই ক্লাসের জন্য কোন বিষয় পাওয়া যায়নি</div></div>';
                                    }
                                } else {
                                    subjectsContainer.innerHTML = '<div class="col-12"><div class="alert alert-danger">বিষয় লোড করতে সমস্যা হয়েছে</div></div>';
                                }
                            })
                            .catch(error => {
                                console.error('Error:', error);
                                subjectsContainer.innerHTML = '<div class="col-12"><div class="alert alert-danger">বিষয় লোড করতে সমস্যা হয়েছে</div></div>';
                            });
                    } else {
                        subjectSection.style.display = 'none';
                        subjectsContainer.innerHTML = '';
                    }
                });
                
                // Trigger change event if class is already selected (for pre-filled forms)
                if (classSelect.value) {
                    classSelect.dispatchEvent(new Event('change'));
                }
            }
        });
        
        // Function to check file size before upload
        function checkFileSize(input) {
            if (input.files && input.files[0]) {
                const file = input.files[0];
                const maxSize = 5 * 1024 * 1024; // 5MB in bytes as initial check
                
                if (file.size > maxSize) {
                    alert('ছবির সাইজ ৫MB এর বেশি। অনুগ্রহ করে ছোট সাইজের ছবি নির্বাচন করুন।');
                    input.value = '';
                    return;
                }
                
                // Show preview
                const reader = new FileReader();
                reader.onload = function(e) {
                    let preview = document.getElementById('photo-preview');
                    if (!preview) {
                        preview = document.createElement('img');
                        preview.id = 'photo-preview';
                        preview.className = 'img-thumbnail mt-2';
                        preview.style.maxWidth = '200px';
                        // Try to find the photo preview container, otherwise use input parent
                        const container = document.getElementById('photo-preview-container');
                        if (container) {
                            container.appendChild(preview);
                        } else {
                            input.parentNode.appendChild(preview);
                        }
                    }
                    preview.src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }
    </script>
</body>
</html>