<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

set_error_handler(function ($severity, $message, $file, $line) {
    http_response_code(500);
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace;direction:ltr'>";
    echo "<h2>PHP ERROR</h2>";
    echo "<p><b>Message:</b> " . htmlspecialchars((string)$message, ENT_QUOTES, 'UTF-8') . "</p>";
    echo "<p><b>File:</b> " . htmlspecialchars((string)$file, ENT_QUOTES, 'UTF-8') . "</p>";
    echo "<p><b>Line:</b> " . (int)$line . "</p>";
    echo "</div>";
    exit;
});

set_exception_handler(function ($e) {
    http_response_code(500);
    echo "<div style='background:#111;color:#fff;padding:20px;font-family:monospace;direction:ltr'>";
    echo "<h2>UNCAUGHT EXCEPTION</h2>";
    echo "<p><b>Message:</b> " . htmlspecialchars((string)$e->getMessage(), ENT_QUOTES, 'UTF-8') . "</p>";
    echo "<p><b>File:</b> " . htmlspecialchars((string)$e->getFile(), ENT_QUOTES, 'UTF-8') . "</p>";
    echo "<p><b>Line:</b> " . (int)$e->getLine() . "</p>";
    echo "</div>";
    exit;
});

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../inc/auth.php';

if (empty($_SESSION['user_id'])) {
    header('Location: ../index.html');
    exit;
}

$pdo = db();
if (!$pdo instanceof PDO) {
    http_response_code(500);
    exit('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('table_exists')) {
    function table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];

        if (isset($cache[$table])) {
            return $cache[$table];
        }

        $sql = "
            SELECT COUNT(*)
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = :table
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':table' => $table]);

        $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        return $cache[$table];
    }
}

if (!function_exists('table_has_column')) {
    function table_has_column(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];

        $key = $table . '.' . $column;
        if (isset($cache[$key])) {
            return $cache[$key];
        }

        $sql = "
            SELECT COUNT(*)
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_SCHEMA = DATABASE()
              AND TABLE_NAME = :table
              AND COLUMN_NAME = :column
        ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':table'  => $table,
            ':column' => $column,
        ]);

        $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        return $cache[$key];
    }
}

if (!function_exists('normalize_date_input')) {
    function normalize_date_input(?string $value): ?string
    {
        $value = trim((string)$value);
        if ($value === '') {
            return null;
        }

        $ts = strtotime($value);
        if ($ts === false) {
            return null;
        }

        return date('Y-m-d', $ts);
    }
}

if (!function_exists('doc_status_meta')) {
    function doc_status_meta($date, bool $required = true): array
    {
        if (!$required) {
            return ['غير مطلوب', 'not-required', null];
        }

        $date = trim((string)($date ?? ''));

        if ($date === '' || $date === '0000-00-00') {
            return ['غير مدخل', 'missing', null];
        }

        $todayTs = strtotime(date('Y-m-d'));
        $dateTs  = strtotime($date);

        if ($todayTs === false || $dateTs === false) {
            return ['غير مدخل', 'missing', null];
        }

        $days = (int) floor(($dateTs - $todayTs) / 86400);

        if ($days < 0) {
            return ['منتهي', 'expired', $days];
        }

        if ($days <= 30) {
            return ['قريب', 'warning', $days];
        }

        return ['سليم', 'valid', $days];
    }
}

if (!function_exists('status_hint')) {
    function status_hint(?int $days, string $status): string
    {
        if ($status === 'غير مطلوب') {
            return 'هذا المستند غير مطلوب لهذا الشخص';
        }

        if ($status === 'غير مدخل') {
            return 'لم يتم إدخال التاريخ';
        }

        if ($days === null) {
            return $status;
        }

        if ($days < 0) {
            return 'منتهي منذ ' . abs($days) . ' يوم';
        }

        return 'متبقي ' . $days . ' يوم';
    }
}

if (!function_exists('safe_unlink')) {
    function safe_unlink(string $path): void
    {
        if (is_file($path)) {
            @unlink($path);
        }
    }
}

if (!function_exists('sync_doc_days_left')) {
    function sync_doc_days_left(?string $expiryDate): ?int
    {
        $expiryDate = trim((string)$expiryDate);
        if ($expiryDate === '' || $expiryDate === '0000-00-00') {
            return null;
        }

        $today = new DateTime('today', new DateTimeZone('Asia/Dubai'));
        $exp   = new DateTime($expiryDate, new DateTimeZone('Asia/Dubai'));

        return (int)$today->diff($exp)->format('%r%a');
    }
}

