<?php
// pages/employees/edit_employee.php

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

$pageTitle = 'تعديل بيانات الموظف';
include '../../includes/header.php';

checkLogin();
if (!hasPermission('edit_employee')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لتعديل بيانات الموظفين.';
    header('Location: index.php');
    exit();
}

$db = getDB();
$errors = [];
$employee_id = $_GET['id'] ?? null;

if (!$employee_id) {
    header('Location: index.php');
    exit();
}

// جلب بيانات الموظف الحالية
$employee = $db->select("SELECT * FROM employees WHERE id = ?", [$employee_id]);
if (!$employee) {
    $_SESSION['error_message'] = 'الموظف غير موجود.';
    header('Location: index.php');
    exit();
}
$emp = $employee[0];

// جلب المواقع المسجلة مسبقاً للقوائم
$locations_result = $db->select("SELECT DISTINCT location_of_work FROM employees WHERE location_of_work IS NOT NULL AND location_of_work != ''");
$locations = array_column($locations_result, 'location_of_work');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $date_of_birth = trim($_POST['date_of_birth'] ?? '');
    $national_id_number = trim($_POST['national_id_number'] ?? '');
    $date_hired = trim($_POST['date_hired'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $marital_status = trim($_POST['marital_status'] ?? '');
    $gender = trim($_POST['gender'] ?? '');
    $salary = trim($_POST['salary'] ?? '0');
    $home_address = trim($_POST['home_address'] ?? '');
    $status = isset($_POST['status']) ? 1 : 0;

    // المنصب والموقع
    $position = ($_POST['position'] === 'other_position') ? trim($_POST['new_position'] ?? '') : trim($_POST['position'] ?? '');
    $location_of_work = ($_POST['location_of_work'] === 'other') ? trim($_POST['new_location_of_work'] ?? '') : trim($_POST['location_of_work'] ?? '');

    // التحقق
    if (empty($full_name)) $errors[] = 'الاسم الكامل مطلوب.';
    if (empty($position)) $errors[] = 'المنصب الوظيفي مطلوب.';

    // إعداد المجلدات
    $profile_dir = '../../uploads/profile_pictures/';
    $attach_dir = '../../uploads/attachments/';

    // تحديث صورة الملف الشخصي
    $profile_picture_path = $emp['profile_picture'];
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $file_name = uniqid('profile_') . '_' . basename($_FILES['profile_picture']['name']);
        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $profile_dir . $file_name)) {
            $profile_picture_path = 'uploads/profile_pictures/' . $file_name;
        }
    }

    // تحديث المرفقات
    $attachments = [
        'attachment1' => $emp['attachment1'],
        'attachment2' => $emp['attachment2'],
        'attachment3' => $emp['attachment3']
    ];

    for ($i = 1; $i <= 3; $i++) {
        $key = 'attachment' . $i;
        if (isset($_FILES[$key]) && $_FILES[$key]['error'] === UPLOAD_ERR_OK) {
            $file_name = uniqid('attach_') . '_' . basename($_FILES[$key]['name']);
            if (move_uploaded_file($_FILES[$key]['tmp_name'], $attach_dir . $file_name)) {
                $attachments[$key] = 'uploads/attachments/' . $file_name;
            }
        }
    }

    if (empty($errors)) {
        try {
            $query = "UPDATE `employees` SET 
                full_name = ?, position = ?, date_of_birth = ?, national_id_number = ?, 
                date_hired = ?, salary = ?, notes = ?, location_of_work = ?, 
                home_address = ?, marital_status = ?, gender = ?, status = ?,
                profile_picture = ?, attachment1 = ?, attachment2 = ?, attachment3 = ?
                WHERE id = ?";
            
            $params = [
                $full_name, $position, $date_of_birth, $national_id_number,
                $date_hired, $salary, $notes, $location_of_work,
                $home_address, $marital_status, $gender, $status,
                $profile_picture_path, $attachments['attachment1'], 
                $attachments['attachment2'], $attachments['attachment3'],
                $employee_id
            ];

            if ($db->update($query, $params)) {
                $_SESSION['success_message'] = 'تم تحديث بيانات الموظف بنجاح!';
                header("Location: index.php");
                exit();
            }
        } catch (Exception $e) {
            $errors[] = 'خطأ في قاعدة البيانات: ' . $e->getMessage();
        }
    }
}
?>

