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

$page_title   = 'تعديل مستندات الشركة';
$layout_title = 'تعديل مستندات الشركة';
$active_page  = 'company_docs_dashboard';
$active_menu  = 'hr';

require_once __DIR__ . '/../inc/layout.php';

$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): array
    {
        $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 ($days === null) {
            return $status;
        }

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

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

if (!function_exists('company_branch_name_ar')) {
    function company_branch_name_ar(int $branchId): string
    {
        return match ($branchId) {
            1       => 'أبوظبي',
            2       => 'دبي',
            3       => 'الشارقة',
            4       => 'العين',
            default => 'الفرع العام',
        };
    }
}

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

if (!function_exists('upload_company_doc_file')) {
    function upload_company_doc_file(array $file, string $prefix, int $branchId): 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/company_docs/';
        $branchDirName = 'BRANCH_' . $branchId;
        $branchDir = $baseDir . $branchDirName . '/' . $prefix . '/';

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

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

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

        return [
            'ok'    => true,
            'path'  => 'hr/uploads/company_docs/' . $branchDirName . '/' . $prefix . '/' . $filename,
            'error' => null,
        ];
    }
}

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 $value;
        }

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

if (!function_exists('delete_company_alerts_by_doc')) {
    function delete_company_alerts_by_doc(PDO $pdo, int $companyDocId, string $documentKey): void
    {
        if (table_exists($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' => $companyDocId,
                ':document_key'    => $documentKey,
            ]);
        }
    }
}

/* =========================
   التحقق من الجدول
========================= */
if (!table_exists($pdo, 'company_docs')) {
    http_response_code(500);
    exit('جدول company_docs غير موجود');
}

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

/* =========================
   الصلاحيات
========================= */
$userRole = strtolower(trim((string)($_SESSION['role'] ?? '')));
$isAllowedEditor = in_array($userRole, ['owner', 'super_admin', 'superadmin', 'admin'], true);

if (!$isAllowedEditor) {
    http_response_code(403);
    exit('غير مصرح لك بتعديل مستندات الشركة. التعديل متاح للأونر والإدمن فقط.');
}

/* =========================
   فحص الأعمدة
========================= */
$hasBranchId                   = table_has_column($pdo, 'company_docs', 'branch_id');
$hasAdLicenseExpiry            = table_has_column($pdo, 'company_docs', 'ad_license_expiry');
$hasDubaiLicenseExpiry         = table_has_column($pdo, 'company_docs', 'dubai_license_expiry');
$hasJudicialRegistrationExpiry = table_has_column($pdo, 'company_docs', 'judicial_registration_expiry');
$hasDubaiRegistrationExpiry    = table_has_column($pdo, 'company_docs', 'dubai_registration_expiry');
$hasFederalRegistrationExpiry  = table_has_column($pdo, 'company_docs', 'federal_registration_expiry');

$hasAdLicenseFile              = table_has_column($pdo, 'company_docs', 'ad_license_file');
$hasDubaiLicenseFile           = table_has_column($pdo, 'company_docs', 'dubai_license_file');
$hasJudicialRegistrationFile   = table_has_column($pdo, 'company_docs', 'judicial_registration_file');
$hasDubaiRegistrationFile      = table_has_column($pdo, 'company_docs', 'dubai_registration_file');
$hasFederalRegistrationFile    = table_has_column($pdo, 'company_docs', 'federal_registration_file');

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

/* =========================
   الاستعلام
========================= */
$selectBranchId   = $hasBranchId ? 'branch_id' : '0 AS branch_id';
$selectAdExpiry   = $hasAdLicenseExpiry ? 'ad_license_expiry' : 'NULL AS ad_license_expiry';
$selectDuExpiry   = $hasDubaiLicenseExpiry ? 'dubai_license_expiry' : 'NULL AS dubai_license_expiry';
$selectJdExpiry   = $hasJudicialRegistrationExpiry ? 'judicial_registration_expiry' : 'NULL AS judicial_registration_expiry';
$selectDrExpiry   = $hasDubaiRegistrationExpiry ? 'dubai_registration_expiry' : 'NULL AS dubai_registration_expiry';
$selectFrExpiry   = $hasFederalRegistrationExpiry ? 'federal_registration_expiry' : 'NULL AS federal_registration_expiry';