if (!function_exists('delete_single_doc_alert_now')) {
    function delete_single_doc_alert_now(PDO $pdo, int $employeeId, int $docsId, string $docKey): void
    {
        if (!table_exists($pdo, 'hr_document_alerts')) {
            return;
        }

        $stmt = $pdo->prepare("
            DELETE FROM hr_document_alerts
            WHERE employee_id = :employee_id
              AND docs_id = :docs_id
              AND document_key = :document_key
        ");
        $stmt->execute([
            ':employee_id'  => $employeeId,
            ':docs_id'      => $docsId,
            ':document_key' => $docKey,
        ]);
    }
}

if (!function_exists('sync_single_doc_alert_now')) {
    function sync_single_doc_alert_now(
        PDO $pdo,
        int $employeeId,
        int $docsId,
        int $branchId,
        string $docKey,
        string $docLabel,
        ?string $expiryDate
    ): void {
        if (!table_exists($pdo, 'hr_document_alerts')) {
            return;
        }

        delete_single_doc_alert_now($pdo, $employeeId, $docsId, $docKey);

        $daysLeft = sync_doc_days_left($expiryDate);
        if ($daysLeft === null) {
            return;
        }

        if ($daysLeft > 30) {
            return;
        }

        $hasBranchId   = table_has_column($pdo, 'hr_document_alerts', 'branch_id');
        $hasAlertType  = table_has_column($pdo, 'hr_document_alerts', 'alert_type');
        $hasIsRead     = table_has_column($pdo, 'hr_document_alerts', 'is_read');
        $hasIsResolved = table_has_column($pdo, 'hr_document_alerts', 'is_resolved');

        $status = ($daysLeft < 0) ? 'expired' : 'warning';

        $columns = [
            'employee_id',
            'docs_id',
            'document_key',
            'document_label',
            'expiry_date',
            'days_left',
            'status',
            'created_at',
        ];

        $values = [
            ':employee_id',
            ':docs_id',
            ':document_key',
            ':document_label',
            ':expiry_date',
            ':days_left',
            ':status',
            'NOW()',
        ];

        $params = [
            ':employee_id'    => $employeeId,
            ':docs_id'        => $docsId,
            ':document_key'   => $docKey,
            ':document_label' => $docLabel,
            ':expiry_date'    => $expiryDate,
            ':days_left'      => $daysLeft,
            ':status'         => $status,
        ];

        if ($hasBranchId) {
            $columns[] = 'branch_id';
            $values[]  = ':branch_id';
            $params[':branch_id'] = $branchId;
        }

        if ($hasAlertType) {
            $columns[] = 'alert_type';
            $values[]  = ':alert_type';
            $params[':alert_type'] = 'document';
        }

        if ($hasIsRead) {
            $columns[] = 'is_read';
            $values[]  = '0';
        }

        if ($hasIsResolved) {
            $columns[] = 'is_resolved';
            $values[]  = '0';
        }

        $sql = "
            INSERT INTO hr_document_alerts
            (" . implode(', ', $columns) . ")
            VALUES
            (" . implode(', ', $values) . ")
        ";

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    }
}

if (!function_exists('upload_doc_file')) {
    function upload_doc_file(array $file, string $prefix, int $personId): array
    {
        if (!isset($file['error']) || (int)$file['error'] === UPLOAD_ERR_NO_FILE) {
            return ['ok' => true, 'path' => null, 'error' => null];
        }

        if ((int)$file['error'] !== UPLOAD_ERR_OK) {
            return ['ok' => false, 'path' => null, 'error' => 'حدث خطأ أثناء رفع الملف.'];
        }

        if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
            return ['ok' => false, 'path' => null, 'error' => 'الملف المرفوع غير صالح.'];
        }

        if ((int)($file['size'] ?? 0) > 8 * 1024 * 1024) {
            return ['ok' => false, 'path' => null, 'error' => 'حجم الملف كبير. الحد الأقصى 8 ميجابايت.'];
        }

        $allowedExt = ['pdf', 'jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));

        if (!in_array($ext, $allowedExt, true)) {
            return ['ok' => false, 'path' => null, 'error' => 'نوع الملف غير مسموح.'];
        }

        $mime = '';
        if (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            if ($finfo) {
                $mime = (string) finfo_file($finfo, $file['tmp_name']);
                finfo_close($finfo);
            }
        }

        $allowedMime = [
            'application/pdf',
            'image/jpeg',
            'image/png',
            'image/webp',
        ];

        if ($mime !== '' && !in_array($mime, $allowedMime, true)) {
            return ['ok' => false, 'path' => null, 'error' => 'نوع الملف غير آمن.'];
        }

        $baseDir = __DIR__ . '/uploads/employee_docs/';
        $personDirName = 'EMP_' . $personId;
        $personDir = $baseDir . $personDirName . '/';

        if (!is_dir($personDir) && !mkdir($personDir, 0775, true) && !is_dir($personDir)) {
            return ['ok' => false, 'path' => null, 'error' => 'تعذر إنشاء مجلد الشخص.'];
        }

        $filename = $prefix . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $targetPath = $personDir . $filename;

        if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
            return ['ok' => false, 'path' => null, 'error' => 'تعذر حفظ الملف على الخادم.'];
        }

        return [
            'ok'    => true,
            'path'  => 'uploads/employee_docs/' . $personDirName . '/' . $filename,
            'error' => null,
        ];
    }
}

if (!function_exists('person_type_ar')) {
    function person_type_ar(string $type): string
    {
        return match ($type) {
            'owner'             => 'صاحب شركة',
            'special_affiliate' => 'منتسب خاص',
            'partner'           => 'شريك',
            default             => 'موظف',
        };
    }
}

if (!function_exists('format_datetime_ar')) {
    function format_datetime_ar(?string $value): string
    {
        $value = trim((string)($value ?? ''));
        if ($value === '' || $value === '0000-00-00 00:00:00') {
            return '—';
        }

        $ts = strtotime($value);
        if ($ts === false) {
            return '—';
        }

        return date('Y-m-d h:i A', $ts);
    }
}

$personId = (int)($_GET['id'] ?? $_POST['employee_id'] ?? 0);
if ($personId <= 0) {
    http_response_code(400);
    exit('رقم الشخص غير صحيح');
}

if (!table_exists($pdo, 'employees')) {
    http_response_code(500);
    exit('جدول employees غير موجود');
}

if (!table_exists($pdo, 'employee_docs')) {
    http_response_code(500);
    exit('جدول employee_docs غير موجود');
}

$hasContractExpiry = table_has_column($pdo, 'employee_docs', 'contract_expiry');
$hasDrivingExpiry  = table_has_column($pdo, 'employee_docs', 'driving_license_expiry');