<div class="content-area">
    <div class="page-header mb-4">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <h2 class="page-title">تعديل بيانات: <?php echo htmlspecialchars($emp['full_name'] ?? ''); ?></h2>
            </div>
            <a href="index.php" class="btn btn-outline-secondary"><i class="fas fa-arrow-right me-2"></i>العودة للقائمة</a>
        </div>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul class="mb-0"><?php foreach ($errors as $error) echo "<li>$error</li>"; ?></ul>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm border-0">
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-12 text-center mb-3">
                        <?php if (!empty($emp['profile_picture'])): ?>
                            <img src="../../<?php echo $emp['profile_picture']; ?>" class="rounded-circle img-thumbnail" style="width: 120px; height: 120px; object-fit: cover;">
                        <?php else: ?>
                            <div class="bg-light d-inline-block rounded-circle p-4"><i class="fas fa-user fa-3x text-secondary"></i></div>
                        <?php endif; ?>
                    </div>

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

                    <div class="col-md-6">
                        <label class="form-label">الاسم الكامل</label>
                        <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($emp['full_name'] ?? ''); ?>" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">المنصب الوظيفي</label>
                        <?php 
                            $preset_positions = ['طبيب', 'ممرض', 'صيدلاني', 'كيميائي', 'إحصائي', 'إداري', 'موظف', 'متابع'];
                            $current_pos = $emp['position'] ?? '';
                            $is_other_pos = !in_array($current_pos, $preset_positions) && !empty($current_pos);
                        ?>
                        <select class="form-select select2-basic" id="position" name="position" required>
                            <option value="">اختر المنصب...</option>
                            <?php foreach ($preset_positions as $p): ?>
                                <option value="<?php echo $p; ?>" <?php echo ($current_pos === $p) ? 'selected' : ''; ?>><?php echo $p; ?></option>
                            <?php endforeach; ?>
                            <option value="other_position" <?php echo $is_other_pos ? 'selected' : ''; ?>>أخرى (إدخال يدوي)...</option>
                        </select>
                    </div>

                    <div class="col-md-6" id="new_position_container" style="display: <?php echo $is_other_pos ? 'block' : 'none'; ?>;">
                        <label class="form-label text-primary">المنصب الجديد</label>
                        <input type="text" class="form-control border-primary" id="new_position" name="new_position" value="<?php echo $is_other_pos ? htmlspecialchars($current_pos) : ''; ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">تاريخ الميلاد</label>
                  <input type="date" class="form-control" name="date_of_birth" value="<?php echo ($emp['date_of_birth'] == '0000-00-00') ? '' : ($emp['date_of_birth'] ?? ''); ?>">
                  </div>

                    <div class="col-md-3">
                        <label class="form-label">رقم الهوية</label>
                        <input type="text" class="form-control" name="national_id_number" value="<?php echo htmlspecialchars($emp['national_id_number'] ?? ''); ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">تاريخ التعيين</label>
                 <input type="date" class="form-control" name="date_hired" value="<?php echo ($emp['date_hired'] == '0000-00-00') ? '' : ($emp['date_hired'] ?? ''); ?>" required>
                 </div>

                    <div class="col-md-3">
                        <label class="form-label">الراتب</label>
                        <input type="number" step="0.01" class="form-control" name="salary" value="<?php echo $emp['salary'] ?? '0'; ?>" required>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label">موقع العمل</label>
                        <select class="form-select select2-basic" id="location_of_work" name="location_of_work" required>
                            <option value="">اختر الموقع...</option>
                            <?php foreach ($locations as $loc): ?>
                                <option value="<?php echo htmlspecialchars($loc ?? ''); ?>" <?php echo (($emp['location_of_work'] ?? '') === $loc) ? 'selected' : ''; ?>><?php echo htmlspecialchars($loc ?? ''); ?></option>
                            <?php endforeach; ?>
                            <option value="other">أخرى...</option>
                        </select>
                    </div>

                    <div class="col-md-6" id="new_location_container" style="display:none;">
                        <label class="form-label text-primary">أدخل الموقع الجديد</label>
                        <input type="text" class="form-control border-primary" id="new_location_of_work" name="new_location_of_work">
                    </div>

                    <div class="col-md-12">
                        <label class="form-label">عنوان السكن</label>
                        <input type="text" class="form-control" name="home_address" value="<?php echo htmlspecialchars($emp['home_address'] ?? ''); ?>" required>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">الحالة الزوجية</label>
                        <select class="form-select" name="marital_status" required>
                            <option value="single" <?php echo ($emp['marital_status'] ?? '')=='single'?'selected':''; ?>>أعزب</option>
                            <option value="married" <?php echo ($emp['marital_status'] ?? '')=='married'?'selected':''; ?>>متزوج</option>
                            <option value="divorced" <?php echo ($emp['marital_status'] ?? '')=='divorced'?'selected':''; ?>>مطلق</option>
                            <option value="widowed" <?php echo ($emp['marital_status'] ?? '')=='widowed'?'selected':''; ?>>أرمل</option>
                        </select>
                    </div>

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

                    <div class="col-md-4 d-flex align-items-end">
                        <div class="form-check form-switch mb-2">
                            <input class="form-check-input" type="checkbox" name="status" id="status" <?php echo ($emp['status'] ?? 0)==1?'checked':''; ?>>
                            <label class="form-check-label" for="status">موظف فعال</label>
                        </div>
                    </div>

                    <div class="col-md-12">
                        <label class="form-label">ملاحظات</label>
                        <textarea class="form-control" name="notes" rows="2"><?php echo htmlspecialchars($emp['notes'] ?? ''); ?></textarea>
                    </div>

                    <hr class="my-4">
                    <h5>المرفقات الحالية والمستندات</h5>
                    <div class="row">
                        <?php for($i=1; $i<=3; $i++): $field = 'attachment'.$i; ?>
                        <div class="col-md-4 mb-3">
                            <label class="small">مرفق <?php echo $i; ?></label>
                            <?php if (!empty($emp[$field])): ?>
                                <div class="mb-2">
                                    <a href="../../<?php echo $emp[$field]; ?>" target="_blank" class="btn btn-sm btn-light border text-primary">
                                        <i class="fas fa-file-download me-1"></i> عرض الحالي
                                    </a>
                                </div>
                            <?php endif; ?>
                            <input type="file" class="form-control form-control-sm" name="<?php echo $field; ?>">
                        </div>
                        <?php endfor; ?>
                    </div>

                    <div class="col-12 text-start mt-4">
                        <button type="submit" class="btn btn-warning btn-lg px-5">
                            <i class="fas fa-edit me-2"></i> تحديث البيانات
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<style>
    .select2-container--default .select2-selection--single { height: 38px; border: 1px solid #dee2e6; border-radius: 0.375rem; }
    .select2-container--default .select2-selection--single .select2-selection__rendered { line-height: 36px; padding-right: 12px; }
    .select2-container--default .select2-selection--single .select2-selection__arrow { height: 36px; }
</style>

<script>
$(document).ready(function() {
    // تفعيل Select2
    $('.select2-basic').select2({
        dir: "rtl",
        width: '100%'
    });

    const posSelect = $('#position');
    const posContainer = $('#new_position_container');
    const locSelect = $('#location_of_work');
    const locContainer = $('#new_location_container');

    posSelect.on('change', function() {
        if (this.value === 'other_position') {
            posContainer.fadeIn();
        } else {
            posContainer.hide();
        }
    });

    locSelect.on('change', function() {
        if (this.value === 'other') {
            locContainer.fadeIn();
        } else {
            locContainer.hide();
        }
    });
});
</script>

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