$selectAdFile     = $hasAdLicenseFile ? 'ad_license_file' : 'NULL AS ad_license_file';
$selectDuFile     = $hasDubaiLicenseFile ? 'dubai_license_file' : 'NULL AS dubai_license_file';
$selectJdFile     = $hasJudicialRegistrationFile ? 'judicial_registration_file' : 'NULL AS judicial_registration_file';
$selectDrFile     = $hasDubaiRegistrationFile ? 'dubai_registration_file' : 'NULL AS dubai_registration_file';
$selectFrFile     = $hasFederalRegistrationFile ? 'federal_registration_file' : 'NULL AS federal_registration_file';
$selectUpdatedAt  = $hasUpdatedAt ? 'updated_at' : 'NULL AS updated_at';
$selectCreatedAt  = $hasCreatedAt ? 'created_at' : 'NULL AS created_at';

$sql = "
    SELECT
        id,
        {$selectBranchId},
        {$selectAdExpiry},
        {$selectDuExpiry},
        {$selectJdExpiry},
        {$selectDrExpiry},
        {$selectFrExpiry},
        {$selectAdFile},
        {$selectDuFile},
        {$selectJdFile},
        {$selectDrFile},
        {$selectFrFile},
        {$selectUpdatedAt},
        {$selectCreatedAt}
    FROM company_docs
    WHERE id = :id
    LIMIT 1
";

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