$hasVisaFile       = table_has_column($pdo, 'employee_docs', 'visa_file');
$hasEidFile        = table_has_column($pdo, 'employee_docs', 'emirates_id_file');
$hasInsuranceFile  = table_has_column($pdo, 'employee_docs', 'insurance_file');
$hasPassportFile   = table_has_column($pdo, 'employee_docs', 'passport_file');
$hasContractFile   = table_has_column($pdo, 'employee_docs', 'contract_file');
$hasDrivingFile    = table_has_column($pdo, 'employee_docs', 'driving_license_file');

$hasUpdatedAt      = table_has_column($pdo, 'employee_docs', 'updated_at');
$hasCreatedAt      = table_has_column($pdo, 'employee_docs', 'created_at');

$selectContract  = $hasContractExpiry ? 'd.contract_expiry' : 'NULL AS contract_expiry';
$selectDriving   = $hasDrivingExpiry ? 'd.driving_license_expiry' : 'NULL AS driving_license_expiry';
$selectVisaFile  = $hasVisaFile ? 'd.visa_file' : 'NULL AS visa_file';
$selectEidFile   = $hasEidFile ? 'd.emirates_id_file' : 'NULL AS emirates_id_file';
$selectInsFile   = $hasInsuranceFile ? 'd.insurance_file' : 'NULL AS insurance_file';
$selectPassFile  = $hasPassportFile ? 'd.passport_file' : 'NULL AS passport_file';
$selectContFile  = $hasContractFile ? 'd.contract_file' : 'NULL AS contract_file';
$selectDrivFile  = $hasDrivingFile ? 'd.driving_license_file' : 'NULL AS driving_license_file';
$selectUpdatedAt = $hasUpdatedAt ? 'd.updated_at' : 'NULL AS updated_at';
$selectCreatedAt = $hasCreatedAt ? 'd.created_at' : 'NULL AS created_at';

$sql = "
    SELECT
        e.id,
        e.name,
        e.branch_id,
        e.person_type,
        e.require_visa,
        e.require_contract,
        e.require_driving_license,
        d.id AS docs_id,
        d.employee_id AS doc_employee_id,
        d.visa_expiry,
        d.emirates_id_expiry,
        d.insurance_expiry,
        d.passport_expiry,
        {$selectContract},
        {$selectDriving},
        {$selectVisaFile},
        {$selectEidFile},
        {$selectInsFile},
        {$selectPassFile},
        {$selectContFile},
        {$selectDrivFile},
        {$selectUpdatedAt},
        {$selectCreatedAt}
    FROM employees e
    LEFT JOIN employee_docs d ON d.employee_id = e.id
    WHERE e.id = :id
    LIMIT 1
";

$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => $personId]);
$person = $stmt->fetch();

if (!$person) {
    http_response_code(404);
    exit('الشخص غير موجود');
}

$requireVisa     = (int)($person['require_visa'] ?? 1) === 1;
$requireContract = (int)($person['require_contract'] ?? 1) === 1;
$requireDriving  = (int)($person['require_driving_license'] ?? 0) === 1;

