<?php
/**
 * ISCMS shell - same chrome as index.php (sidebar, topbar, tokens, tables).
 * Use from root-level pages: require_once __DIR__ . '/includes/iscms_layout.php';
 */
declare(strict_types=1);

function iscms_h(?string $s): string
{
    return htmlspecialchars((string) $s, ENT_QUOTES, 'UTF-8');
}

/** Table cell: escaped text or muted dash when empty. */
function iscms_val(?string $s): string
{
    $t = trim((string) $s);
    return $t !== '' ? iscms_h($t) : '<span class="text-muted">-</span>';
}

/** Abort with 403 unless session role_code is one of the allowed codes. */
function iscms_require_roles(array $allowedRoleCodes): void
{
    $rc = (string) ($_SESSION['role_code'] ?? '');
    foreach ($allowedRoleCodes as $code) {
        if ($rc === $code) {
            return;
        }
    }
    http_response_code(403);
    header('Content-Type: text/plain; charset=UTF-8');
    echo 'Access denied.';
    exit;
}

/** Session + DB; redirects to login if unauthenticated. */
function iscms_init(): mysqli
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (!isset($_SESSION['user_id'])) {
        header('Location: login.php');
        exit;
    }

    global $conn;                                           // must precede require_once
    require_once __DIR__ . '/../layouts/dbconn.php';

    if (!($conn instanceof mysqli)) {
        throw new \RuntimeException(
            'Database connection failed: dbconn.php did not assign a mysqli instance to $conn.'
        );
    }

    return $conn;
}

/** CSRF token for POST forms (session-backed). */
function iscms_csrf_token(): string
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return (string) $_SESSION['csrf_token'];
}

function iscms_csrf_validate(?string $postedToken): bool
{
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if ($postedToken === null || $postedToken === '' || empty($_SESSION['csrf_token'])) {
        return false;
    }
    return hash_equals($_SESSION['csrf_token'], $postedToken);
}

/** True if a table exists in the current database. */
function iscms_table_exists(mysqli $conn, string $table): bool
{
    $t = $conn->real_escape_string($table);
    $r = $conn->query("SHOW TABLES LIKE '" . $t . "'");
    return $r !== false && $r->num_rows > 0;
}

/** True if column exists on table in current schema. */
function iscms_column_exists(mysqli $conn, string $table, string $column): bool
{
    $dbRow = $conn->query('SELECT DATABASE() AS d');
    if (!$dbRow) {
        return false;
    }
    $db = (string) (($dbRow->fetch_assoc()['d'] ?? ''));
    if ($db === '') {
        return false;
    }
    $st = $conn->prepare(
        'SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1'
    );
    if (!$st) {
        return false;
    }
    $st->bind_param('sss', $db, $table, $column);
    $st->execute();
    $res = $st->get_result();
    $ok  = $res && $res->num_rows > 0;
    $st->close();
    return $ok;
}

function iscms_client_ip(): string
{
    $xff   = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    $first = is_string($xff) ? trim(explode(',', $xff)[0] ?? '') : '';
    $ip    = filter_var($first, FILTER_VALIDATE_IP);
    if ($ip !== false) {
        return $ip;
    }
    $ra  = $_SERVER['REMOTE_ADDR'] ?? '';
    $ip2 = filter_var($ra, FILTER_VALIDATE_IP);
    return $ip2 !== false ? $ip2 : (string) $ra;
}

function iscms_nav_active(string $key, string $current): string
{
    return $key === $current ? ' active' : '';
}

