<?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  = 'company_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_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('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_text_with_days')) {
    function status_text_with_days(?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 => 'العين',
            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 (!table_exists($pdo, 'company_docs')) {
    http_response_code(500);
    exit('جدول company_docs غير موجود');
}

$status   = trim((string)($_GET['status'] ?? ''));
$branchId = (int)($_GET['branch_id'] ?? 0);

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

$canViewAllBranches = in_array($userRole, ['owner', 'super_admin', 'superadmin', 'admin'], true);
$canEditDocs        = $canViewAllBranches;

$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');
$hasUpdatedAt                  = table_has_column($pdo, 'company_docs', 'updated_at');

$params = [];

if ($hasBranchId) {
    $sql = "
        SELECT
            cd.id,
            cd.branch_id,
            " . ($hasAdLicenseExpiry ? 'cd.ad_license_expiry' : 'NULL') . " AS ad_license_expiry,
            " . ($hasDubaiLicenseExpiry ? 'cd.dubai_license_expiry' : 'NULL') . " AS dubai_license_expiry,
            " . ($hasJudicialRegistrationExpiry ? 'cd.judicial_registration_expiry' : 'NULL') . " AS judicial_registration_expiry,
            " . ($hasDubaiRegistrationExpiry ? 'cd.dubai_registration_expiry' : 'NULL') . " AS dubai_registration_expiry,
            " . ($hasFederalRegistrationExpiry ? 'cd.federal_registration_expiry' : 'NULL') . " AS federal_registration_expiry,
            " . ($hasUpdatedAt ? 'cd.updated_at' : 'NULL') . " AS updated_at
        FROM company_docs cd
        INNER JOIN (
            SELECT branch_id, MAX(id) AS max_id
            FROM company_docs
            WHERE branch_id IS NOT NULL AND branch_id > 0
            GROUP BY branch_id
        ) latest ON latest.max_id = cd.id
        WHERE 1=1
    ";

    if ($branchId > 0) {
        $sql .= " AND cd.branch_id = :branch_id ";
        $params[':branch_id'] = $branchId;
    }

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

    $sql .= " ORDER BY cd.branch_id ASC ";
} else {
    $sql = "
        SELECT
            id,
            0 AS branch_id,
            " . ($hasAdLicenseExpiry ? 'ad_license_expiry' : 'NULL') . " AS ad_license_expiry,
            " . ($hasDubaiLicenseExpiry ? 'dubai_license_expiry' : 'NULL') . " AS dubai_license_expiry,
            " . ($hasJudicialRegistrationExpiry ? 'judicial_registration_expiry' : 'NULL') . " AS judicial_registration_expiry,
            " . ($hasDubaiRegistrationExpiry ? 'dubai_registration_expiry' : 'NULL') . " AS dubai_registration_expiry,
            " . ($hasFederalRegistrationExpiry ? 'federal_registration_expiry' : 'NULL') . " AS federal_registration_expiry,
            " . ($hasUpdatedAt ? 'updated_at' : 'NULL') . " AS updated_at
        FROM company_docs
        ORDER BY id DESC
    ";
}

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

$stats = [
    'expired' => 0,
    'warning' => 0,
    'missing' => 0,
    'valid'   => 0,
];

$rows = [];
$seenBranches = [];

foreach ($rowsRaw as $row) {
    $currentBranchId = (int)($row['branch_id'] ?? 0);

    if ($hasBranchId && $currentBranchId <= 0) {
        continue;
    }

    if ($hasBranchId && isset($seenBranches[$currentBranchId])) {
        continue;
    }

    if ($hasBranchId) {
        $seenBranches[$currentBranchId] = true;
    }

    $documents = [
        'ad_license'            => doc_status_meta($row['ad_license_expiry'] ?? null),
        'dubai_license'         => doc_status_meta($row['dubai_license_expiry'] ?? null),
        'judicial_registration' => doc_status_meta($row['judicial_registration_expiry'] ?? null),
        'dubai_registration'    => doc_status_meta($row['dubai_registration_expiry'] ?? null),
        'federal_registration'  => doc_status_meta($row['federal_registration_expiry'] ?? null),
    ];

    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),
        'branch_id'  => $currentBranchId,
        '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="company-docs-page">
    <div class="company-docs-shell">

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

            <div class="company-docs-top-actions">
                <a class="action-btn light" href="hr_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">
                    <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>
                    </select>
                </div>

                <div class="field">
                    <label>الفرع</label>
                    <select name="branch_id">
                        <option value="0">كل الفروع</option>
                        <option value="1" <?= $branchId === 1 ? 'selected' : '' ?>>أبوظبي</option>
                        <option value="2" <?= $branchId === 2 ? 'selected' : '' ?>>دبي</option>
                        <option value="3" <?= $branchId === 3 ? 'selected' : '' ?>>العين</option>
                    </select>
                </div>

                <div class="field actions">
                    <button type="submit" class="action-btn primary">بحث</button>
                    <a href="company_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>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="8">
                                <div class="empty-state">لا توجد بيانات لعرضها حالياً</div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($rows as $row): ?>
                            <?php
                                [$adText, $adClass, $adDays] = $row['documents']['ad_license'];
                                [$duText, $duClass, $duDays] = $row['documents']['dubai_license'];
                                [$jdText, $jdClass, $jdDays] = $row['documents']['judicial_registration'];
                                [$drText, $drClass, $drDays] = $row['documents']['dubai_registration'];
                                [$frText, $frClass, $frDays] = $row['documents']['federal_registration'];
                            ?>
                            <tr>
                                <td>
                                    <span class="branch-tag"><?= h(company_branch_name_ar((int)$row['branch_id'])) ?></span>
                                </td>

                                <td><span class="status-pill <?= h($adClass) ?>" title="<?= h(status_text_with_days($adDays, $adText)) ?>"><?= h($adText) ?></span></td>
                                <td><span class="status-pill <?= h($duClass) ?>" title="<?= h(status_text_with_days($duDays, $duText)) ?>"><?= h($duText) ?></span></td>
                                <td><span class="status-pill <?= h($jdClass) ?>" title="<?= h(status_text_with_days($jdDays, $jdText)) ?>"><?= h($jdText) ?></span></td>
                                <td><span class="status-pill <?= h($drClass) ?>" title="<?= h(status_text_with_days($drDays, $drText)) ?>"><?= h($drText) ?></span></td>
                                <td><span class="status-pill <?= h($frClass) ?>" title="<?= h(status_text_with_days($frDays, $frText)) ?>"><?= h($frText) ?></span></td>

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

                                <td>
                                    <div class="row-actions">
                                        <?php if ($canEditDocs): ?>
                                            <a href="company_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>
  .company-docs-page{direction:rtl;padding:20px}
  .company-docs-shell{display:flex;flex-direction:column;gap:16px}
  .company-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)
  }
  .company-docs-topbar h1{margin:0 0 6px;font-size:26px;line-height:1.2}
  .company-docs-topbar p{margin:0;opacity:.92;font-size:14px}
  .company-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:1fr 1fr auto;gap:12px;align-items:end}
  .field{display:flex;flex-direction:column;gap:8px}
  .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:1100px;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}
  .branch-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
  }
  .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}
  .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){
    .company-docs-page{padding:14px}
    .company-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}
  }
</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();
}
?>