$errors  = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $visaExpiry      = normalize_date_input($_POST['visa_expiry'] ?? null);
    $eidExpiry       = normalize_date_input($_POST['emirates_id_expiry'] ?? null);
    $insuranceExpiry = normalize_date_input($_POST['insurance_expiry'] ?? null);
    $passportExpiry  = normalize_date_input($_POST['passport_expiry'] ?? null);
    $contractExpiry  = $hasContractExpiry ? normalize_date_input($_POST['contract_expiry'] ?? null) : null;
    $drivingExpiry   = $hasDrivingExpiry ? normalize_date_input($_POST['driving_license_expiry'] ?? null) : null;

    $rawVisa      = trim((string)($_POST['visa_expiry'] ?? ''));
    $rawEid       = trim((string)($_POST['emirates_id_expiry'] ?? ''));
    $rawInsurance = trim((string)($_POST['insurance_expiry'] ?? ''));
    $rawPassport  = trim((string)($_POST['passport_expiry'] ?? ''));
    $rawContract  = trim((string)($_POST['contract_expiry'] ?? ''));
    $rawDriving   = trim((string)($_POST['driving_license_expiry'] ?? ''));

    if ($requireVisa && $rawVisa !== '' && $visaExpiry === null) {
        $errors[] = 'تاريخ الإقامة غير صحيح.';
    }
    if ($rawEid !== '' && $eidExpiry === null) {
        $errors[] = 'تاريخ الهوية غير صحيح.';
    }
    if ($rawInsurance !== '' && $insuranceExpiry === null) {
        $errors[] = 'تاريخ التأمين غير صحيح.';
    }
    if ($rawPassport !== '' && $passportExpiry === null) {
        $errors[] = 'تاريخ الجواز غير صحيح.';
    }
    if ($hasContractExpiry && $requireContract && $rawContract !== '' && $contractExpiry === null) {
        $errors[] = 'تاريخ عقد العمل غير صحيح.';
    }
    if ($hasDrivingExpiry && $requireDriving && $rawDriving !== '' && $drivingExpiry === null) {
        $errors[] = 'تاريخ رخصة القيادة غير صحيح.';
    }

    $newVisaFilePath      = null;
    $newEidFilePath       = null;
    $newInsuranceFilePath = null;
    $newPassportFilePath  = null;
    $newContractFilePath  = null;
    $newDrivingFilePath   = null;

    if (!$errors && $hasVisaFile && isset($_FILES['visa_file'])) {
        $res = upload_doc_file($_FILES['visa_file'], 'visa', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف الإقامة: ' . $res['error'];
        } else {
            $newVisaFilePath = $res['path'];
        }
    }

    if (!$errors && $hasEidFile && isset($_FILES['emirates_id_file'])) {
        $res = upload_doc_file($_FILES['emirates_id_file'], 'eid', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف الهوية: ' . $res['error'];
        } else {
            $newEidFilePath = $res['path'];
        }
    }

    if (!$errors && $hasInsuranceFile && isset($_FILES['insurance_file'])) {
        $res = upload_doc_file($_FILES['insurance_file'], 'insurance', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف التأمين: ' . $res['error'];
        } else {
            $newInsuranceFilePath = $res['path'];
        }
    }

    if (!$errors && $hasPassportFile && isset($_FILES['passport_file'])) {
        $res = upload_doc_file($_FILES['passport_file'], 'passport', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف الجواز: ' . $res['error'];
        } else {
            $newPassportFilePath = $res['path'];
        }
    }

    if (!$errors && $hasContractFile && isset($_FILES['contract_file'])) {
        $res = upload_doc_file($_FILES['contract_file'], 'contract', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف عقد العمل: ' . $res['error'];
        } else {
            $newContractFilePath = $res['path'];
        }
    }

    if (!$errors && $hasDrivingFile && isset($_FILES['driving_license_file'])) {
        $res = upload_doc_file($_FILES['driving_license_file'], 'driving', $personId);
        if (!$res['ok']) {
            $errors[] = 'ملف رخصة القيادة: ' . $res['error'];
        } else {
            $newDrivingFilePath = $res['path'];
        }
    }

    if (!$errors) {
        $oldStmt = $pdo->prepare($sql);
        $oldStmt->execute([':id' => $personId]);
        $oldData = $oldStmt->fetch() ?: [];

        $uploadedPaths = array_filter([
            $newVisaFilePath,
            $newEidFilePath,
            $newInsuranceFilePath,
            $newPassportFilePath,
            $newContractFilePath,
            $newDrivingFilePath,
        ]);

        try {
            $pdo->beginTransaction();

            $docsId = (int)($oldData['docs_id'] ?? 0);

            $existsStmt = $pdo->prepare("SELECT COUNT(*) FROM employee_docs WHERE employee_id = :employee_id");
            $existsStmt->execute([':employee_id' => $personId]);
            $exists = (int)$existsStmt->fetchColumn() > 0;

            if ($exists) {
                $parts = [
                    "visa_expiry = :visa_expiry",
                    "emirates_id_expiry = :eid_expiry",
                    "insurance_expiry = :insurance_expiry",
                    "passport_expiry = :passport_expiry",
                ];

                $params = [
                    ':visa_expiry'      => $visaExpiry,
                    ':eid_expiry'       => $eidExpiry,
                    ':insurance_expiry' => $insuranceExpiry,
                    ':passport_expiry'  => $passportExpiry,
                    ':employee_id'      => $personId,
                ];

                if ($hasContractExpiry) {
                    $parts[] = "contract_expiry = :contract_expiry";
                    $params[':contract_expiry'] = $contractExpiry;
                }

                if ($hasDrivingExpiry) {
                    $parts[] = "driving_license_expiry = :driving_expiry";
                    $params[':driving_expiry'] = $drivingExpiry;
                }

                if ($hasVisaFile && $newVisaFilePath !== null) {
                    $parts[] = "visa_file = :visa_file";
                    $params[':visa_file'] = $newVisaFilePath;
                }

                if ($hasEidFile && $newEidFilePath !== null) {
                    $parts[] = "emirates_id_file = :eid_file";
                    $params[':eid_file'] = $newEidFilePath;
                }

                if ($hasInsuranceFile && $newInsuranceFilePath !== null) {
                    $parts[] = "insurance_file = :insurance_file";
                    $params[':insurance_file'] = $newInsuranceFilePath;
                }

                if ($hasPassportFile && $newPassportFilePath !== null) {
                    $parts[] = "passport_file = :passport_file";
                    $params[':passport_file'] = $newPassportFilePath;
                }

                if ($hasContractFile && $newContractFilePath !== null) {
                    $parts[] = "contract_file = :contract_file";
                    $params[':contract_file'] = $newContractFilePath;
                }

                if ($hasDrivingFile && $newDrivingFilePath !== null) {
                    $parts[] = "driving_license_file = :driving_file";
                    $params[':driving_file'] = $newDrivingFilePath;
                }

                if ($hasUpdatedAt) {
                    $parts[] = "updated_at = NOW()";
                }

                $updateSql = "UPDATE employee_docs SET " . implode(", ", $parts) . " WHERE employee_id = :employee_id";
                $updateStmt = $pdo->prepare($updateSql);
                $updateStmt->execute($params);

                $idStmt = $pdo->prepare("SELECT id FROM employee_docs WHERE employee_id = :employee_id LIMIT 1");
                $idStmt->execute([':employee_id' => $personId]);
                $docsId = (int)$idStmt->fetchColumn();
            } else {
                $columns = [
                    "employee_id",
                    "visa_expiry",
                    "emirates_id_expiry",
                    "insurance_expiry",
                    "passport_expiry",
                ];

                $values = [
                    ":employee_id",
                    ":visa_expiry",
                    ":eid_expiry",
                    ":insurance_expiry",
                    ":passport_expiry",
                ];

                $params = [
                    ':employee_id'      => $personId,
                    ':visa_expiry'      => $visaExpiry,
                    ':eid_expiry'       => $eidExpiry,
                    ':insurance_expiry' => $insuranceExpiry,
                    ':passport_expiry'  => $passportExpiry,
                ];

                if ($hasContractExpiry) {
                    $columns[] = "contract_expiry";
                    $values[] = ":contract_expiry";
                    $params[':contract_expiry'] = $contractExpiry;
                }

                if ($hasDrivingExpiry) {
                    $columns[] = "driving_license_expiry";
                    $values[] = ":driving_expiry";
                    $params[':driving_expiry'] = $drivingExpiry;
                }

                if ($hasVisaFile) {
                    $columns[] = "visa_file";
                    $values[] = ":visa_file";
                    $params[':visa_file'] = $newVisaFilePath;
                }

                if ($hasEidFile) {
                    $columns[] = "emirates_id_file";
                    $values[] = ":eid_file";
                    $params[':eid_file'] = $newEidFilePath;
                }

                if ($hasInsuranceFile) {
                    $columns[] = "insurance_file";
                    $values[] = ":insurance_file";
                    $params[':insurance_file'] = $newInsuranceFilePath;
                }

                if ($hasPassportFile) {
                    $columns[] = "passport_file";
                    $values[] = ":passport_file";
                    $params[':passport_file'] = $newPassportFilePath;
                }

                if ($hasContractFile) {
                    $columns[] = "contract_file";
                    $values[] = ":contract_file";
                    $params[':contract_file'] = $newContractFilePath;
                }

                if ($hasDrivingFile) {
                    $columns[] = "driving_license_file";
                    $values[] = ":driving_file";
                    $params[':driving_file'] = $newDrivingFilePath;
                }

                if ($hasCreatedAt) {
                    $columns[] = "created_at";
                    $values[] = "NOW()";
                }

                if ($hasUpdatedAt) {
                    $columns[] = "updated_at";
                    $values[] = "NOW()";
                }

                $insertSql = "
                    INSERT INTO employee_docs (" . implode(", ", $columns) . ")
                    VALUES (" . implode(", ", $values) . ")
                ";
                $insertStmt = $pdo->prepare($insertSql);
                $insertStmt->execute($params);
                $docsId = (int)$pdo->lastInsertId();
            }

            sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'visa', 'الإقامة', $visaExpiry);
            sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'eid', 'الهوية الإماراتية', $eidExpiry);
            sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'insurance', 'التأمين الصحي', $insuranceExpiry);
            sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'passport', 'جواز السفر', $passportExpiry);

            if ($hasContractExpiry) {
                sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'contract', 'عقد العمل', $contractExpiry);
            }

            if ($hasDrivingExpiry) {
                sync_single_doc_alert_now($pdo, $personId, $docsId, (int)($person['branch_id'] ?? 0), 'driving_license', 'رخصة القيادة', $drivingExpiry);
            }

            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            foreach ($uploadedPaths as $uploadedPath) {
                safe_unlink(__DIR__ . '/' . ltrim((string)$uploadedPath, '/'));
            }

            throw $e;
        }

        if ($hasVisaFile && $newVisaFilePath !== null && !empty($oldData['visa_file']) && $oldData['visa_file'] !== $newVisaFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['visa_file'], '/'));
        }
        if ($hasEidFile && $newEidFilePath !== null && !empty($oldData['emirates_id_file']) && $oldData['emirates_id_file'] !== $newEidFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['emirates_id_file'], '/'));
        }
        if ($hasInsuranceFile && $newInsuranceFilePath !== null && !empty($oldData['insurance_file']) && $oldData['insurance_file'] !== $newInsuranceFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['insurance_file'], '/'));
        }
        if ($hasPassportFile && $newPassportFilePath !== null && !empty($oldData['passport_file']) && $oldData['passport_file'] !== $newPassportFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['passport_file'], '/'));
        }
        if ($hasContractFile && $newContractFilePath !== null && !empty($oldData['contract_file']) && $oldData['contract_file'] !== $newContractFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['contract_file'], '/'));
        }
        if ($hasDrivingFile && $newDrivingFilePath !== null && !empty($oldData['driving_license_file']) && $oldData['driving_license_file'] !== $newDrivingFilePath) {
            safe_unlink(__DIR__ . '/' . ltrim((string)$oldData['driving_license_file'], '/'));
        }

        header('Location: hr_docs_edit.php?id=' . $personId . '&saved=1');
        exit;
    }
}