function iscms_status_badge(string $status): string
{
    $s   = strtolower(str_replace(' ', '_', $status));
    $cls = match (true) {
        in_array($s, [
            'active', 'issued', 'approved', 'completed', 'closed',
            'payment_confirmed', 'cleared', 'conforms', 'satisfactory',
            'compliant', 'pass', 'tested', 'acceptable', 'resolved',
            'complied', 'executed',
        ], true) => 'bg-success-subtle text-success',

        in_array($s, [
            'suspended', 'inactive', 'revoked', 'rejected', 'withdrawn',
            'deregistered', 'expired', 'cancelled', 'does_not_conform',
            'unsatisfactory', 'non_compliant', 'non_conformance', 'fail',
            'overdue', 'damaged', 'compromised', 'critical', 'major', 'high',
            'not_complied', 'escalated', 'locked',
        ], true) => 'bg-danger-subtle text-danger',

        in_array($s, [
            'pending', 'pending_verification', 'draft', 'scheduled',
            'submitted', 'under_review', 'in_progress', 'pending_review',
            'partial_conformity', 'conditionally_satisfactory', 'inconclusive',
            'indeterminate', 'acknowledged', 'in_testing', 'rescheduled',
            'open', 'minor', 'medium', 'awaiting_response',
            'under_investigation', 'corrective_action_in_progress', 'appealed',
            'partially_completed', 'initiated', 'notified', 'partial',
        ], true) => 'bg-warning-subtle text-warning',

        in_array($s, [
            'awaiting_inspection', 'awaiting_lab', 'awaiting_decision',
            'pending_payment', 'pending_lab_test', 'under_query', 'investigation',
        ], true) => 'bg-primary-subtle text-primary',

        in_array($s, [
            'on_hold', 'surrendered', 'used', 'not_applicable', 'disposed',
            'observation', 'received', 'low', 'informational', 'overturned',
        ], true) => 'bg-secondary-subtle text-secondary',

        default => 'bg-secondary-subtle text-secondary',
    };
    $label = ucwords(str_replace('_', ' ', $s));
    return '<span class="badge ' . $cls . '" style="font-size:.68rem">' . iscms_h($label) . '</span>';
}

function iscms_priority_badge(int $p): string
{
    $map = [
        1 => ['Critical', 'bg-danger'],
        2 => ['High',     'bg-warning text-dark'],
        3 => ['Normal',   'bg-info text-dark'],
        4 => ['Low',      'bg-secondary'],
    ];
    [$label, $cls] = $map[$p] ?? ['-', 'bg-secondary'];
    return '<span class="badge ' . $cls . '" style="font-size:.65rem">' . iscms_h($label) . '</span>';
}

function iscms_render_head(string $htmlTitle): void
{
    ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= iscms_h($htmlTitle) ?> - SSBS-ISCMS</title>
    <meta name="robots" content="noindex, nofollow">
    <link rel="stylesheet" href="assets/libs/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/libs/remixicon/remixicon.css">
    <link rel="stylesheet" href="assets/css/iscms-app.css">
</head>
<body>
<?php
}

