<?php
// edit_faculty.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('edit_college') && !hasPermission('edit_faculty')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لتعديل بيانات التدريسيين.';
    header('Location: index.php');
    exit();
}

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = 'رقم التدريسي غير صحيح.';
    header('Location: index.php');
    exit();
}

$teacher_id = (int)$_GET['id'];

// جلب البيانات الحالية
$current_data = [];
try {
    $stmt = "SELECT * FROM faculty WHERE Teacher_ID = ? LIMIT 1";
    if (method_exists($db, 'select')) {
        $result = $db->select($stmt, [$teacher_id]);
    } else {
        $q = $db->prepare($stmt);
        $q->execute([$teacher_id]);
        $result = $q->fetchAll(PDO::FETCH_ASSOC);
    }

    if (empty($result)) {
        $_SESSION['error_message'] = 'التدريسي غير موجود.';
        header('Location: index.php');
        exit();
    }
    $current_data = $result[0];
} catch (Exception $e) {
    $errors[] = 'خطأ في جلب البيانات: ' . $e->getMessage();
}

// القوائم
$colleges_list = [];
$departments_list = [];
$ranks_list = ['Assistant Lecturer' => 'مدرس مساعد', 'Lecturer' => 'مدرس', 'Assistant Professor' => 'أستاذ مساعد', 'Professor' => 'أستاذ'];
$certificates_list = ['BSc' => 'بكالوريوس (BSc)', 'High Diploma' => 'دبلوم عالي', 'MSc' => 'ماجستير (MSc)', 'PhD' => 'دكتوراه (PhD)', 'Other' => 'أخرى'];

try {
    $colleges_list = $db->select("SELECT College_ID, College FROM colleges ORDER BY College ASC");
    $departments_list = $db->select("SELECT Departement_ID, College_ID, Departement FROM departemenets ORDER BY Departement ASC");
} catch (Exception $e) { }