if (isset($_GET['saved']) && $_GET['saved'] === '1') {
    $success = 'تم حفظ البيانات بنجاح.';
}

$reloadStmt = $pdo->prepare($sql);
$reloadStmt->execute([':id' => $personId]);
$person = $reloadStmt->fetch();

if (!$person) {
    http_response_code(404);
    exit('الشخص غير موجود');
}

$requireVisa     = (int)($person['require_visa'] ?? 1) === 1;
$requireContract = (int)($person['require_contract'] ?? 1) === 1;
$requireDriving  = (int)($person['require_driving_license'] ?? 0) === 1;

[$visaText, $visaClass, $visaDays]             = doc_status_meta($person['visa_expiry'] ?? null, $requireVisa);
[$eidText, $eidClass, $eidDays]                = doc_status_meta($person['emirates_id_expiry'] ?? null, true);
[$insText, $insClass, $insDays]                = doc_status_meta($person['insurance_expiry'] ?? null, true);
[$passText, $passClass, $passDays]             = doc_status_meta($person['passport_expiry'] ?? null, true);
[$contractText, $contractClass, $contractDays] = doc_status_meta($person['contract_expiry'] ?? null, $requireContract);
[$drivingText, $drivingClass, $drivingDays]    = doc_status_meta($person['driving_license_expiry'] ?? null, $requireDriving);

if (function_exists('layout_start')) {
    layout_start();
} elseif (function_exists('render_layout_start')) {
    render_layout_start();
} elseif (function_exists('layout_header')) {
    layout_header();
}
?>
<style>
.docs-page-fix .layout-topbar,
.docs-page-fix .layout-toolbar,
.docs-page-fix .layout-header-actions {
    flex-wrap: wrap;
    gap: 10px;
}