function iscms_render_sidebar(string $activeNav): void
{
    $role_code = $_SESSION['role_code'] ?? '';
    $showAdmin = in_array($role_code, ['SUPER_ADMIN', 'ADMIN'], true);
    ?>
<nav class="sidebar" id="sidebar">
    <a href="index.php" class="sidebar-brand text-decoration-none">
        <span class="brand-logo">&#127963;</span>
        <span class="brand-name">SSBS-ISCMS</span>
        <span class="brand-sub">South Sudan Bureau of Standards</span>
    </a>
    <div class="flag-bar">
        <span class="f-black"></span>
        <span class="f-red"></span>
        <span class="f-green"></span>
        <span class="f-blue"></span>
    </div>
    <div class="sidebar-nav">
        <div class="nav-section-title">Main</div>
        <div class="nav-item">
            <a href="index.php" class="<?= iscms_nav_active('dashboard', $activeNav) ?>">
                <i class="ri-dashboard-3-line"></i> Dashboard
            </a>
        </div>

        <div class="nav-section-title">Operations</div>
        <div class="nav-item">
            <a href="applications.php" class="<?= iscms_nav_active('applications', $activeNav) ?>">
                <i class="ri-file-list-3-line"></i> Applications
            </a>
        </div>
        <div class="nav-item">
            <a href="queue_dashboard.php" class="<?= iscms_nav_active('queue', $activeNav) ?>">
                <i class="ri-stack-line"></i> Application queue
            </a>
        </div>
        <div class="nav-item">
            <a href="viewed_queue.php" class="<?= iscms_nav_active('viewed_queue', $activeNav) ?>">
                <i class="ri-history-line"></i> Recent activity
            </a>
        </div>
        <div class="nav-item">
            <a href="inspections.php" class="<?= iscms_nav_active('inspections', $activeNav) ?>">
                <i class="ri-search-2-line"></i> Inspections
            </a>
        </div>
        <div class="nav-item">
            <a href="lab_test_requests.php" class="<?= iscms_nav_active('laboratory', $activeNav) ?>">
                <i class="ri-flask-line"></i> Laboratory
            </a>
        </div>
        <div class="nav-item">
            <a href="certifications.php" class="<?= iscms_nav_active('certifications', $activeNav) ?>">
                <i class="ri-shield-star-line"></i> Certifications
            </a>
        </div>
        <div class="nav-item">
            <a href="import_export_permits.php" class="<?= iscms_nav_active('import_export', $activeNav) ?>">
                <i class="ri-ship-line"></i> Import / Export
            </a>
        </div>

        <div class="nav-section-title">Compliance</div>
        <div class="nav-item">
            <a href="non_conformances.php" class="<?= iscms_nav_active('non_conformances', $activeNav) ?>">
                <i class="ri-error-warning-line"></i> Non-Conformances
            </a>
        </div>
        <div class="nav-item">
            <a href="enforcement_notices.php" class="<?= iscms_nav_active('enforcement', $activeNav) ?>">
                <i class="ri-scales-3-line"></i> Enforcement
            </a>
        </div>
        <div class="nav-item">
            <a href="product_recalls.php" class="<?= iscms_nav_active('market_surveillance', $activeNav) ?>">
                <i class="ri-store-2-line"></i> Market Surveillance
            </a>
        </div>
        <div class="nav-item">
            <a href="complaints.php" class="<?= iscms_nav_active('complaints', $activeNav) ?>">
                <i class="ri-feedback-line"></i> Complaints
            </a>
        </div>

        <div class="nav-section-title">Standards</div>
        <div class="nav-item">
            <a href="standards.php" class="<?= iscms_nav_active('standards', $activeNav) ?>">
                <i class="ri-book-2-line"></i> Standards Library
            </a>
        </div>
        <div class="nav-item">
            <a href="standard_categories.php" class="<?= iscms_nav_active('standard_categories', $activeNav) ?>">
                <i class="ri-folder-3-line"></i> Standard categories
            </a>
        </div>
        <div class="nav-item">
            <a href="certificate_types.php" class="<?= iscms_nav_active('certificate_types', $activeNav) ?>">
                <i class="ri-award-line"></i> Certificate types
            </a>
        </div>
        <div class="nav-item">
            <a href="fee_schedules.php" class="<?= iscms_nav_active('fee_schedules', $activeNav) ?>">
                <i class="ri-money-dollar-circle-line"></i> Fee schedules
            </a>
        </div>
        <div class="nav-item">
            <a href="products.php" class="<?= iscms_nav_active('products', $activeNav) ?>">
                <i class="ri-box-3-line"></i> Products Register
            </a>
        </div>
        <div class="nav-item">
            <a href="organizations.php" class="<?= iscms_nav_active('organizations', $activeNav) ?>">
                <i class="ri-building-2-line"></i> Organisations
            </a>
        </div>
        <div class="nav-item">
            <a href="departments.php" class="<?= iscms_nav_active('departments', $activeNav) ?>">
                <i class="ri-organization-chart"></i> Departments
            </a>
        </div>

        <?php if ($showAdmin): ?>
        <div class="nav-section-title">Administration</div>
        <div class="nav-item">
            <a href="list_users.php" class="<?= iscms_nav_active('users', $activeNav) ?>">
                <i class="ri-team-line"></i> Users
            </a>
        </div>
        <div class="nav-item">
            <a href="audit_logs.php" class="<?= iscms_nav_active('audit_logs', $activeNav) ?>">
                <i class="ri-file-code-line"></i> Audit Logs
            </a>
        </div>
        <div class="nav-item">
            <a href="settings.php" class="<?= iscms_nav_active('settings', $activeNav) ?>">
                <i class="ri-settings-3-line"></i> System Settings
            </a>
        </div>
        <?php endif; ?>
    </div>
    <div class="sidebar-footer">
        SSBS-ISCMS v2.0 &bull; <?= (int) date('Y') ?>
    </div>
</nav>
<?php
}