if (!$doc) {
    http_response_code(404);
    exit('السجل غير موجود');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $adExpiry = normalize_date_input($_POST['ad_license_expiry'] ?? null);
    $duExpiry = normalize_date_input($_POST['dubai_license_expiry'] ?? null);
    $jdExpiry = normalize_date_input($_POST['judicial_registration_expiry'] ?? null);
    $drExpiry = normalize_date_input($_POST['dubai_registration_expiry'] ?? null);
    $frExpiry = normalize_date_input($_POST['federal_registration_expiry'] ?? null);

    $rawAd = trim((string)($_POST['ad_license_expiry'] ?? ''));
    $rawDu = trim((string)($_POST['dubai_license_expiry'] ?? ''));
    $rawJd = trim((string)($_POST['judicial_registration_expiry'] ?? ''));
    $rawDr = trim((string)($_POST['dubai_registration_expiry'] ?? ''));
    $rawFr = trim((string)($_POST['federal_registration_expiry'] ?? ''));

    if ($rawAd !== '' && $adExpiry === null) {
        $errors[] = 'تاريخ رخصة أبوظبي غير صحيح.';
    }
    if ($rawDu !== '' && $duExpiry === null) {
        $errors[] = 'تاريخ رخصة دبي غير صحيح.';
    }
    if ($rawJd !== '' && $jdExpiry === null) {
        $errors[] = 'تاريخ قيد دائرة القضاء غير صحيح.';
    }
    if ($rawDr !== '' && $drExpiry === null) {
        $errors[] = 'تاريخ قيد دبي غير صحيح.';
    }
    if ($rawFr !== '' && $frExpiry === null) {
        $errors[] = 'تاريخ القيد الاتحادي غير صحيح.';
    }

    $branchId = (int)($doc['branch_id'] ?? 0);

    $newAdFile = null;
    $newDuFile = null;
    $newJdFile = null;
    $newDrFile = null;
    $newFrFile = null;

    if (!$errors && $hasAdLicenseFile && isset($_FILES['ad_license_file'])) {
        $res = upload_company_doc_file($_FILES['ad_license_file'], 'ad_license', $branchId);
        if (!$res['ok']) {
            $errors[] = 'ملف رخصة أبوظبي: ' . $res['error'];
        } else {
            $newAdFile = $res['path'];
        }
    }

    if (!$errors && $hasDubaiLicenseFile && isset($_FILES['dubai_license_file'])) {
        $res = upload_company_doc_file($_FILES['dubai_license_file'], 'dubai_license', $branchId);
        if (!$res['ok']) {
            $errors[] = 'ملف رخصة دبي: ' . $res['error'];
        } else {
            $newDuFile = $res['path'];
        }
    }

    if (!$errors && $hasJudicialRegistrationFile && isset($_FILES['judicial_registration_file'])) {
        $res = upload_company_doc_file($_FILES['judicial_registration_file'], 'judicial_registration', $branchId);
        if (!$res['ok']) {
            $errors[] = 'ملف قيد دائرة القضاء: ' . $res['error'];
        } else {
            $newJdFile = $res['path'];
        }
    }

    if (!$errors && $hasDubaiRegistrationFile && isset($_FILES['dubai_registration_file'])) {
        $res = upload_company_doc_file($_FILES['dubai_registration_file'], 'dubai_registration', $branchId);
        if (!$res['ok']) {
            $errors[] = 'ملف قيد دبي: ' . $res['error'];
        } else {
            $newDrFile = $res['path'];
        }
    }

    if (!$errors && $hasFederalRegistrationFile && isset($_FILES['federal_registration_file'])) {
        $res = upload_company_doc_file($_FILES['federal_registration_file'], 'federal_registration', $branchId);
        if (!$res['ok']) {
            $errors[] = 'ملف القيد الاتحادي: ' . $res['error'];
        } else {
            $newFrFile = $res['path'];
        }
    }

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

        $uploadedPaths = array_filter([
            $newAdFile,
            $newDuFile,
            $newJdFile,
            $newDrFile,
            $newFrFile,
        ]);

        try {
            $pdo->beginTransaction();

            $parts = [];
            $params = [':id' => $docId];

            if ($hasAdLicenseExpiry) {
                $parts[] = "ad_license_expiry = :ad_license_expiry";
                $params[':ad_license_expiry'] = $adExpiry;
            }

            if ($hasDubaiLicenseExpiry) {
                $parts[] = "dubai_license_expiry = :dubai_license_expiry";
                $params[':dubai_license_expiry'] = $duExpiry;
            }

            if ($hasJudicialRegistrationExpiry) {
                $parts[] = "judicial_registration_expiry = :judicial_registration_expiry";
                $params[':judicial_registration_expiry'] = $jdExpiry;
            }

            if ($hasDubaiRegistrationExpiry) {
                $parts[] = "dubai_registration_expiry = :dubai_registration_expiry";
                $params[':dubai_registration_expiry'] = $drExpiry;
            }

            if ($hasFederalRegistrationExpiry) {
                $parts[] = "federal_registration_expiry = :federal_registration_expiry";
                $params[':federal_registration_expiry'] = $frExpiry;
            }

            if ($hasAdLicenseFile && $newAdFile !== null) {
                $parts[] = "ad_license_file = :ad_license_file";
                $params[':ad_license_file'] = $newAdFile;
            }

            if ($hasDubaiLicenseFile && $newDuFile !== null) {
                $parts[] = "dubai_license_file = :dubai_license_file";
                $params[':dubai_license_file'] = $newDuFile;
            }

            if ($hasJudicialRegistrationFile && $newJdFile !== null) {
                $parts[] = "judicial_registration_file = :judicial_registration_file";
                $params[':judicial_registration_file'] = $newJdFile;
            }

            if ($hasDubaiRegistrationFile && $newDrFile !== null) {
                $parts[] = "dubai_registration_file = :dubai_registration_file";
                $params[':dubai_registration_file'] = $newDrFile;
            }

            if ($hasFederalRegistrationFile && $newFrFile !== null) {
                $parts[] = "federal_registration_file = :federal_registration_file";
                $params[':federal_registration_file'] = $newFrFile;
            }

            $notifiedMap = [
                'ad_license_expiry'            => 'ad_license_notified',
                'dubai_license_expiry'         => 'dubai_license_notified',
                'judicial_registration_expiry' => 'judicial_registration_notified',
                'dubai_registration_expiry'    => 'dubai_registration_notified',
                'federal_registration_expiry'  => 'federal_registration_notified',
            ];

            foreach ($notifiedMap as $expiryCol => $notifiedCol) {
                if (!table_has_column($pdo, 'company_docs', $expiryCol) || !table_has_column($pdo, 'company_docs', $notifiedCol)) {
                    continue;
                }

                $newVal = match ($expiryCol) {
                    'ad_license_expiry'            => $adExpiry,
                    'dubai_license_expiry'         => $duExpiry,
                    'judicial_registration_expiry' => $jdExpiry,
                    'dubai_registration_expiry'    => $drExpiry,
                    'federal_registration_expiry'  => $frExpiry,
                    default                        => null,
                };

                $oldVal = $oldData[$expiryCol] ?? null;

                if ((string)$oldVal !== (string)$newVal) {
                    $parts[] = "{$notifiedCol} = NULL";
                }
            }

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

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

            $deleteMap = [
                'ad_license'            => ['column' => 'ad_license_expiry',            'new' => $adExpiry],
                'dubai_license'         => ['column' => 'dubai_license_expiry',         'new' => $duExpiry],
                'judicial_registration' => ['column' => 'judicial_registration_expiry', 'new' => $jdExpiry],
                'dubai_registration'    => ['column' => 'dubai_registration_expiry',    'new' => $drExpiry],
                'federal_registration'  => ['column' => 'federal_registration_expiry',  'new' => $frExpiry],
            ];

            foreach ($deleteMap as $docKey => $info) {
                $col = $info['column'];
                $newVal = $info['new'];
                $oldVal = $oldData[$col] ?? null;

                if ((string)$oldVal !== (string)$newVal) {
                    delete_company_alerts_by_doc($pdo, $docId, $docKey);
                }
            }

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

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

            throw $e;
        }

        if ($hasAdLicenseFile && $newAdFile !== null && !empty($oldData['ad_license_file']) && $oldData['ad_license_file'] !== $newAdFile) {
            safe_unlink(dirname(__DIR__) . '/' . ltrim((string)$oldData['ad_license_file'], '/'));
        }

        if ($hasDubaiLicenseFile && $newDuFile !== null && !empty($oldData['dubai_license_file']) && $oldData['dubai_license_file'] !== $newDuFile) {
            safe_unlink(dirname(__DIR__) . '/' . ltrim((string)$oldData['dubai_license_file'], '/'));
        }

        if ($hasJudicialRegistrationFile && $newJdFile !== null && !empty($oldData['judicial_registration_file']) && $oldData['judicial_registration_file'] !== $newJdFile) {
            safe_unlink(dirname(__DIR__) . '/' . ltrim((string)$oldData['judicial_registration_file'], '/'));
        }

        if ($hasDubaiRegistrationFile && $newDrFile !== null && !empty($oldData['dubai_registration_file']) && $oldData['dubai_registration_file'] !== $newDrFile) {
            safe_unlink(dirname(__DIR__) . '/' . ltrim((string)$oldData['dubai_registration_file'], '/'));
        }

        if ($hasFederalRegistrationFile && $newFrFile !== null && !empty($oldData['federal_registration_file']) && $oldData['federal_registration_file'] !== $newFrFile) {
            safe_unlink(dirname(__DIR__) . '/' . ltrim((string)$oldData['federal_registration_file'], '/'));
        }

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

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

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

if (!$doc) {
    http_response_code(404);
    exit('السجل غير موجود');
}

[$adText, $adClass, $adDays] = doc_status_meta($doc['ad_license_expiry'] ?? null);
[$duText, $duClass, $duDays] = doc_status_meta($doc['dubai_license_expiry'] ?? null);
[$jdText, $jdClass, $jdDays] = doc_status_meta($doc['judicial_registration_expiry'] ?? null);
[$drText, $drClass, $drDays] = doc_status_meta($doc['dubai_registration_expiry'] ?? null);
[$frText, $frClass, $frDays] = doc_status_meta($doc['federal_registration_expiry'] ?? null);

if (function_exists('layout_start')) {
    layout_start();
} elseif (function_exists('render_layout_start')) {
    render_layout_start();
} elseif (function_exists('layout_header')) {
    layout_header();
}
?>

<div class="company-docs-page">
    <div class="company-docs-shell">

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

        <div class="branch-card">
            <div class="branch-name"><?= h(company_branch_name_ar((int)($doc['branch_id'] ?? 0))) ?></div>
            <div class="branch-id">
                رقم السجل: <?= (int)($doc['id'] ?? 0) ?> |
                آخر تحديث: <?= h(format_datetime_ar($doc['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($adClass) ?>" title="<?= h(status_hint($adDays, $adText)) ?>"><?= h($adText) ?></span></div>
            <div class="status-card"><div class="status-title">رخصة دبي</div><span class="status-pill <?= h($duClass) ?>" title="<?= h(status_hint($duDays, $duText)) ?>"><?= h($duText) ?></span></div>
            <div class="status-card"><div class="status-title">قيد دائرة القضاء</div><span class="status-pill <?= h($jdClass) ?>" title="<?= h(status_hint($jdDays, $jdText)) ?>"><?= h($jdText) ?></span></div>
            <div class="status-card"><div class="status-title">قيد دبي</div><span class="status-pill <?= h($drClass) ?>" title="<?= h(status_hint($drDays, $drText)) ?>"><?= h($drText) ?></span></div>
            <div class="status-card"><div class="status-title">القيد الاتحادي</div><span class="status-pill <?= h($frClass) ?>" title="<?= h(status_hint($frDays, $frText)) ?>"><?= h($frText) ?></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="id" value="<?= (int)$docId ?>">

                <div class="doc-block">
                    <div class="doc-block-head">
                        <h3>رخصة أبوظبي</h3>
                        <div class="doc-actions-inline">
                            <?php if (!empty($doc['ad_license_file'])): ?>
                                <a class="file-btn open" href="<?= h(u($doc['ad_license_file'])) ?>" target="_blank" rel="noopener">فتح</a>
                                <a class="file-btn download" href="<?= h(u($doc['ad_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="ad_license_expiry" value="<?= h((string)($doc['ad_license_expiry'] ?? '')) ?>">
                            </div>
                        </div>
                        <?php if ($hasAdLicenseFile): ?>
                        <div class="field">
                            <label>رفع ملف رخصة أبوظبي</label>
                            <div class="file-input-wrap">
                                <input type="file" name="ad_license_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($doc['dubai_license_file'])): ?>
                                <a class="file-btn open" href="<?= h(u($doc['dubai_license_file'])) ?>" target="_blank" rel="noopener">فتح</a>
                                <a class="file-btn download" href="<?= h(u($doc['dubai_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="dubai_license_expiry" value="<?= h((string)($doc['dubai_license_expiry'] ?? '')) ?>">
                            </div>
                        </div>
                        <?php if ($hasDubaiLicenseFile): ?>
                        <div class="field">
                            <label>رفع ملف رخصة دبي</label>
                            <div class="file-input-wrap">
                                <input type="file" name="dubai_license_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($doc['judicial_registration_file'])): ?>
                                <a class="file-btn open" href="<?= h(u($doc['judicial_registration_file'])) ?>" target="_blank" rel="noopener">فتح</a>
                                <a class="file-btn download" href="<?= h(u($doc['judicial_registration_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="judicial_registration_expiry" value="<?= h((string)($doc['judicial_registration_expiry'] ?? '')) ?>">
                            </div>
                        </div>
                        <?php if ($hasJudicialRegistrationFile): ?>
                        <div class="field">
                            <label>رفع ملف قيد دائرة القضاء</label>
                            <div class="file-input-wrap">
                                <input type="file" name="judicial_registration_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($doc['dubai_registration_file'])): ?>
                                <a class="file-btn open" href="<?= h(u($doc['dubai_registration_file'])) ?>" target="_blank" rel="noopener">فتح</a>
                                <a class="file-btn download" href="<?= h(u($doc['dubai_registration_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="dubai_registration_expiry" value="<?= h((string)($doc['dubai_registration_expiry'] ?? '')) ?>">
                            </div>
                        </div>
                        <?php if ($hasDubaiRegistrationFile): ?>
                        <div class="field">
                            <label>رفع ملف قيد دبي</label>
                            <div class="file-input-wrap">
                                <input type="file" name="dubai_registration_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($doc['federal_registration_file'])): ?>
                                <a class="file-btn open" href="<?= h(u($doc['federal_registration_file'])) ?>" target="_blank" rel="noopener">فتح</a>
                                <a class="file-btn download" href="<?= h(u($doc['federal_registration_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="federal_registration_expiry" value="<?= h((string)($doc['federal_registration_expiry'] ?? '')) ?>">
                            </div>
                        </div>
                        <?php if ($hasFederalRegistrationFile): ?>
                        <div class="field">
                            <label>رفع ملف القيد الاتحادي</label>
                            <div class="file-input-wrap">
                                <input type="file" name="federal_registration_file" accept=".pdf,.jpg,.jpeg,.png,.webp">
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

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

    </div>
</div>

<style>
  .company-docs-page{direction:rtl;padding:20px}
  .company-docs-shell{display:flex;flex-direction:column;gap:16px}
  .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)
  }
  .topbar h1{margin:0 0 6px;font-size:25px}
  .topbar p{margin:0;font-size:14px;opacity:.92}
  .branch-card,.form-box{
    background:#fff;border:1px solid #e6eef0;border-radius:20px;padding:18px;box-shadow:0 10px 24px rgba(15,34,38,.05)
  }
  .branch-name{font-size:22px;color:#102328;margin-bottom:4px}
  .branch-id{font-size:13px;color:#73858b}
  .msg{border-radius:16px;padding:14px 16px;font-size:14px}
  .msg.success{background:#e8f8ef;color:#0d7c44;border:1px solid #cfeedd}
  .msg.error{background:#fff1f1;color:#b42323;border:1px solid #ffd3d3}
  .status-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:12px}
  .status-card{
    background:#fff;border:1px solid #e6eef0;border-radius:18px;padding:16px;box-shadow:0 10px 24px rgba(15,34,38,.05)
  }
  .status-title{font-size:13px;color:#65777d;margin-bottom:10px}
  .section-head{margin-bottom:14px}
  .section-head h2{margin:0 0 4px;font-size:18px;color:#102328}
  .section-head p{margin:0;font-size:13px;color:#74878d}
  .docs-form{display:flex;flex-direction:column;gap:16px}
  .doc-block{border:1px solid #e7eef1;border-radius:18px;padding:16px;background:linear-gradient(180deg,#ffffff 0%,#fbfdfe 100%)}
  .doc-block-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}
  .doc-block-head h3{margin:0;font-size:17px;color:#103137}
  .doc-actions-inline{display:flex;gap:8px;flex-wrap:wrap}
  .doc-grid{display:grid;grid-template-columns:1.2fr 1fr;gap:14px}
  .field{display:flex;flex-direction:column;gap:8px}
  .field label{font-size:13px;color:#52656b}
  .date-wrap,.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)
  }
  .date-wrap:focus-within,.file-input-wrap:focus-within{
    border-color:#006a7a;box-shadow:0 0 0 4px rgba(0,106,122,.08);background:#fff
  }
  .date-wrap input[type="date"],.file-input-wrap input[type="file"]{
    width:100%;border:0;outline:none;background:transparent;font-family:inherit;font-size:14px;color:#102328
  }
  .date-wrap input[type="date"]{min-height:50px}
  .file-input-wrap input[type="file"]{padding:10px 0}
  .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
  }
  .action-btn.primary{background:#d4af37;color:#13262b;font-weight:700}
  .action-btn.light{background:#fff;color:#00424f;border:1px solid rgba(0,66,79,.14)}
  .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
  }
  .file-btn.open{background:#f4f8f9;color:#00424f}
  .file-btn.download{background:#006a7a;color:#fff;border-color:#006a7a}
  .file-empty{font-size:12px;color:#7b8e94;background:#f3f6f8;border:1px solid #e2eaee;padding:8px 10px;border-radius:10px}
  .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
  }
  .status-pill.valid{background:#e7f7ef;color:#0d7c44}
  .status-pill.warning{background:#fff4d6;color:#9b6500}
  .status-pill.expired{background:#ffe3e3;color:#b42323}
  .status-pill.missing{background:#edf2f5;color:#60727a}
  .form-actions{display:flex;gap:10px;flex-wrap:wrap;margin-top:4px}
  @media (max-width:1200px){.status-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}
  @media (max-width:860px){
    .company-docs-page{padding:14px}
    .topbar{flex-direction:column}
    .status-grid{grid-template-columns:1fr 1fr}
    .doc-grid{grid-template-columns:1fr}
  }
  @media (max-width:560px){
    .status-grid{grid-template-columns:1fr}
    .form-actions,.doc-block-head{flex-direction:column;align-items:stretch}
  }
</style>

<?php
if (function_exists('layout_end')) {
    layout_end();
} elseif (function_exists('render_layout_end')) {
    render_layout_end();
} elseif (function_exists('layout_footer')) {
    layout_footer();
}
?>