<?php
declare(strict_types=1);

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

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

header('Content-Type: text/html; charset=UTF-8');

if (!function_exists('db')) {
    http_response_code(500);
    exit('db() not found');
}

function pdo_conn(): PDO
{
    $pdo = db();
    if (!$pdo instanceof PDO) {
        http_response_code(500);
        exit('DB connection failed');
    }

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

    return $pdo;
}

function h($v): string
{
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

function current_role_upper(): string
{
    return strtoupper((string)($_SESSION['role'] ?? 'STAFF'));
}

function is_admin_like(): bool
{
    return in_array(current_role_upper(), ['OWNER', 'ADMIN'], true);
}

function current_branch_id_safe(): int
{
    return (int)($_SESSION['branch_id'] ?? 1);
}

function can_manage_hr_docs(): bool
{
    return is_admin_like() || ((int)($_SESSION['can_hr'] ?? 0) === 1);
}

function normalize_date_or_null($value): ?string
{
    $value = trim((string)$value);
    if ($value === '' || $value === '0000-00-00') {
        return null;
    }

    $dt = DateTime::createFromFormat('Y-m-d', $value);
    if (!$dt || $dt->format('Y-m-d') !== $value) {
        return null;
    }

    return $value;
}

function days_left_from_today(?string $expiryDate): ?int
{
    if ($expiryDate === null) {
        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');
}

function delete_single_doc_alert(PDO $pdo, int $employeeId, int $docsId, string $docKey): void
{
    $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,
    ]);
}

function sync_single_doc_alert(
    PDO $pdo,
    int $employeeId,
    int $docsId,
    int $branchId,
    string $docKey,
    string $docLabel,
    ?string $expiryDate
): void {
    delete_single_doc_alert($pdo, $employeeId, $docsId, $docKey);

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

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

    if ($daysLeft > 30) {
        return;
    }

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

    $stmt = $pdo->prepare("
        INSERT INTO hr_document_alerts
        (
            employee_id,
            docs_id,
            branch_id,
            document_key,
            document_label,
            expiry_date,
            days_left,
            status,
            alert_type,
            is_read,
            is_resolved,
            created_at
        )
        VALUES
        (
            :employee_id,
            :docs_id,
            :branch_id,
            :document_key,
            :document_label,
            :expiry_date,
            :days_left,
            :status,
            'document',
            0,
            0,
            NOW()
        )
    ");

    $stmt->execute([
        ':employee_id'    => $employeeId,
        ':docs_id'        => $docsId,
        ':branch_id'      => $branchId,
        ':document_key'   => $docKey,
        ':document_label' => $docLabel,
        ':expiry_date'    => $expiryDate,
        ':days_left'      => $daysLeft,
        ':status'         => $status,
    ]);
}

function fetch_employee_branch_id(PDO $pdo, int $employeeId): int
{
    $stmt = $pdo->prepare("SELECT branch_id FROM employees WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $employeeId]);
    $row = $stmt->fetch();

    if (!$row) {
        return current_branch_id_safe();
    }

    return (int)($row['branch_id'] ?? current_branch_id_safe());
}

/* =========================
   بدء التنفيذ
========================= */
if (empty($_SESSION['user_id'])) {
    header('Location: ../index.html?e=1');
    exit;
}

if (!can_manage_hr_docs()) {
    http_response_code(403);
    exit('غير مصرح');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

$pdo = pdo_conn();

$employeeId = (int)($_POST['employee_id'] ?? 0);
if ($employeeId <= 0) {
    http_response_code(422);
    exit('رقم الموظف غير صالح');
}

$visaExpiry      = normalize_date_or_null($_POST['visa_expiry'] ?? null);
$eidExpiry       = normalize_date_or_null($_POST['emirates_id_expiry'] ?? null);
$insuranceExpiry = normalize_date_or_null($_POST['insurance_expiry'] ?? null);
$passportExpiry  = normalize_date_or_null($_POST['passport_expiry'] ?? null);

$branchId = fetch_employee_branch_id($pdo, $employeeId);

try {
    $pdo->beginTransaction();

    $checkStmt = $pdo->prepare("
        SELECT id
        FROM employee_docs
        WHERE employee_id = :employee_id
        LIMIT 1
    ");
    $checkStmt->execute([':employee_id' => $employeeId]);

    $existing = $checkStmt->fetch();
    $docsId   = (int)($existing['id'] ?? 0);

    if ($docsId > 0) {
        $updateStmt = $pdo->prepare("
            UPDATE employee_docs
            SET
                visa_expiry = :visa_expiry,
                emirates_id_expiry = :eid_expiry,
                insurance_expiry = :insurance_expiry,
                passport_expiry = :passport_expiry
            WHERE id = :id
        ");
        $updateStmt->execute([
            ':visa_expiry'      => $visaExpiry,
            ':eid_expiry'       => $eidExpiry,
            ':insurance_expiry' => $insuranceExpiry,
            ':passport_expiry'  => $passportExpiry,
            ':id'               => $docsId,
        ]);
    } else {
        $insertStmt = $pdo->prepare("
            INSERT INTO employee_docs
            (
                employee_id,
                visa_expiry,
                emirates_id_expiry,
                insurance_expiry,
                passport_expiry
            )
            VALUES
            (
                :employee_id,
                :visa_expiry,
                :eid_expiry,
                :insurance_expiry,
                :passport_expiry
            )
        ");
        $insertStmt->execute([
            ':employee_id'      => $employeeId,
            ':visa_expiry'      => $visaExpiry,
            ':eid_expiry'       => $eidExpiry,
            ':insurance_expiry' => $insuranceExpiry,
            ':passport_expiry'  => $passportExpiry,
        ]);

        $docsId = (int)$pdo->lastInsertId();
    }

    sync_single_doc_alert($pdo, $employeeId, $docsId, $branchId, 'visa', 'الإقامة', $visaExpiry);
    sync_single_doc_alert($pdo, $employeeId, $docsId, $branchId, 'eid', 'الهوية الإماراتية', $eidExpiry);
    sync_single_doc_alert($pdo, $employeeId, $docsId, $branchId, 'insurance', 'التأمين الصحي', $insuranceExpiry);
    sync_single_doc_alert($pdo, $employeeId, $docsId, $branchId, 'passport', 'جواز السفر', $passportExpiry);

    $pdo->commit();

    $back = trim((string)($_POST['redirect'] ?? 'hr_docs_dashboard.php'));
    if ($back === '') {
        $back = 'hr_docs_dashboard.php';
    }

    header('Location: ' . $back . '?saved=1&employee_id=' . $employeeId);
    exit;
} catch (Throwable $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    http_response_code(500);
    echo '<div style="font-family:Arial;padding:20px;direction:rtl">';
    echo '<h3>تعذر حفظ المستندات</h3>';
    echo '<pre style="white-space:pre-wrap;background:#f6f6f6;padding:12px;border-radius:8px;">' . h($e->getMessage()) . '</pre>';
    echo '</div>';
    exit;
}