<?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', 'SUPER_ADMIN', 'SUPERADMIN'], true);
}

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

function can_manage_company_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 table_exists_safe(PDO $pdo, string $table): bool
{
    static $cache = [];

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

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

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

function column_exists_safe(PDO $pdo, string $table, string $column): bool
{
    static $cache = [];

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

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

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

function delete_single_company_doc_alert(PDO $pdo, int $companyDocsId, string $docKey): void
{
    if (table_exists_safe($pdo, 'company_document_alerts')) {
        $stmt = $pdo->prepare("
            DELETE FROM company_document_alerts
            WHERE company_docs_id = :company_docs_id
              AND document_key = :document_key
        ");
        $stmt->execute([
            ':company_docs_id' => $companyDocsId,
            ':document_key'    => $docKey,
        ]);
    }

    if (table_exists_safe($pdo, 'hr_document_alerts')) {
        $stmt = $pdo->prepare("
            DELETE FROM hr_document_alerts
            WHERE employee_id = 0
              AND docs_id = :docs_id
              AND document_key = :document_key
        ");
        $stmt->execute([
            ':docs_id'       => $companyDocsId,
            ':document_key'  => $docKey,
        ]);
    }
}

function reset_single_company_doc_notified(PDO $pdo, int $companyDocsId, string $column): void
{
    $allowed = [
        'ad_license_notified',
        'dubai_license_notified',
        'judicial_registration_notified',
        'dubai_registration_notified',
        'federal_registration_notified',
    ];

    if (!in_array($column, $allowed, true)) {
        return;
    }

    if (!column_exists_safe($pdo, 'company_docs', $column)) {
        return;
    }

    $sql = "UPDATE company_docs SET {$column} = NULL WHERE id = :id";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':id' => $companyDocsId]);
}

function sync_single_company_doc_alert(
    PDO $pdo,
    int $companyDocsId,
    int $branchId,
    string $docKey,
    string $docLabel,
    ?string $expiryDate
): void {
    delete_single_company_doc_alert($pdo, $companyDocsId, $docKey);

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

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

    if ($daysLeft > 30) {
        return;
    }

    if (!table_exists_safe($pdo, 'company_document_alerts')) {
        return;
    }

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

    $hasBranchName = column_exists_safe($pdo, 'company_document_alerts', 'branch_name');
    $hasAlertType  = column_exists_safe($pdo, 'company_document_alerts', 'alert_type');
    $hasIsRead     = column_exists_safe($pdo, 'company_document_alerts', 'is_read');
    $hasIsResolved = column_exists_safe($pdo, 'company_document_alerts', 'is_resolved');
    $hasAlertDate  = column_exists_safe($pdo, 'company_document_alerts', 'alert_date');
    $hasCreatedAt  = column_exists_safe($pdo, 'company_document_alerts', 'created_at');

    $columns = [
        'company_docs_id',
        'branch_id',
        'document_key',
        'document_label',
        'expiry_date',
        'days_left',
        'status',
    ];

    $values = [
        ':company_docs_id',
        ':branch_id',
        ':document_key',
        ':document_label',
        ':expiry_date',
        ':days_left',
        ':status',
    ];

    $params = [
        ':company_docs_id' => $companyDocsId,
        ':branch_id'       => $branchId,
        ':document_key'    => $docKey,
        ':document_label'  => $docLabel,
        ':expiry_date'     => $expiryDate,
        ':days_left'       => $daysLeft,
        ':status'          => $status,
    ];

    if ($hasBranchName) {
        $columns[] = 'branch_name';
        $values[]  = ':branch_name';
        $params[':branch_name'] = match ($branchId) {
            1 => 'أبوظبي',
            2 => 'دبي',
            3 => 'العين',
            default => 'الفرع العام',
        };
    }

    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';
    }

    if ($hasAlertDate) {
        $columns[] = 'alert_date';
        $values[]  = ':alert_date';
        $params[':alert_date'] = date('Y-m-d');
    }

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

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

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

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

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

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

$pdo = pdo_conn();

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

$branchId = (int)($_POST['branch_id'] ?? current_branch_id_safe());
if ($branchId <= 0) {
    http_response_code(422);
    exit('رقم الفرع غير صالح');
}

$adLicenseExpiry            = normalize_date_or_null($_POST['ad_license_expiry'] ?? null);
$dubaiLicenseExpiry         = normalize_date_or_null($_POST['dubai_license_expiry'] ?? null);
$judicialRegistrationExpiry = normalize_date_or_null($_POST['judicial_registration_expiry'] ?? null);
$dubaiRegistrationExpiry    = normalize_date_or_null($_POST['dubai_registration_expiry'] ?? null);
$federalRegistrationExpiry  = normalize_date_or_null($_POST['federal_registration_expiry'] ?? null);

try {
    $pdo->beginTransaction();

    $checkStmt = $pdo->prepare("
        SELECT *
        FROM company_docs
        WHERE branch_id = :branch_id
        LIMIT 1
    ");
    $checkStmt->execute([':branch_id' => $branchId]);

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

    if ($companyDocsId > 0) {
        $parts = [];
        $params = [
            ':id' => $companyDocsId,
        ];

        $oldAd = $existing['ad_license_expiry'] ?? null;
        $oldDu = $existing['dubai_license_expiry'] ?? null;
        $oldJd = $existing['judicial_registration_expiry'] ?? null;
        $oldDr = $existing['dubai_registration_expiry'] ?? null;
        $oldFr = $existing['federal_registration_expiry'] ?? null;

        if (column_exists_safe($pdo, 'company_docs', 'ad_license_expiry')) {
            $parts[] = "ad_license_expiry = :ad_license_expiry";
            $params[':ad_license_expiry'] = $adLicenseExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'dubai_license_expiry')) {
            $parts[] = "dubai_license_expiry = :dubai_license_expiry";
            $params[':dubai_license_expiry'] = $dubaiLicenseExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'judicial_registration_expiry')) {
            $parts[] = "judicial_registration_expiry = :judicial_registration_expiry";
            $params[':judicial_registration_expiry'] = $judicialRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'dubai_registration_expiry')) {
            $parts[] = "dubai_registration_expiry = :dubai_registration_expiry";
            $params[':dubai_registration_expiry'] = $dubaiRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'federal_registration_expiry')) {
            $parts[] = "federal_registration_expiry = :federal_registration_expiry";
            $params[':federal_registration_expiry'] = $federalRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'updated_at')) {
            $parts[] = "updated_at = NOW()";
        }

        if ($parts) {
            $updateStmt = $pdo->prepare("
                UPDATE company_docs
                SET " . implode(', ', $parts) . "
                WHERE id = :id
            ");
            $updateStmt->execute($params);
        }

        if ((string)$oldAd !== (string)$adLicenseExpiry) {
            delete_single_company_doc_alert($pdo, $companyDocsId, 'ad_license');
            reset_single_company_doc_notified($pdo, $companyDocsId, 'ad_license_notified');
        }

        if ((string)$oldDu !== (string)$dubaiLicenseExpiry) {
            delete_single_company_doc_alert($pdo, $companyDocsId, 'dubai_license');
            reset_single_company_doc_notified($pdo, $companyDocsId, 'dubai_license_notified');
        }

        if ((string)$oldJd !== (string)$judicialRegistrationExpiry) {
            delete_single_company_doc_alert($pdo, $companyDocsId, 'judicial_registration');
            reset_single_company_doc_notified($pdo, $companyDocsId, 'judicial_registration_notified');
        }

        if ((string)$oldDr !== (string)$dubaiRegistrationExpiry) {
            delete_single_company_doc_alert($pdo, $companyDocsId, 'dubai_registration');
            reset_single_company_doc_notified($pdo, $companyDocsId, 'dubai_registration_notified');
        }

        if ((string)$oldFr !== (string)$federalRegistrationExpiry) {
            delete_single_company_doc_alert($pdo, $companyDocsId, 'federal_registration');
            reset_single_company_doc_notified($pdo, $companyDocsId, 'federal_registration_notified');
        }
    } else {
        $columns = ['branch_id'];
        $values  = [':branch_id'];
        $params  = [':branch_id' => $branchId];

        if (column_exists_safe($pdo, 'company_docs', 'ad_license_expiry')) {
            $columns[] = 'ad_license_expiry';
            $values[]  = ':ad_license_expiry';
            $params[':ad_license_expiry'] = $adLicenseExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'dubai_license_expiry')) {
            $columns[] = 'dubai_license_expiry';
            $values[]  = ':dubai_license_expiry';
            $params[':dubai_license_expiry'] = $dubaiLicenseExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'judicial_registration_expiry')) {
            $columns[] = 'judicial_registration_expiry';
            $values[]  = ':judicial_registration_expiry';
            $params[':judicial_registration_expiry'] = $judicialRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'dubai_registration_expiry')) {
            $columns[] = 'dubai_registration_expiry';
            $values[]  = ':dubai_registration_expiry';
            $params[':dubai_registration_expiry'] = $dubaiRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'federal_registration_expiry')) {
            $columns[] = 'federal_registration_expiry';
            $values[]  = ':federal_registration_expiry';
            $params[':federal_registration_expiry'] = $federalRegistrationExpiry;
        }

        if (column_exists_safe($pdo, 'company_docs', 'created_at')) {
            $columns[] = 'created_at';
            $values[]  = 'NOW()';
        }

        if (column_exists_safe($pdo, 'company_docs', 'updated_at')) {
            $columns[] = 'updated_at';
            $values[]  = 'NOW()';
        }

        $insertStmt = $pdo->prepare("
            INSERT INTO company_docs
            (" . implode(', ', $columns) . ")
            VALUES
            (" . implode(', ', $values) . ")
        ");
        $insertStmt->execute($params);

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

    sync_single_company_doc_alert($pdo, $companyDocsId, $branchId, 'ad_license', 'رخصة أبوظبي', $adLicenseExpiry);
    sync_single_company_doc_alert($pdo, $companyDocsId, $branchId, 'dubai_license', 'رخصة دبي', $dubaiLicenseExpiry);
    sync_single_company_doc_alert($pdo, $companyDocsId, $branchId, 'judicial_registration', 'قيد دائرة القضاء', $judicialRegistrationExpiry);
    sync_single_company_doc_alert($pdo, $companyDocsId, $branchId, 'dubai_registration', 'قيد دبي', $dubaiRegistrationExpiry);
    sync_single_company_doc_alert($pdo, $companyDocsId, $branchId, 'federal_registration', 'القيد الاتحادي', $federalRegistrationExpiry);

    $pdo->commit();

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

    $separator = str_contains($back, '?') ? '&' : '?';
    header('Location: ' . $back . $separator . 'saved=1&branch_id=' . $branchId);
    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;
}