<?php
// Display errors for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'إضافة طالب جديد';
include '../../includes/header.php';

// Session and Permission Check
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

checkLogin();

if (!hasPermission('add_student')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لإضافة طلاب.';
    header('Location: index.php');
    exit();
}

$db = getDB();
$errors = [];
$success_msg = '';

// 1. Governorates List
$governorates_list = [
    'بغداد', 'البصرة', 'نينوى', 'أربيل', 'السليمانية', 'دهوك', 'كركوك', 'صلاح الدين',
    'ديالى', 'الأنبار', 'بابل', 'كربلاء المقدسة', 'النجف الأشرف', 'القادسية', 'المثنى',
    'ذي قار', 'ميسان', 'واسط'
];

// 2. Fetch Colleges and Departments
$colleges_list = [];
$departments_list = [];

try {
    $colleges_sql = "SELECT College_ID, College FROM colleges ORDER BY College ASC";
    $colleges_list = $db->select($colleges_sql);

    $dept_sql = "SELECT Departement_ID, College_ID, Departement FROM departemenets ORDER BY Departement ASC";
    $departments_list = $db->select($dept_sql);
} catch (Exception $e) {
    $errors[] = 'خطأ في جلب بيانات القوائم: ' . $e->getMessage();
}

// Default Values
$data = [
    'full_name' => '',
    'national_id_number' => '',
    'guardian_phone' => '',
    'grade_level' => 'المرحلة الأولى',
    'gender' => 'male', // Changed default to English
    'enrollment_date' => date('Y-m-d'),
    'governorate' => '', 
    'college_id' => '',
    'department_id' => '',
    'addmission' => 'صباحي',
    'Yearly_Cost' => ''
];

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Sanitize Inputs
    $data['full_name'] = trim($_POST['full_name'] ?? '');
    $data['national_id_number'] = trim($_POST['national_id_number'] ?? '');
    $data['guardian_phone'] = trim($_POST['guardian_phone'] ?? '');
    $data['grade_level'] = $_POST['grade_level'] ?? '';
    $data['gender'] = $_POST['gender'] ?? 'male'; // Default fallback
    $data['enrollment_date'] = $_POST['enrollment_date'] ?? date('Y-m-d');
    $data['governorate'] = $_POST['governorate'] ?? ''; 
    $data['college_id'] = $_POST['college_id'] ?? '';
    $data['department_id'] = $_POST['department_id'] ?? '';
    $data['addmission'] = $_POST['addmission'] ?? '';
    $data['Yearly_Cost'] = trim($_POST['Yearly_Cost'] ?? '');

    // Validation
    if (empty($data['full_name'])) $errors[] = 'يرجى إدخال اسم الطالب الكامل.';
    if (empty($data['national_id_number'])) $errors[] = 'يرجى إدخال الرقم الوطني.';
    if (empty($data['college_id'])) $errors[] = 'يرجى اختيار الكلية.';
    if (empty($data['department_id'])) $errors[] = 'يرجى اختيار القسم.';

    // Check Required Files
    if (!isset($_FILES['school_doc']) || $_FILES['school_doc']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع الوثيقة المدرسية.';
    }
    if (!isset($_FILES['national_id_card']) || $_FILES['national_id_card']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع الهوية الوطنية.';
    }

    if (empty($errors)) {
        try {
            // Get College/Dept Names
            $coll_res = $db->select("SELECT College FROM colleges WHERE College_ID = ?", [$data['college_id']]);
            $college_name_str = $coll_res[0]['College'] ?? '';

            $dept_res = $db->select("SELECT Departement FROM departemenets WHERE Departement_ID = ?", [$data['department_id']]);
            $department_name_str = $dept_res[0]['Departement'] ?? '';

            // 1. Insert Student Data
            $sql = "INSERT INTO students 
                    (full_name, national_id_number, guardian_phone, grade_level, gender, enrollment_date, address, status, 
                     College_ID, College, Departement_ID, Departement, addmission, Yearly_Cost) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?)";
            
            $params = [
                $data['full_name'], $data['national_id_number'], $data['guardian_phone'],
                $data['grade_level'], $data['gender'], $data['enrollment_date'],
                $data['governorate'], $data['college_id'], $college_name_str,
                $data['department_id'], $department_name_str, $data['addmission'],
                $data['Yearly_Cost'] !== '' ? $data['Yearly_Cost'] : null
            ];

            $db->insert($sql, $params);
            
            // 2. Retrieve New Student ID
            $new_student_id = 0;
            // First try using the class method if it exists
            if (method_exists($db, 'lastInsertId')) {
                $new_student_id = $db->lastInsertId();
            } 
            // Fallback to SQL query
            if (!$new_student_id) {
                $res_id = $db->select("SELECT LAST_INSERT_ID() as last_id");
                $new_student_id = $res_id[0]['last_id'] ?? 0;
            }

            if ($new_student_id > 0) {
                // 3. Insert Documents into students_docs
                $pdo = method_exists($db, 'getConnection') ? $db->getConnection() : null;

                // Prepare file streams
                $school_doc = fopen($_FILES['school_doc']['tmp_name'], 'rb');
                $nat_id = fopen($_FILES['national_id_card']['tmp_name'], 'rb');
                $med_exam = !empty($_FILES['medical_exam']['tmp_name']) ? fopen($_FILES['medical_exam']['tmp_name'], 'rb') : null;
                $min_exam = !empty($_FILES['ministry_exam_card']['tmp_name']) ? fopen($_FILES['ministry_exam_card']['tmp_name'], 'rb') : null;

                if ($pdo) {
                    // Use PDO Param LOB for binary data safety
                    $doc_sql = "INSERT INTO students_docs 
                                (Student_ID, School_doc, National_ID_Card, Medical_exam, Ministry_exam_card) 
                                VALUES (:sid, :school, :nat, :med, :min)";
                    
                    $stmt = $pdo->prepare($doc_sql);
                    $stmt->bindParam(':sid', $new_student_id, PDO::PARAM_INT);
                    $stmt->bindParam(':school', $school_doc, PDO::PARAM_LOB);
                    $stmt->bindParam(':nat', $nat_id, PDO::PARAM_LOB);
                    $stmt->bindParam(':med', $med_exam, $med_exam ? PDO::PARAM_LOB : PDO::PARAM_NULL);
                    $stmt->bindParam(':min', $min_exam, $min_exam ? PDO::PARAM_LOB : PDO::PARAM_NULL);
                    $stmt->execute();
                } else {
                    // Fallback if PDO is not directly accessible (Not recommended for Large BLOBs)
                    $doc_sql = "INSERT INTO students_docs 
                                (Student_ID, School_doc, National_ID_Card, Medical_exam, Ministry_exam_card) 
                                VALUES (?, ?, ?, ?, ?)";
                    
                    $db->insert($doc_sql, [
                        $new_student_id,
                        file_get_contents($_FILES['school_doc']['tmp_name']),
                        file_get_contents($_FILES['national_id_card']['tmp_name']),
                        $med_exam ? file_get_contents($_FILES['medical_exam']['tmp_name']) : null,
                        $min_exam ? file_get_contents($_FILES['ministry_exam_card']['tmp_name']) : null
                    ]);
                }

                $_SESSION['success_message'] = 'تمت إضافة الطالب والوثائق بنجاح!';
                header('Location: index.php');
                exit();
            } else {
                $errors[] = 'فشل في الحصول على رقم الطالب الجديد.';
            }
        } catch (Exception $e) {
            $errors[] = 'خطأ في قاعدة البيانات: ' . $e->getMessage();
        }
    }
}
?>

