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

$page_title   = 'مستندات الموظفين';
$layout_title = 'مستندات الموظفين';
$active_page  = 'hr_docs_dashboard';
$active_menu  = 'hr';

require_once __DIR__ . '/../inc/layout.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_has_column')) {
    function table_has_column(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];

        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) {
            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('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_text_with_days')) {
    function status_text_with_days(?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('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);
    }
}

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

/* =========================
   الفلاتر
========================= */
$search           = trim((string)($_GET['search'] ?? ''));
$status           = trim((string)($_GET['status'] ?? ''));
$personTypeFilter = trim((string)($_GET['person_type'] ?? ''));

/* =========================
   الصلاحيات
========================= */
$userRole = strtolower(trim((string)($_SESSION['role'] ?? '')));
$branchId = (int)($_SESSION['branch_id'] ?? 0);

/* الأونر والإدمن يشوفون كل الفروع ويقدرون يعدلون */
$canViewAllBranches = in_array($userRole, ['owner', 'super_admin', 'superadmin', 'admin'], true);
$canEditDocs        = $canViewAllBranches;

/* =========================
   التحقق من الأعمدة
========================= */
$employeesHasBranchId        = table_has_column($pdo, 'employees', 'branch_id');
$employeesHasPersonType      = table_has_column($pdo, 'employees', 'person_type');
$employeesHasRequireVisa     = table_has_column($pdo, 'employees', 'require_visa');
$employeesHasRequireContract = table_has_column($pdo, 'employees', 'require_contract');
$employeesHasRequireDriving  = table_has_column($pdo, 'employees', 'require_driving_license');

$docsHasContractExpiry = table_has_column($pdo, 'employee_docs', 'contract_expiry');
$docsHasDrivingExpiry  = table_has_column($pdo, 'employee_docs', 'driving_license_expiry');
$docsHasUpdatedAt      = table_has_column($pdo, 'employee_docs', 'updated_at');

/* =========================
   الأعمدة الديناميكية
========================= */
$selectBranchId        = $employeesHasBranchId ? "e.branch_id" : "0 AS branch_id";
$selectPersonType      = $employeesHasPersonType ? "e.person_type" : "'employee' AS person_type";
$selectRequireVisa     = $employeesHasRequireVisa ? "e.require_visa" : "1 AS require_visa";
$selectRequireContract = $employeesHasRequireContract ? "e.require_contract" : "1 AS require_contract";
$selectRequireDriving  = $employeesHasRequireDriving ? "e.require_driving_license" : "0 AS require_driving_license";
$selectContract        = $docsHasContractExpiry ? "d.contract_expiry" : "NULL AS contract_expiry";
$selectDriving         = $docsHasDrivingExpiry ? "d.driving_license_expiry" : "NULL AS driving_license_expiry";
$selectUpdatedAt       = $docsHasUpdatedAt ? "d.updated_at" : "NULL AS updated_at";

/* =========================
   الاستعلام
========================= */
$sql = "
    SELECT
        e.id,
        e.name,
        {$selectBranchId},
        {$selectPersonType},
        {$selectRequireVisa},
        {$selectRequireContract},
        {$selectRequireDriving},
        d.visa_expiry,
        d.emirates_id_expiry,
        d.insurance_expiry,
        d.passport_expiry,
        {$selectContract},
        {$selectDriving},
        {$selectUpdatedAt}
    FROM employees e
    LEFT JOIN employee_docs d ON d.employee_id = e.id
    WHERE 1=1
";

$params = [];

if ($search !== '') {
    $sql .= " AND (e.name LIKE :search OR CAST(e.id AS CHAR) LIKE :search2) ";
    $params[':search']  = '%' . $search . '%';
    $params[':search2'] = '%' . $search . '%';
}

$allowedPersonTypes = ['employee', 'owner', 'special_affiliate', 'partner'];
if ($personTypeFilter !== '' && in_array($personTypeFilter, $allowedPersonTypes, true) && $employeesHasPersonType) {
    $sql .= " AND e.person_type = :person_type ";
    $params[':person_type'] = $personTypeFilter;
}

/* المستخدم العادي يرى فقط فرعه */
if (!$canViewAllBranches && $branchId > 0 && $employeesHasBranchId) {
    $sql .= " AND e.branch_id = :branch_id ";
    $params[':branch_id'] = $branchId;
}

$sql .= " ORDER BY e.id DESC ";

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

/* =========================
   تجهيز البيانات
========================= */
$stats = [
    'expired'      => 0,
    'warning'      => 0,
    'missing'      => 0,
    'valid'        => 0,
    'not-required' => 0,
];

$rows = [];

foreach ($rowsRaw as $row) {
    $requireVisa     = (int)($row['require_visa'] ?? 1) === 1;
    $requireContract = (int)($row['require_contract'] ?? 1) === 1;
    $requireDriving  = (int)($row['require_driving_license'] ?? 0) === 1;

    $documents = [
        'visa'      => doc_status_meta($row['visa_expiry'] ?? null, $requireVisa),
        'eid'       => doc_status_meta($row['emirates_id_expiry'] ?? null, true),
        'insurance' => doc_status_meta($row['insurance_expiry'] ?? null, true),
        'passport'  => doc_status_meta($row['passport_expiry'] ?? null, true),
        'contract'  => doc_status_meta($row['contract_expiry'] ?? null, $requireContract),
        'driving'   => doc_status_meta($row['driving_license_expiry'] ?? null, $requireDriving),
    ];

    foreach ($documents as $meta) {
        $class = $meta[1];
        if (isset($stats[$class])) {
            $stats[$class]++;
        }
    }

    if ($status !== '') {
        $hasRequestedStatus = false;
        foreach ($documents as $meta) {
            if ($meta[1] === $status) {
                $hasRequestedStatus = true;
                break;
            }
        }
        if (!$hasRequestedStatus) {
            continue;
        }
    }

    $rows[] = [
        'id'          => (int)($row['id'] ?? 0),
        'name'        => trim((string)($row['name'] ?? '')) !== '' ? (string)$row['name'] : 'بدون اسم',
        'branch_id'   => (int)($row['branch_id'] ?? 0),
        'person_type' => (string)($row['person_type'] ?? 'employee'),
        'updated_at'  => $row['updated_at'] ?? null,
        'documents'   => $documents,
    ];
}

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="hr-docs-page">
    <div class="hr-docs-shell">

        <div class="hr-docs-topbar">
            <div>
                <h1>لوحة مستندات الموظفين</h1>
                <p>إدارة الهوية والجواز والتأمين والإقامة وعقد العمل ورخصة القيادة حسب متطلبات كل شخص</p>
            </div>

            <div class="hr-docs-top-actions">
                <a class="action-btn light" href="company_docs_dashboard.php">مستندات الشركة</a>
            </div>
        </div>

        <div class="stats-row">
            <div class="stat-chip expired">
                <span class="label">منتهي</span>
                <span class="value"><?= (int)$stats['expired'] ?></span>
            </div>

            <div class="stat-chip warning">
                <span class="label">قريب</span>
                <span class="value"><?= (int)$stats['warning'] ?></span>
            </div>

            <div class="stat-chip missing">
                <span class="label">غير مدخل</span>
                <span class="value"><?= (int)$stats['missing'] ?></span>
            </div>

            <div class="stat-chip valid">
                <span class="label">سليم</span>
                <span class="value"><?= (int)$stats['valid'] ?></span>
            </div>
        </div>

        <div class="filter-box">
            <form method="get" class="filter-form">
                <div class="field wide">
                    <label>بحث باسم الشخص أو رقمه</label>
                    <input type="text" name="search" value="<?= h($search) ?>" placeholder="ابحث هنا">
                </div>

                <div class="field">
                    <label>الحالة</label>
                    <select name="status">
                        <option value="">الكل</option>
                        <option value="expired" <?= $status === 'expired' ? 'selected' : '' ?>>منتهي</option>
                        <option value="warning" <?= $status === 'warning' ? 'selected' : '' ?>>قريب</option>
                        <option value="missing" <?= $status === 'missing' ? 'selected' : '' ?>>غير مدخل</option>
                        <option value="valid" <?= $status === 'valid' ? 'selected' : '' ?>>سليم</option>
                        <option value="not-required" <?= $status === 'not-required' ? 'selected' : '' ?>>غير مطلوب</option>
                    </select>
                </div>

                <div class="field">
                    <label>النوع</label>
                    <select name="person_type">
                        <option value="">الكل</option>
                        <option value="employee" <?= $personTypeFilter === 'employee' ? 'selected' : '' ?>>موظف</option>
                        <option value="owner" <?= $personTypeFilter === 'owner' ? 'selected' : '' ?>>صاحب الشركة</option>
                        <option value="special_affiliate" <?= $personTypeFilter === 'special_affiliate' ? 'selected' : '' ?>>منتسب خاص</option>
                        <option value="partner" <?= $personTypeFilter === 'partner' ? 'selected' : '' ?>>شريك</option>
                    </select>
                </div>

                <div class="field actions">
                    <button type="submit" class="action-btn primary">بحث</button>
                    <a href="hr_docs_dashboard.php" class="action-btn light">عرض الكل</a>
                </div>
            </form>
        </div>

        <div class="table-box">
            <div class="table-head">
                <div>
                    <h2>قائمة المستندات</h2>
                    <p>تظهر المستندات المطلوبة وغير المطلوبة لكل شخص بحسب حالته الفعلية</p>
                </div>
            </div>

            <div class="table-wrap">
                <table class="docs-table">
                    <thead>
                        <tr>
                            <th>الشخص</th>
                            <th>الفرع</th>
                            <th>النوع</th>
                            <th>الإقامة</th>
                            <th>الهوية</th>
                            <th>التأمين</th>
                            <th>الجواز</th>
                            <th>عقد العمل</th>
                            <th>رخصة القيادة</th>
                            <th>آخر تحديث</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="11">
                                <div class="empty-state">لا توجد بيانات لعرضها حالياً</div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($rows as $row): ?>
                            <?php
                                [$visaText, $visaClass, $visaDays]             = $row['documents']['visa'];
                                [$eidText, $eidClass, $eidDays]                = $row['documents']['eid'];
                                [$insText, $insClass, $insDays]                = $row['documents']['insurance'];
                                [$passText, $passClass, $passDays]             = $row['documents']['passport'];
                                [$contractText, $contractClass, $contractDays] = $row['documents']['contract'];
                                [$drivingText, $drivingClass, $drivingDays]    = $row['documents']['driving'];
                            ?>
                            <tr>
                                <td>
                                    <div class="emp-cell">
                                        <div class="emp-name"><?= h($row['name']) ?></div>
                                        <div class="emp-id">الرقم: <?= (int)$row['id'] ?></div>
                                    </div>
                                </td>

                                <td>
                                    <span class="branch-tag"><?= h(branch_name_ar((int)$row['branch_id'])) ?></span>
                                </td>

                                <td>
                                    <span class="person-type-tag"><?= h(person_type_ar($row['person_type'])) ?></span>
                                </td>

                                <td><span class="status-pill <?= h($visaClass) ?>" title="<?= h(status_text_with_days($visaDays, $visaText)) ?>"><?= h($visaText) ?></span></td>
                                <td><span class="status-pill <?= h($eidClass) ?>" title="<?= h(status_text_with_days($eidDays, $eidText)) ?>"><?= h($eidText) ?></span></td>
                                <td><span class="status-pill <?= h($insClass) ?>" title="<?= h(status_text_with_days($insDays, $insText)) ?>"><?= h($insText) ?></span></td>
                                <td><span class="status-pill <?= h($passClass) ?>" title="<?= h(status_text_with_days($passDays, $passText)) ?>"><?= h($passText) ?></span></td>
                                <td><span class="status-pill <?= h($contractClass) ?>" title="<?= h(status_text_with_days($contractDays, $contractText)) ?>"><?= h($contractText) ?></span></td>
                                <td><span class="status-pill <?= h($drivingClass) ?>" title="<?= h(status_text_with_days($drivingDays, $drivingText)) ?>"><?= h($drivingText) ?></span></td>

                                <td><?= h(format_datetime_ar($row['updated_at'] ?? null)) ?></td>

                                <td>
                                    <div class="row-actions">
                                        <?php if ($canEditDocs): ?>
                                            <a href="hr_docs_edit.php?id=<?= (int)$row['id'] ?>" class="mini-btn primary">تعديل</a>
                                        <?php else: ?>
                                            <span class="mini-btn disabled" aria-disabled="true" title="ليس لديك صلاحية التعديل">التعديل مقفل</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<style>
  .hr-docs-page{direction:rtl;padding:20px}
  .hr-docs-shell{display:flex;flex-direction:column;gap:16px}
  .hr-docs-topbar{
    display:flex;justify-content:space-between;align-items:flex-start;gap:16px;
    background:linear-gradient(135deg,#00424f,#006a7a);color:#fff;border-radius:18px;padding:18px 20px;
    box-shadow:0 14px 30px rgba(0,0,0,.10)
  }
  .hr-docs-topbar h1{margin:0 0 6px;font-size:26px;line-height:1.2}
  .hr-docs-topbar p{margin:0;opacity:.92;font-size:14px}
  .hr-docs-top-actions{display:flex;gap:10px;flex-wrap:wrap}
  .stats-row{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
  .stat-chip{background:#fff;border:1px solid #e6eef0;border-radius:18px;padding:16px;box-shadow:0 10px 24px rgba(15,34,38,.05)}
  .stat-chip .label{display:block;font-size:13px;color:#65777d;margin-bottom:8px}
  .stat-chip .value{display:block;font-size:28px;font-weight:800;color:#0f2226}
  .stat-chip.expired{border-top:4px solid #df4c4c}
  .stat-chip.warning{border-top:4px solid #f0b429}
  .stat-chip.missing{border-top:4px solid #a9b6bc}
  .stat-chip.valid{border-top:4px solid #21a366}
  .filter-box,.table-box{
    background:#fff;border:1px solid #e6eef0;border-radius:18px;padding:16px;
    box-shadow:0 10px 24px rgba(15,34,38,.05)
  }
  .filter-form{display:grid;grid-template-columns:2fr 1fr 1fr auto;gap:12px;align-items:end}
  .field{display:flex;flex-direction:column;gap:8px}
  .field.wide{min-width:240px}
  .field label{font-size:13px;color:#52656b}
  .field input,.field select{
    height:46px;border:1px solid #dbe5e8;border-radius:14px;padding:0 14px;font-family:inherit;
    font-size:14px;outline:none;background:#fbfdfe;color:#102328
  }
  .field input:focus,.field select:focus{border-color:#006a7a;box-shadow:0 0 0 3px rgba(0,106,122,.08)}
  .field.actions{flex-direction:row;gap:10px;align-items:center}
  .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)}
  .action-btn:hover{transform:translateY(-1px)}
  .table-head{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px}
  .table-head h2{margin:0 0 4px;color:#0f2226;font-size:18px}
  .table-head p{margin:0;color:#6d8087;font-size:13px}
  .table-wrap{overflow:auto}
  .docs-table{width:100%;min-width:1280px;border-collapse:separate;border-spacing:0}
  .docs-table thead th{
    background:#f7fbfc;color:#50646b;font-size:13px;font-weight:800;text-align:right;padding:14px 12px;
    border-bottom:1px solid #e3ecef;position:sticky;top:0;white-space:nowrap
  }
  .docs-table tbody td{
    background:#fff;padding:14px 12px;border-bottom:1px solid #edf3f5;vertical-align:middle;white-space:nowrap
  }
  .docs-table tbody tr:hover td{background:#fbfefe}
  .emp-cell{display:flex;flex-direction:column;gap:4px}
  .emp-name{font-size:14px;color:#102328}
  .emp-id{font-size:12px;color:#7a8d93}
  .person-type-tag{
    display:inline-flex;align-items:center;justify-content:center;min-width:86px;padding:7px 12px;border-radius:999px;
    font-size:12px;background:#eef7fa;color:#0b5c68
  }
  .branch-tag{
    display:inline-flex;align-items:center;justify-content:center;min-width:78px;padding:7px 12px;border-radius:999px;
    font-size:12px;background:#f4f1ff;color:#5a35b1
  }
  .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}
  .status-pill.not-required{background:#eef6ff;color:#4b6b88}
  .row-actions{display:flex;gap:8px;flex-wrap:wrap}
  .mini-btn{
    display:inline-flex;align-items:center;justify-content:center;min-width:90px;height:34px;padding:0 12px;border-radius:10px;
    text-decoration:none;font-size:13px;border:1px solid #d6e3e7;background:#f4f8f9;color:#00424f
  }
  .mini-btn.primary{background:#006a7a;color:#fff;border-color:#006a7a}
  .mini-btn.disabled{
    background:#edf2f5 !important;
    color:#90a0a7 !important;
    border-color:#d7e0e4 !important;
    cursor:not-allowed;
    pointer-events:none;
  }
  .empty-state{text-align:center;padding:24px;color:#74878d}
  @media (max-width:1200px){.stats-row{grid-template-columns:repeat(2,minmax(0,1fr))}}
  @media (max-width:860px){
    .hr-docs-page{padding:14px}
    .hr-docs-topbar{flex-direction:column}
    .filter-form{grid-template-columns:1fr}
    .field.actions{flex-direction:column;align-items:stretch}
    .stats-row{grid-template-columns:1fr}
  }
   /* إصلاح انكماش صفحة تعديل القضية */
.layout-content,
.layout-main,
.main-content,
.page-content,
.app-content,
.content,
.content-area{
  width:100% !important;
  max-width:none !important;
}
</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();
}
?>