// تهيئة البيانات
$data = [
    'teacher_name' => $_POST['teacher_name'] ?? $current_data['Teacher'],
    'email'        => $_POST['email']        ?? $current_data['email'],
    'phone'        => $_POST['phone']        ?? $current_data['phone'],
    'college_id'   => $_POST['college_id']   ?? $current_data['College_ID'],
    'department_id'=> $_POST['department_id']?? $current_data['Department_ID'],
    'salary'       => $_POST['salary']       ?? $current_data['Salary'],
    'rank'         => $_POST['rank']         ?? $current_data['Rank'],
    'specialization'=> $_POST['specialization'] ?? $current_data['specialization'],
    'hiring_date'  => $_POST['hiring_date']  ?? $current_data['Hiring_date'],
    'gender'       => $_POST['gender']       ?? $current_data['Gender'],
    'certificate'  => $_POST['certificate']  ?? $current_data['Certificate']
];

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['salary']       = trim($_POST['salary'] ?? '');
    $data['rank']         = trim($_POST['rank'] ?? '');
    $data['specialization']= trim($_POST['specialization'] ?? '');
    $data['hiring_date']  = $_POST['hiring_date'] ?? '';
    $data['gender']       = $_POST['gender'] ?? 'male';
    $data['certificate']  = $_POST['certificate'] ?? '';

    if (empty($data['teacher_name'])) $errors[] = 'يرجى إدخال اسم التدريسي.';
    if (empty($data['college_id'])) $errors[] = 'يرجى اختيار الكلية.';
    if (empty($data['department_id'])) $errors[] = 'يرجى اختيار القسم.';

    if (empty($errors)) {
        try {
            $coll_res = $db->select("SELECT College FROM colleges WHERE College_ID = ? LIMIT 1", [$data['college_id']]);
            $college_name = $coll_res[0]['College'] ?? '';

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

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

            // تحديث البيانات الأساسية
            $sql = "UPDATE faculty SET 
                    Teacher=:name, email=:email, phone=:phone, College_ID=:cid, College=:cname, 
                    Department_ID=:did, Department=:dname, Salary=:salary, Rank=:rank, 
                    specialization=:spec, Hiring_date=:hdate, Gender=:gender, Certificate=:cert";
            
            // إضافة تحديث الصورة إذا تم رفعها
            if (isset($_FILES['teacher_pic']) && $_FILES['teacher_pic']['error'] == UPLOAD_ERR_OK) {
                $sql .= ", Teacher_pic=:pic";
            }
            
            $sql .= " WHERE Teacher_ID=:tid";
            
            $stmt = $pdo->prepare($sql);
            $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->bindValue(':salary', $data['salary'] !== '' ? $data['salary'] : 0);
            $stmt->bindParam(':rank', $data['rank']);
            $stmt->bindParam(':spec', $data['specialization']);
            $stmt->bindParam(':hdate', $data['hiring_date']);
            $stmt->bindParam(':gender', $data['gender']);
            $stmt->bindParam(':cert', $data['certificate']);
            $stmt->bindParam(':tid', $teacher_id, PDO::PARAM_INT);

            if (isset($_FILES['teacher_pic']) && $_FILES['teacher_pic']['error'] == UPLOAD_ERR_OK) {
                $pic_stream = fopen($_FILES['teacher_pic']['tmp_name'], 'rb');
                $stmt->bindParam(':pic', $pic_stream, PDO::PARAM_LOB);
            }

            $stmt->execute();

            // تحديث الوثائق إذا تم رفعها
            if ((isset($_FILES['national_id_card']) && $_FILES['national_id_card']['error'] == UPLOAD_ERR_OK) ||
                (isset($_FILES['residential_card']) && $_FILES['residential_card']['error'] == UPLOAD_ERR_OK) ||
                (isset($_FILES['certificate_file']) && $_FILES['certificate_file']['error'] == UPLOAD_ERR_OK)) {
                
                $doc_updates = [];
                $doc_params = [':tid' => $teacher_id];
                
                if ($_FILES['national_id_card']['error'] == UPLOAD_ERR_OK) {
                    $doc_updates[] = "National_ID_Card = :nat";
                }
                if ($_FILES['residential_card']['error'] == UPLOAD_ERR_OK) {
                    $doc_updates[] = "Residential_Card = :res";
                }
                if ($_FILES['certificate_file']['error'] == UPLOAD_ERR_OK) {
                    $doc_updates[] = "Certificate_Pic = :cert";
                }
                
                if (!empty($doc_updates)) {
                    $doc_sql = "UPDATE faculty_docs SET " . implode(", ", $doc_updates) . " WHERE Teacher_ID = :tid";
                    $doc_stmt = $pdo->prepare($doc_sql);
                    $doc_stmt->bindParam(':tid', $teacher_id, PDO::PARAM_INT);
                    
                    if ($_FILES['national_id_card']['error'] == UPLOAD_ERR_OK) {
                        $nat_stream = fopen($_FILES['national_id_card']['tmp_name'], 'rb');
                        $doc_stmt->bindParam(':nat', $nat_stream, PDO::PARAM_LOB);
                    }
                    if ($_FILES['residential_card']['error'] == UPLOAD_ERR_OK) {
                        $res_stream = fopen($_FILES['residential_card']['tmp_name'], 'rb');
                        $doc_stmt->bindParam(':res', $res_stream, PDO::PARAM_LOB);
                    }
                    if ($_FILES['certificate_file']['error'] == UPLOAD_ERR_OK) {
                        $cert_stream = fopen($_FILES['certificate_file']['tmp_name'], 'rb');
                        $doc_stmt->bindParam(':cert', $cert_stream, PDO::PARAM_LOB);
                    }
                    $doc_stmt->execute();
                }
            }

            $_SESSION['success_message'] = 'تم تعديل بيانات التدريسي والوثائق بنجاح!';
            header('Location: index.php');
            exit();

        } 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-warning text-dark">
            <h5 class="mb-0"><i class="fas fa-user-edit me-2"></i>تعديل: <?php echo htmlspecialchars($current_data['Teacher']); ?></h5>
        </div>
        <div class="card-body p-4">
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger"><ul><?php foreach ($errors as $error) echo "<li>$error</li>"; ?></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">اسم التدريسي <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' || $data['gender'] == 'Male') ? 'selected' : ''; ?>>ذكر</option>
                            <option value="female" <?php echo ($data['gender'] == 'female' || $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">الكلية <span class="text-danger">*</span></label>
                        <select class="form-select" id="college_id" name="college_id" required onchange="filterDepartments()">
                            <option value="" disabled>-- اختر الكلية --</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">القسم <span class="text-danger">*</span></label>
                        <select class="form-select" id="department_id" name="department_id" required></select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">الشهادة <span class="text-danger">*</span></label>
                        <select class="form-select" name="certificate" required>
                            <option value="" disabled>-- اختر الشهادة --</option>
                            <?php foreach ($certificates_list as $val => $lbl): ?>
                                <option value="<?php echo $val; ?>" <?php echo ($data['certificate'] == $val) ? 'selected' : ''; ?>><?php echo $lbl; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">اللقب العلمي</label>
                        <select class="form-select" name="rank">
                            <option value="">-- اختر --</option>
                            <?php foreach ($ranks_list as $val => $lbl): ?>
                                <option value="<?php echo $val; ?>" <?php echo ($data['rank'] == $val) ? 'selected' : ''; ?>><?php echo $lbl; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">التخصص</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">تحديث الصور والوثائق (اختياري)</h6></div>

                    <div class="col-md-6">
                        <label class="form-label">الصورة الشخصية</label>
                        <input class="form-control" type="file" name="teacher_pic" accept="image/*">
                    </div>

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

                    <div class="col-md-6">
                        <label class="form-label">بطاقة السكن</label>
                        <input class="form-control" type="file" name="residential_card" accept="image/*,.pdf">
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">نسخة الشهادة</label>
                        <input class="form-control" type="file" name="certificate_file" accept="image/*,.pdf">
                    </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-warning 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 savedCollegeId = "<?php echo $data['college_id']; ?>";
    const savedDeptId = "<?php echo $data['department_id']; ?>";

    function filterDepartments() {
        const collegeSelect = document.getElementById('college_id');
        const departmentSelect = document.getElementById('department_id');
        const selectedCollegeId = collegeSelect.value;
        let deptToSelect = (selectedCollegeId == savedCollegeId) ? savedDeptId : null;

        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 == deptToSelect) option.selected = true;
                    departmentSelect.appendChild(option);
                });
            }
        }
    }

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

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