.docs-page-fix .layout-branch-form {
    margin: 0;
}

.docs-page-fix .layout-branch-select {
    min-width: 140px;
    height: 42px;
    border-radius: 12px;
}

.docs-page-fix .layout-topbar a,
.docs-page-fix .layout-topbar button,
.docs-page-fix .layout-topbar .layout-pill,
.docs-page-fix .layout-topbar .layout-chip {
    min-height: 42px;
    padding: 10px 14px;
    border-radius: 12px;
    white-space: nowrap;
}

.docs-page-fix .layout-userbox,
.docs-page-fix .layout-user-card,
.docs-page-fix .layout-profile-box {
    min-height: 64px;
    border-radius: 18px;
}

.docs-page-fix .hr-docs-header,
.docs-page-fix .docs-header-card {
    margin-top: 14px;
}

.docs-page-fix .hr-docs-grid,
.docs-page-fix .docs-grid {
    gap: 14px;
}

/* إصلاح محلي لصفحة المستندات فقط بدون التأثير على الكود الموحد */
.docs-page-fix{
  direction:rtl;
}

.docs-page-fix .layout-topbar,
.docs-page-fix .layout-toolbar,
.docs-page-fix .layout-header-actions,
.docs-page-fix .layout-top-actions,
.docs-page-fix .layout-actions{
  display:flex;
  align-items:center;
  flex-wrap:wrap;
  gap:10px;
}

.docs-page-fix .layout-branch-form{
  margin:0;
  flex:0 0 auto;
}

.docs-page-fix .layout-branch-select{
  min-width:140px;
  height:42px;
  border-radius:12px;
}

.docs-page-fix .layout-topbar a,
.docs-page-fix .layout-topbar button,
.docs-page-fix .layout-topbar .layout-pill,
.docs-page-fix .layout-topbar .layout-chip,
.docs-page-fix .layout-toolbar a,
.docs-page-fix .layout-toolbar button,
.docs-page-fix .layout-header-actions a,
.docs-page-fix .layout-header-actions button{
  min-height:42px;
  padding:10px 14px;
  border-radius:12px;
  white-space:nowrap;
  flex:0 0 auto;
}

.docs-page-fix .layout-userbox,
.docs-page-fix .layout-user-card,
.docs-page-fix .layout-profile-box,
.docs-page-fix .layout-account-card{
  min-height:64px;
  border-radius:18px;
}

.docs-page-fix .hr-docs-page{
  direction:rtl;
  padding:20px;
}

.docs-page-fix .hr-docs-shell{
  display:flex;
  flex-direction:column;
  gap:16px;
}