<div class="content-area">
    <div class="page-header mb-4">
        <h2 class="page-title">إضافة طالب جديد</h2>
    </div>

    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-user-plus me-2"></i> استمارة التسجيل</h5>
        </div>
        <div class="card-body p-4">
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="POST" action="" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-12"><h6 class="text-muted border-bottom pb-2">المعلومات الأكاديمية</h6></div>

                    <div class="col-md-4">
                        <label class="form-label">الكلية <span class="text-danger">*</span></label>
                        <select class="form-select" id="college_id" name="college_id" required onchange="filterDepartments()">
                            <option value="" disabled selected>-- اختر الكلية --</option>
                            <?php foreach ($colleges_list as $college): ?>
                                <option value="<?= $college['College_ID'] ?>"><?= htmlspecialchars($college['College']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">القسم <span class="text-danger">*</span></label>
                        <select class="form-select" id="department_id" name="department_id" required>
                            <option value="" disabled selected>-- اختر الكلية أولاً --</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">المرحلة الدراسية</label>
                        <select class="form-select" name="grade_level">
                            <option value="المرحلة الأولى">المرحلة الأولى</option>
                            <option value="المرحلة الثانية">المرحلة الثانية</option>
                            <option value="المرحلة الثالثة">المرحلة الثالثة</option>
                            <option value="المرحلة الرابعة">المرحلة الرابعة</option>
                            <option value="المرحلة الخامسة">المرحلة الخامسة</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">نوع القبول</label>
                        <select class="form-select" name="addmission">
                            <option value="صباحي">صباحي</option>
                            <option value="مسائي">مسائي</option>
                            <option value="صباحي\شهداء">صباحي\شهداء</option>
                            <option value="مسائي\شهداء">مسائي\شهداء</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">التكلفة السنوية</label>
                        <input type="number" class="form-control" name="Yearly_Cost" placeholder="0">
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">تاريخ التسجيل</label>
                        <input type="date" class="form-control" name="enrollment_date" value="<?= date('Y-m-d') ?>">
                    </div>

                    <div class="col-12 mt-4"><h6 class="text-muted border-bottom pb-2">المعلومات الشخصية</h6></div>

                    <div class="col-md-6">
                        <label class="form-label">الاسم الكامل <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="full_name" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">الرقم الوطني <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="national_id_number" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">رقم الهاتف <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="guardian_phone" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">الجنس</label>
                        <select class="form-select" name="gender">
                            <option value="male" <?php echo ($data['gender'] == 'male') ? 'selected' : ''; ?>>ذكر</option>
                            <option value="female" <?php echo ($data['gender'] == 'female') ? 'selected' : ''; ?>>أنثى</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">المحافظة</label>
                        <select class="form-select" name="governorate">
                            <?php foreach ($governorates_list as $gov): ?>
                                <option value="<?= $gov ?>"><?= $gov ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-12 mt-4"><h6 class="text-muted border-bottom pb-2">الوثائق الثبوتية</h6></div>

                    <div class="col-md-6">
                        <label class="form-label">الوثيقة المدرسية <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="school_doc" accept="image/*,.pdf" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">الهوية الوطنية <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="national_id_card" accept="image/*,.pdf" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">الفحص الطبي</label>
                        <input class="form-control" type="file" name="medical_exam" accept="image/*,.pdf">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">بطاقة الامتحان الوزاري</label>
                        <input class="form-control" type="file" name="ministry_exam_card" accept="image/*,.pdf">
                    </div>
                </div>

                <div class="mt-5 d-flex justify-content-end gap-3">
                    <a href="index.php" class="btn btn-light border px-4">إلغاء</a>
                    <button type="submit" class="btn btn-primary px-5">حفظ بيانات الطالب</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const allDepartments = <?= json_encode($departments_list) ?>;
function filterDepartments() {
    const collegeId = document.getElementById('college_id').value;
    const deptSelect = document.getElementById('department_id');
    deptSelect.innerHTML = '<option value="" disabled selected>-- اختر القسم --</option>';
    
    allDepartments.filter(d => d.College_ID == collegeId).forEach(d => {
        const opt = document.createElement('option');
        opt.value = d.Departement_ID;
        opt.textContent = d.Departement;
        deptSelect.appendChild(opt);
    });
}
</script>

<?php include '../../includes/footer.php'; ?>