<?php
// تفعيل عرض الأخطاء للتطوير
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'إضافة تدريسي جديد';
include '../../includes/header.php';

// التحقق من الجلسة والصلاحيات
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

checkLogin();

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

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

// ---------------------------------------------------------
// 1. جلب البيانات للقوائم المنسدلة (Colleges & Departments)
// ---------------------------------------------------------
$colleges_list = [];
$departments_list = [];

try {
    $colleges_sql = "SELECT College_ID, College FROM colleges ORDER BY College ASC";
    if (method_exists($db, 'select')) {
        $colleges_list = $db->select($colleges_sql);
    } else {
        $stmt = $db->prepare($colleges_sql);
        $stmt->execute();
        $colleges_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $dept_sql = "SELECT Departement_ID, College_ID, Departement FROM departemenets ORDER BY Departement ASC";
    if (method_exists($db, 'select')) {
        $departments_list = $db->select($dept_sql);
    } else {
        $stmt = $db->prepare($dept_sql);
        $stmt->execute();
        $departments_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    $errors[] = 'خطأ في جلب البيانات: ' . $e->getMessage();
}

// القيم الافتراضية
$data = [
    'teacher_name' => '', // Changed key to reflect 'Teacher'
    'email' => '',
    'phone' => '',
    'college_id' => '',
    'department_id' => '',
    'rank' => '',
    'Certificate' => '',       // New Field for Certificate Dropdown
    'specialization' => '',
    'Hiring_date' => date('Y-m-d'),
    'salary' => '',
    'gender' => 'male'
];

// ---------------------------------------------------------
// 2. معالجة الإرسال (POST)
// ---------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // استلام البيانات
    $data['teacher_name'] = trim($_POST['teacher_name'] ?? '');
    $data['email'] = trim($_POST['email'] ?? '');
    $data['phone'] = trim($_POST['phone'] ?? '');
    $data['college_id'] = trim($_POST['college_id'] ?? '');
    $data['department_id'] = trim($_POST['department_id'] ?? '');
    $data['rank'] = trim($_POST['rank'] ?? '');
    $data['Certificate'] = trim($_POST['Certificate'] ?? ''); // Certificate Dropdown Value
    $data['specialization'] = trim($_POST['specialization'] ?? '');
    $data['Hiring_date'] = $_POST['Hiring_date'] ?? date('Y-m-d');
    $data['salary'] = trim($_POST['salary'] ?? '');
    $data['gender'] = $_POST['gender'] ?? 'male';

    // التحقق من الحقول الإجبارية
    if (empty($data['teacher_name'])) $errors[] = 'يرجى إدخال اسم التدريسي.';
    if (empty($data['college_id'])) $errors[] = 'يرجى اختيار الكلية.';
    if (empty($data['department_id'])) $errors[] = 'يرجى اختيار القسم.';
    if (empty($data['Certificate'])) $errors[] = 'يرجى اختيار الشهادة (التحصيل العلمي).';

    // التحقق من الملفات (إجبارية)
    if (!isset($_FILES['teacher_pic']) || $_FILES['teacher_pic']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع الصورة الشخصية.';
    }
    if (!isset($_FILES['national_id_card']) || $_FILES['national_id_card']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع صورة البطاقة الوطنية.';
    }
    if (!isset($_FILES['residential_card']) || $_FILES['residential_card']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع صورة بطاقة السكن.';
    }
    if (!isset($_FILES['certificate_file']) || $_FILES['certificate_file']['error'] != UPLOAD_ERR_OK) {
        $errors[] = 'يرجى رفع نسخة من الشهادة.';
    }

    if (empty($errors)) {
        try {
            // جلب أسماء الكلية والقسم
            $college_name = '';
            if (method_exists($db, 'select')) {
                $c_res = $db->select("SELECT College FROM colleges WHERE College_ID = ?", [$data['college_id']]);
                $college_name = $c_res[0]['College'] ?? '';
            }

            $dept_name = '';
            if (method_exists($db, 'select')) {
                $d_res = $db->select("SELECT Departement FROM departemenets WHERE Departement_ID = ?", [$data['department_id']]);
                $dept_name = $d_res[0]['Departement'] ?? '';
            }

            $pdo = method_exists($db, 'getConnection') ? $db->getConnection() : $db;

            // 1. إدخال بيانات التدريسي في جدول FACULTY
            // Added 'Certificate' column here
            $sql = "INSERT INTO faculty 
                    (Teacher, email, phone, college_id, College, department_id, Department, 
                     rank, Certificate, specialization, Hiring_date, salary, gender, status, Teacher_pic) 
                    VALUES (:name, :email, :phone, :cid, :cname, :did, :dname, 
                            :rank, :Certificate, :spec, :hdate, :salary, :gender, 1, :pic)";
            
            $stmt = $pdo->prepare($sql);
            
            // قراءة الصورة الشخصية
            $teacher_pic = fopen($_FILES['teacher_pic']['tmp_name'], 'rb');

            $stmt->bindParam(':name', $data['teacher_name']);
            $stmt->bindParam(':email', $data['email']);
            $stmt->bindParam(':phone', $data['phone']);
            $stmt->bindParam(':cid', $data['college_id']);
            $stmt->bindParam(':cname', $college_name);
            $stmt->bindParam(':did', $data['department_id']);
            $stmt->bindParam(':dname', $dept_name);
            $stmt->bindParam(':rank', $data['rank']);
            $stmt->bindParam(':Certificate', $data['Certificate']); // Insert Dropdown Value
            $stmt->bindParam(':spec', $data['specialization']);
            $stmt->bindParam(':hdate', $data['Hiring_date']);
            $stmt->bindValue(':salary', $data['salary'] !== '' ? $data['salary'] : 0);
            $stmt->bindParam(':gender', $data['gender']);
            $stmt->bindParam(':pic', $teacher_pic, PDO::PARAM_LOB);

            $stmt->execute();
            
            $new_teacher_id = $pdo->lastInsertId();

            if ($new_teacher_id > 0) {
                // 2. إدخال الوثائق في جدول FACULTY_DOCS
                $nat_card = fopen($_FILES['national_id_card']['tmp_name'], 'rb');
                $res_card = fopen($_FILES['residential_card']['tmp_name'], 'rb');
                $cert_file = fopen($_FILES['certificate_file']['tmp_name'], 'rb'); // The actual file

                $doc_sql = "INSERT INTO faculty_docs (Teacher_ID, National_ID_Card, Residential_Card, Certificate_Pic) 
                            VALUES (:tid, :nat, :res, :cert)";
                
                $doc_stmt = $pdo->prepare($doc_sql);
                $doc_stmt->bindParam(':tid', $new_teacher_id, PDO::PARAM_INT);
                $doc_stmt->bindParam(':nat', $nat_card, PDO::PARAM_LOB);
                $doc_stmt->bindParam(':res', $res_card, PDO::PARAM_LOB);
                $doc_stmt->bindParam(':cert', $cert_file, PDO::PARAM_LOB);
                
                $doc_stmt->execute();

                $_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>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="../../index.php">الرئيسية</a></li>
                <li class="breadcrumb-item"><a href="index.php">التدريسيين</a></li>
                <li class="breadcrumb-item active">إضافة تدريسي</li>
            </ol>
        </nav>
    </div>

    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0"><i class="fas fa-user-tie 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 mb-3">المعلومات الشخصية</h6></div>

                    <div class="col-md-6">
                        <label class="form-label">اسم التدريسي (Teacher) <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="teacher_name" value="<?php echo htmlspecialchars($data['teacher_name']); ?>" required>
                    </div>

                    <div class="col-md-6">
                        <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-6">
                        <label class="form-label">رقم الهاتف</label>
                        <input type="text" class="form-control" name="phone" value="<?php echo htmlspecialchars($data['phone']); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">البريد الإلكتروني</label>
                        <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($data['email']); ?>">
                    </div>

                    <div class="col-12 mt-4"><h6 class="text-muted border-bottom pb-2 mb-3">المعلومات الأكاديمية والوظيفية</h6></div>

                    <div class="col-md-6">
                        <label class="form-label">الكلية (College) <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="<?php echo $college['College_ID']; ?>" <?php echo ($data['college_id'] == $college['College_ID']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($college['College']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">القسم (Department) <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">الشهادة (Certificate) <span class="text-danger">*</span></label>
                        <select class="form-select" name="Certificate" required>
                            <option value="" disabled selected>-- اختر الشهادة --</option>
                            <option value="BSc" <?php echo ($data['Certificate'] == 'BSc') ? 'selected' : ''; ?>>بكالوريوس (BSc)</option>
                            <option value="High Diploma" <?php echo ($data['Certificate'] == 'High Diploma') ? 'selected' : ''; ?>>دبلوم عالي</option>
                            <option value="MSc" <?php echo ($data['Certificate'] == 'MSc') ? 'selected' : ''; ?>>ماجستير (MSc)</option>
                            <option value="PhD" <?php echo ($data['Certificate'] == 'PhD') ? 'selected' : ''; ?>>دكتوراه (PhD)</option>
                            <option value="Other" <?php echo ($data['Certificate'] == 'Other') ? 'selected' : ''; ?>>أخرى</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">اللقب العلمي (Academic Rank)</label>
                        <select class="form-select" name="rank">
                            <option value="">-- اختر --</option>
                            <option value="Assistant Lecturer" <?php echo ($data['rank'] == 'Assistant Lecturer') ? 'selected' : ''; ?>>مدرس مساعد</option>
                            <option value="Lecturer" <?php echo ($data['rank'] == 'Lecturer') ? 'selected' : ''; ?>>مدرس</option>
                            <option value="Assistant Professor" <?php echo ($data['rank'] == 'Assistant Professor') ? 'selected' : ''; ?>>أستاذ مساعد</option>
                            <option value="Professor" <?php echo ($data['rank'] == 'Professor') ? 'selected' : ''; ?>>أستاذ</option>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">التخصص (Specialization)</label>
                        <input type="text" class="form-control" name="specialization" value="<?php echo htmlspecialchars($data['specialization']); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">تاريخ التعيين</label>
                        <input type="date" class="form-control" name="Hiring_date" value="<?php echo htmlspecialchars($data['Hiring_date']); ?>">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">الراتب الشهري</label>
                        <input type="number" class="form-control" name="salary" value="<?php echo htmlspecialchars($data['salary']); ?>">
                    </div>

                    <div class="col-12 mt-4"><h6 class="text-muted border-bottom pb-2 mb-3">الوثائق والمستمسكات (Faculty Docs)</h6></div>

                    <div class="col-md-6">
                        <label class="form-label bg-light border p-1 w-100">1. الصورة الشخصية (Teacher Picture) <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="teacher_pic" accept="image/*" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label bg-light border p-1 w-100">2. البطاقة الوطنية (National ID Card) <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 bg-light border p-1 w-100">3. بطاقة السكن (Residential Card) <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="residential_card" accept="image/*,.pdf" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label bg-light border p-1 w-100">4. نسخة الشهادة (Certificate File) <span class="text-danger">*</span></label>
                        <input class="form-control" type="file" name="certificate_file" accept="image/*,.pdf" required>
                        <div class="form-text small">يرجى رفع صورة ضوئية أو ملف PDF للشهادة التي تم اختيارها أعلاه.</div>
                    </div>

                </div>

                <div class="mt-4 d-flex justify-content-end gap-2">
                    <a href="index.php" class="btn btn-secondary">إلغاء</a>
                    <button type="submit" class="btn btn-primary px-5"><i class="fas fa-save me-2"></i>حفظ البيانات</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    const allDepartments = <?php echo json_encode($departments_list); ?>;
    const selectedDeptId = "<?php echo $data['department_id']; ?>";

    function filterDepartments() {
        const collegeSelect = document.getElementById('college_id');
        const departmentSelect = document.getElementById('department_id');
        const selectedCollegeId = collegeSelect.value;

        departmentSelect.innerHTML = '<option value="" disabled selected>-- اختر القسم --</option>';

        if (selectedCollegeId) {
            const filteredDepts = allDepartments.filter(dept => dept.College_ID == selectedCollegeId);

            if (filteredDepts.length > 0) {
                filteredDepts.forEach(dept => {
                    const option = document.createElement('option');
                    option.value = dept.Departement_ID;
                    option.textContent = dept.Departement;
                    if (dept.Departement_ID == selectedDeptId) {
                        option.selected = true;
                    }
                    departmentSelect.appendChild(option);
                });
            } else {
                const option = document.createElement('option');
                option.textContent = "لا توجد أقسام لهذه الكلية";
                option.disabled = true;
                departmentSelect.appendChild(option);
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        if (document.getElementById('college_id').value) {
            filterDepartments();
        }
    });
</script>

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