<?php
declare(strict_types=1);

// config/app.php
// Versi kompatibel dengan login master HR

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// App info
if (!defined('APP_NAME')) {
    define('APP_NAME', 'Sistem Keperawatan RS BaliMed');
}

if (!defined('APP_VERSION')) {
    define('APP_VERSION', '1.0.0');
}

if (!defined('BASE_URL')) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
    define('BASE_URL', $scheme . $_SERVER['HTTP_HOST'] . '/');
}

if (!defined('LOGO_URL')) {
    define('LOGO_URL', 'https://balimedhospital.co.id/wp-content/uploads/elementor/thumbs/logo-dark-o9cm6tnx14hcrnest1hge1pwnqj0yaumij7qohadlm.png');
}

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

/**
 * Cek login berdasarkan session master HR
 */
if (!function_exists('isLoggedIn')) {
    function isLoggedIn(): bool
    {
        return !empty($_SESSION['user']['logged_in']);
    }
}

/**
 * Ambil user aktif dalam format kompatibel dengan kode lama
 */
if (!function_exists('current_user')) {
    function current_user(): ?array
    {
        if (empty($_SESSION['user']) || !is_array($_SESSION['user'])) {
            return null;
        }

        $u = $_SESSION['user'];

        return [
            'id'            => $u['employee_id'] ?? null,
            'user_id'       => $u['employee_id'] ?? null,
            'employee_id'   => $u['employee_id'] ?? null,
            'nik'           => $u['nik'] ?? ($u['employee_code'] ?? ''),
            'employee_code' => $u['employee_code'] ?? '',
            'full_name'     => $u['nama'] ?? '',
            'nama'          => $u['nama'] ?? '',
            'username'      => $u['username'] ?? '',
            'email'         => $u['email'] ?? '',
            'unit'          => $u['unit_name'] ?? '',
            'unit_name'     => $u['unit_name'] ?? '',
            'jabatan'       => $u['position_name'] ?? '',
            'position_name' => $u['position_name'] ?? '',
            'role'          => $u['role'] ?? 'user',
            'app_code'      => $u['app_code'] ?? '',
            'app_name'      => $u['app_name'] ?? '',
        ];
    }
}

/**
 * Redirect auth
 */
if (!function_exists('checkAuth')) {
    function checkAuth(): void
    {
        if (!isLoggedIn()) {
            header('Location: ' . BASE_URL . 'login.php');
            exit;
        }
    }
}

/**
 * Role check
 */
if (!function_exists('hasRole')) {
    function hasRole($roles): bool
    {
        if (!isLoggedIn()) {
            return false;
        }

        if (!is_array($roles)) {
            $roles = [$roles];
        }

        $currentRole = strtolower((string)($_SESSION['user']['role'] ?? ''));

        if ($currentRole === 'superadmin') {
            return true;
        }

        $roles = array_map(static fn($r) => strtolower((string)$r), $roles);
        return in_array($currentRole, $roles, true);
    }
}

/**
 * Permission check
 * Versi aman:
 * - superadmin => full access
 * - admin => full access
 * - selain itu, fallback ke tabel permission lama jika masih dipakai
 */
if (!function_exists('hasPermission')) {
    function hasPermission(string $module, string $action = 'view'): bool
    {
        if (!isLoggedIn()) {
            return false;
        }

        $currentRole = strtolower((string)($_SESSION['user']['role'] ?? ''));

        if (in_array($currentRole, ['superadmin', 'admin'], true)) {
            return true;
        }

        // fallback kalau sistem permission lama masih dipakai
        if (!function_exists('getConnection')) {
            return false;
        }

        $conn = getConnection();
        if (!$conn) {
            return false;
        }

        $userId = (int)($_SESSION['user']['employee_id'] ?? 0);
        if ($userId <= 0) {
            return false;
        }

        if ($conn instanceof mysqli) {
            $stmt = $conn->prepare("
                SELECT can_view, can_create, can_edit, can_delete
                FROM user_module_permissions
                WHERE user_id = ? AND module_key = ?
            ");

            if (!$stmt) {
                return false;
            }

            $stmt->bind_param("is", $userId, $module);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($row = $result->fetch_assoc()) {
                return (int)($row['can_' . $action] ?? 0) === 1;
            }

            return false;
        }

        if ($conn instanceof PDO) {
            $stmt = $conn->prepare("
                SELECT can_view, can_create, can_edit, can_delete
                FROM user_module_permissions
                WHERE user_id = ? AND module_key = ?
            ");

            if (!$stmt) {
                return false;
            }

            $stmt->execute([$userId, $module]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($row) {
                return (int)($row['can_' . $action] ?? 0) === 1;
            }

            return false;
        }

        return false;
    }
}

// Load functions
$functionsFile = __DIR__ . '/../includes/functions.php';
if (file_exists($functionsFile)) {
    require_once $functionsFile;
}