.docs-page-fix .topbar{
  display:flex;
  justify-content:space-between;
  align-items:flex-start;
  gap:16px;
  background:linear-gradient(135deg,#00424f,#006a7a);
  color:#fff;
  border-radius:20px;
  padding:20px 22px;
  box-shadow:0 16px 34px rgba(0,0,0,.12);
  margin-top:14px;
}

.docs-page-fix .topbar h1{
  margin:0 0 6px;
  font-size:25px;
}

.docs-page-fix .topbar p{
  margin:0;
  font-size:14px;
  opacity:.92;
}

.docs-page-fix .employee-card,
.docs-page-fix .form-box{
  background:#fff;
  border:1px solid #e6eef0;
  border-radius:20px;
  padding:18px;
  box-shadow:0 10px 24px rgba(15,34,38,.05);
}

.docs-page-fix .employee-name{
  font-size:22px;
  color:#102328;
  margin-bottom:4px;
}

.docs-page-fix .employee-id{
  font-size:13px;
  color:#73858b;
}

.docs-page-fix .msg{
  border-radius:16px;
  padding:14px 16px;
  font-size:14px;
}

.docs-page-fix .msg.success{
  background:#e8f8ef;
  color:#0d7c44;
  border:1px solid #cfeedd;
}

.docs-page-fix .msg.error{
  background:#fff1f1;
  color:#b42323;
  border:1px solid #ffd3d3;
}

.docs-page-fix .status-grid{
  display:grid;
  grid-template-columns:repeat(6,minmax(0,1fr));
  gap:12px;
}

.docs-page-fix .status-card{
  background:#fff;
  border:1px solid #e6eef0;
  border-radius:18px;
  padding:16px;
  box-shadow:0 10px 24px rgba(15,34,38,.05);
}

.docs-page-fix .status-title{
  font-size:13px;
  color:#65777d;
  margin-bottom:10px;
}

.docs-page-fix .section-head{
  margin-bottom:14px;
}

.docs-page-fix .section-head h2{
  margin:0 0 4px;
  font-size:18px;
  color:#102328;
}

.docs-page-fix .section-head p{
  margin:0;
  font-size:13px;
  color:#74878d;
}

.docs-page-fix .docs-form{
  display:flex;
  flex-direction:column;
  gap:16px;
}

.docs-page-fix .doc-block{
  border:1px solid #e7eef1;
  border-radius:18px;
  padding:16px;
  background:linear-gradient(180deg,#ffffff 0%,#fbfdfe 100%);
}

.docs-page-fix .doc-block-head{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  margin-bottom:14px;
}

.docs-page-fix .doc-block-head h3{
  margin:0;
  font-size:17px;
  color:#103137;
}

.docs-page-fix .doc-actions-inline{
  display:flex;
  gap:8px;
  flex-wrap:wrap;
}

.docs-page-fix .doc-grid{
  display:grid;
  grid-template-columns:1.2fr 1fr;
  gap:14px;
}

.docs-page-fix .field{
  display:flex;
  flex-direction:column;
  gap:8px;
}

.docs-page-fix .field label{
  font-size:13px;
  color:#52656b;
}

.docs-page-fix .date-wrap,
.docs-page-fix .file-input-wrap{
  position:relative;
  background:#fbfdfe;
  border:1px solid #dbe5e8;
  border-radius:16px;
  min-height:52px;
  display:flex;
  align-items:center;
  padding:0 14px;
  transition:.18s ease;
  box-shadow:inset 0 1px 0 rgba(255,255,255,.75);
}

.docs-page-fix .date-wrap:focus-within,
.docs-page-fix .file-input-wrap:focus-within{
  border-color:#006a7a;
  box-shadow:0 0 0 4px rgba(0,106,122,.08);
  background:#fff;
}

.docs-page-fix .date-wrap input[type="date"],
.docs-page-fix .file-input-wrap input[type="file"]{
  width:100%;
  border:0;
  outline:none;
  background:transparent;
  font-family:inherit;
  font-size:14px;
  color:#102328;
}

.docs-page-fix .date-wrap input[type="date"]{
  min-height:50px;
}

.docs-page-fix .file-input-wrap input[type="file"]{
  padding:10px 0;
}

.docs-page-fix .action-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:42px;
  padding:0 16px;
  border-radius:14px;
  text-decoration:none;
  border:none;
  cursor:pointer;
  font-size:14px;
  font-family:inherit;
  transition:.18s ease;
}

.docs-page-fix .action-btn.primary{
  background:#d4af37;
  color:#13262b;
  font-weight:700;
}

.docs-page-fix .action-btn.light{
  background:#fff;
  color:#00424f;
  border:1px solid rgba(0,66,79,.14);
}

.docs-page-fix .file-btn{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-height:34px;
  padding:0 12px;
  border-radius:10px;
  text-decoration:none;
  font-size:13px;
  border:1px solid #d5e2e7;
}

.docs-page-fix .file-btn.open{
  background:#f4f8f9;
  color:#00424f;
}

.docs-page-fix .file-btn.download{
  background:#006a7a;
  color:#fff;
  border-color:#006a7a;
}

.docs-page-fix .file-empty{
  font-size:12px;
  color:#7b8e94;
  background:#f3f6f8;
  border:1px solid #e2eaee;
  padding:8px 10px;
  border-radius:10px;
}

.docs-page-fix .status-pill{
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:78px;
  padding:7px 12px;
  border-radius:999px;
  font-size:12px;
  line-height:1;
}

.docs-page-fix .status-pill.valid{
  background:#e7f7ef;
  color:#0d7c44;
}

.docs-page-fix .status-pill.warning{
  background:#fff4d6;
  color:#9b6500;
}

.docs-page-fix .status-pill.expired{
  background:#ffe3e3;
  color:#b42323;
}

.docs-page-fix .status-pill.missing{
  background:#edf2f5;
  color:#60727a;
}

.docs-page-fix .status-pill.not-required{
  background:#eef6ff;
  color:#4b6b88;
}

.docs-page-fix .form-actions{
  display:flex;
  gap:10px;
  flex-wrap:wrap;
  margin-top:4px;
}

@media (max-width:1200px){
  .docs-page-fix .status-grid{
    grid-template-columns:repeat(3,minmax(0,1fr));
  }
}

@media (max-width:860px){
  .docs-page-fix .hr-docs-page{
    padding:14px;
  }

  .docs-page-fix .topbar{
    flex-direction:column;
  }

  .docs-page-fix .status-grid{
    grid-template-columns:1fr 1fr;
  }

  .docs-page-fix .doc-grid{
    grid-template-columns:1fr;
  }
}

@media (max-width:560px){
  .docs-page-fix .status-grid{
    grid-template-columns:1fr;
  }

  .docs-page-fix .form-actions,
  .docs-page-fix .doc-block-head{
    flex-direction:column;
    align-items:stretch;
  }
}
</style>

<div class="docs-page-fix">
  <div class="hr-docs-page">
    <div class="hr-docs-shell">

      <div class="topbar">
        <div>
          <h1>تعديل مستندات الشخص</h1>
          <p>تحديث التواريخ والملفات حسب نوع الشخص والمستندات المطلوبة له</p>
        </div>
        <div class="topbar-actions">
          <a class="action-btn light" href="hr_docs_dashboard.php">العودة إلى اللوحة</a>
        </div>
      </div>

      <div class="employee-card">
        <div class="employee-name"><?= h($person['name'] ?? 'بدون اسم') ?></div>
        <div class="employee-id">
          الرقم: <?= (int)($person['id'] ?? 0) ?> |
          النوع: <?= h(person_type_ar((string)($person['person_type'] ?? 'employee'))) ?> |
          آخر تحديث: <?= h(format_datetime_ar($person['updated_at'] ?? null)) ?>
        </div>
      </div>

      <?php if ($success !== ''): ?>
        <div class="msg success"><?= h($success) ?></div>
      <?php endif; ?>

      <?php if ($errors): ?>
        <div class="msg error">
          <?php foreach ($errors as $error): ?>
            <div><?= h($error) ?></div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>

      <div class="status-grid">
        <div class="status-card"><div class="status-title">الإقامة</div><span class="status-pill <?= h($visaClass) ?>" title="<?= h(status_hint($visaDays, $visaText)) ?>"><?= h($visaText) ?></span></div>
        <div class="status-card"><div class="status-title">الهوية</div><span class="status-pill <?= h($eidClass) ?>" title="<?= h(status_hint($eidDays, $eidText)) ?>"><?= h($eidText) ?></span></div>
        <div class="status-card"><div class="status-title">التأمين</div><span class="status-pill <?= h($insClass) ?>" title="<?= h(status_hint($insDays, $insText)) ?>"><?= h($insText) ?></span></div>
        <div class="status-card"><div class="status-title">الجواز</div><span class="status-pill <?= h($passClass) ?>" title="<?= h(status_hint($passDays, $passText)) ?>"><?= h($passText) ?></span></div>
        <div class="status-card"><div class="status-title">عقد العمل</div><span class="status-pill <?= h($contractClass) ?>" title="<?= h(status_hint($contractDays, $contractText)) ?>"><?= h($contractText) ?></span></div>
        <div class="status-card"><div class="status-title">رخصة القيادة</div><span class="status-pill <?= h($drivingClass) ?>" title="<?= h(status_hint($drivingDays, $drivingText)) ?>"><?= h($drivingText) ?></span></div>
      </div>

      <div class="form-box">
        <div class="section-head">
          <h2>بيانات المستندات</h2>
          <p>المستندات غير المطلوبة تظهر بحالة غير مطلوب ويمكن تركها فارغة</p>
        </div>

        <form method="post" enctype="multipart/form-data" class="docs-form">
          <input type="hidden" name="employee_id" value="<?= (int)$personId ?>">

          <div class="doc-block">
            <div class="doc-block-head">
              <h3>الإقامة</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['visa_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['visa_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['visa_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء الإقامة</label>
                <div class="date-wrap">
                  <input type="date" name="visa_expiry" value="<?= h((string)($person['visa_expiry'] ?? '')) ?>" <?= $requireVisa ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php if ($hasVisaFile): ?>
              <div class="field">
                <label>رفع ملف الإقامة</label>
                <div class="file-input-wrap">
                  <input type="file" name="visa_file" accept=".pdf,.jpg,.jpeg,.png,.webp" <?= $requireVisa ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="doc-block">
            <div class="doc-block-head">
              <h3>الهوية</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['emirates_id_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['emirates_id_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['emirates_id_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء الهوية</label>
                <div class="date-wrap">
                  <input type="date" name="emirates_id_expiry" value="<?= h((string)($person['emirates_id_expiry'] ?? '')) ?>">
                </div>
              </div>
              <?php if ($hasEidFile): ?>
              <div class="field">
                <label>رفع ملف الهوية</label>
                <div class="file-input-wrap">
                  <input type="file" name="emirates_id_file" accept=".pdf,.jpg,.jpeg,.png,.webp">
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="doc-block">
            <div class="doc-block-head">
              <h3>التأمين</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['insurance_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['insurance_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['insurance_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء التأمين</label>
                <div class="date-wrap">
                  <input type="date" name="insurance_expiry" value="<?= h((string)($person['insurance_expiry'] ?? '')) ?>">
                </div>
              </div>
              <?php if ($hasInsuranceFile): ?>
              <div class="field">
                <label>رفع ملف التأمين</label>
                <div class="file-input-wrap">
                  <input type="file" name="insurance_file" accept=".pdf,.jpg,.jpeg,.png,.webp">
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <div class="doc-block">
            <div class="doc-block-head">
              <h3>الجواز</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['passport_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['passport_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['passport_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء الجواز</label>
                <div class="date-wrap">
                  <input type="date" name="passport_expiry" value="<?= h((string)($person['passport_expiry'] ?? '')) ?>">
                </div>
              </div>
              <?php if ($hasPassportFile): ?>
              <div class="field">
                <label>رفع ملف الجواز</label>
                <div class="file-input-wrap">
                  <input type="file" name="passport_file" accept=".pdf,.jpg,.jpeg,.png,.webp">
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>

          <?php if ($hasContractExpiry): ?>
          <div class="doc-block">
            <div class="doc-block-head">
              <h3>عقد العمل</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['contract_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['contract_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['contract_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء عقد العمل</label>
                <div class="date-wrap">
                  <input type="date" name="contract_expiry" value="<?= h((string)($person['contract_expiry'] ?? '')) ?>" <?= $requireContract ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php if ($hasContractFile): ?>
              <div class="field">
                <label>رفع ملف عقد العمل</label>
                <div class="file-input-wrap">
                  <input type="file" name="contract_file" accept=".pdf,.jpg,.jpeg,.png,.webp" <?= $requireContract ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>

          <?php if (true): ?>
          <div class="doc-block">
            <div class="doc-block-head">
              <h3>رخصة القيادة</h3>
              <div class="doc-actions-inline">
                <?php if (!empty($person['driving_license_file'])): ?>
                  <a class="file-btn open" href="<?= h($person['driving_license_file']) ?>" target="_blank" rel="noopener">فتح</a>
                  <a class="file-btn download" href="<?= h($person['driving_license_file']) ?>" download>تحميل</a>
                <?php else: ?>
                  <span class="file-empty">لا يوجد ملف</span>
                <?php endif; ?>
              </div>
            </div>
            <div class="doc-grid">
              <div class="field">
                <label>تاريخ انتهاء رخصة القيادة</label>
                <div class="date-wrap">
                  <input type="date" name="driving_license_expiry" value="<?= h((string)($person['driving_license_expiry'] ?? '')) ?>" <?= $requireDriving ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php if ($hasDrivingFile): ?>
              <div class="field">
                <label>رفع ملف رخصة القيادة</label>
                <div class="file-input-wrap">
                  <input type="file" name="driving_license_file" accept=".pdf,.jpg,.jpeg,.png,.webp" <?= $requireDriving ? '' : 'disabled' ?>>
                </div>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>

          <div class="form-actions">
            <button type="submit" class="action-btn primary">حفظ التعديلات</button>
            <a href="hr_docs_dashboard.php" class="action-btn light">إلغاء</a>
          </div>
        </form>
      </div>

    </div>
  </div>
</div>