function iscms_render_topbar(string $pageTitle): void
{
    $full_name  = $_SESSION['full_name']  ?? 'User';
    $first_name = $_SESSION['first_name'] ?? 'User';
    $last_name  = $_SESSION['last_name']  ?? '';
    $role_name  = $_SESSION['role_name']  ?? ($_SESSION['role_code'] ?? '');
    $initials   = strtoupper(substr($first_name, 0, 1) . substr($last_name, 0, 1));
    if ($initials === '') {
        $initials = 'U';
    }
    ?>
<header class="topbar">
    <button class="d-lg-none btn btn-sm btn-light me-2" id="sidebar-toggle" type="button"
            style="border:none" aria-label="Menu">
        <i class="ri-menu-line" style="font-size:18px"></i>
    </button>
    <div class="topbar-title"><?= iscms_h($pageTitle) ?></div>
    <div class="d-flex align-items-center gap-2">
        <div class="d-none d-md-block text-end me-2"
             style="font-size:.72rem; color:#6b7280; line-height:1.4">
            <div id="topbar-date" style="font-weight:600; color:var(--ssbs-blue)"></div>
            <div id="topbar-time"></div>
        </div>
        <a class="topbar-bell text-decoration-none text-reset"
           href="notifications.php" title="Notifications">
            <i class="ri-notification-3-line"></i>
        </a>
        <div class="dropdown">
            <div class="topbar-user dropdown-toggle" data-bs-toggle="dropdown" role="button">
                <div class="avatar"><?= iscms_h($initials) ?></div>
                <div class="user-info d-none d-sm-block">
                    <div class="name"><?= iscms_h($full_name) ?></div>
                    <div class="role"><?= iscms_h((string) $role_name) ?></div>
                </div>
            </div>
            <ul class="dropdown-menu dropdown-menu-end"
                style="min-width:180px; font-size:.83rem">
                <li>
                    <a class="dropdown-item" href="profile.php">
                        <i class="ri-user-line me-2"></i>My Profile
                    </a>
                </li>
                <li>
                    <a class="dropdown-item" href="change_password.php">
                        <i class="ri-lock-password-line me-2"></i>Change Password
                    </a>
                </li>
                <li><hr class="dropdown-divider"></li>
                <li>
                    <a class="dropdown-item text-danger" href="logout.php">
                        <i class="ri-logout-box-line me-2"></i>Sign Out
                    </a>
                </li>
            </ul>
        </div>
    </div>
</header>
<main class="main-content">
<?php
}

function iscms_render_footer(): void
{
    ?>
</main>
<script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
<script>
(function tick() {
    const now  = new Date();
    const opts = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
    const dateEl = document.getElementById('topbar-date');
    const timeEl = document.getElementById('topbar-time');
    if (dateEl) dateEl.textContent = now.toLocaleDateString('en-SS', opts);
    if (timeEl) timeEl.textContent =
        now.toLocaleTimeString('en-SS', { hour: '2-digit', minute: '2-digit', hour12: false }) + ' EAT';
    setTimeout(tick, 10_000);
})();

document.getElementById('sidebar-toggle')?.addEventListener('click', function () {
    document.getElementById('sidebar').classList.toggle('open');
});
</script>
</body>
</html>
<?php
}