<?php
declare(strict_types=1);
namespace App\Core;

use App\Repositories\UserRepository;

final class SessionAuth {
    private ?array $permissionsCache = null;

    public function user(): ?array {
        if (empty($_SESSION['uid'])) return null;
        return (new UserRepository())->findById((int)$_SESSION['uid']);
    }

    public function check(): bool {
        return $this->user() !== null;
    }

    public function attempt(string $username, string $password): bool {
        $user = (new UserRepository())->findByUsername($username);
        if (!$user || !(int)$user['is_active']) return false;
        if (!password_verify($password, $user['password_hash'])) return false;
        $_SESSION['uid'] = (int)$user['id'];
        unset($_SESSION['_perm_codes']);
        $this->permissionsCache = null;
        return true;
    }

    public function logout(): void {
        unset($_SESSION['uid'], $_SESSION['_perm_codes']);
        $this->permissionsCache = null;
    }

    public function requireLogin(): void {
        if (!$this->check()) redirect(base_url('?page=login'));
    }

    public function permissions(): array {
        if ($this->permissionsCache !== null) return $this->permissionsCache;
        if (isset($_SESSION['_perm_codes']) && is_array($_SESSION['_perm_codes'])) {
            return $this->permissionsCache = $_SESSION['_perm_codes'];
        }
        $user = $this->user();
        if (!$user) return $this->permissionsCache = [];
        $codes = (new UserRepository())->permissionCodesByRole((int)$user['role_id']);
        $_SESSION['_perm_codes'] = $codes;
        return $this->permissionsCache = $codes;
    }

    private function hasAnyPermission(array $needs): bool {
        $perms = $this->permissions();
        foreach ($needs as $need) {
            if ($need !== null && in_array((string)$need, $perms, true)) {
                return true;
            }
        }
        return false;
    }

    public function canAccess(string $page): bool {
        $user = $this->user();
        if (!$user) return false;
        if (($user['role_code'] ?? '') === 'admin') return true;

        $map = [
            'dashboard' => ['page.dashboard'],

            'items' => ['page.items'],
            'categories' => ['page.categories'],
            'category_store' => ['page.categories'],
            'category_update' => ['page.categories'],
            'category_move_items' => ['page.categories'],
            'category_delete' => ['page.categories'],
            'locations' => ['page.locations', 'page.items'],
            'location_store' => ['page.locations', 'page.items'],
            'location_update' => ['page.locations', 'page.items'],
            'location_delete' => ['page.locations', 'page.items'],
            'available_items' => ['page.items'],
            'item_public' => [null],
            'item_barcode' => ['page.items'],
            'item_create' => ['page.items'],
            'item_store' => ['page.items'],
            'item_edit' => ['page.items'],
            'item_update' => ['page.items'],
            'item_delete' => ['page.items'],

            'invoices' => ['page.invoices'],
            'invoice_show' => ['page.invoices'],
            'customer_lookup' => ['page.invoices', 'page.tailoring_create', 'page.tailoring_orders'],
            'customer_search' => ['page.invoices'],

            // Queue split permissions with backward compatibility
            'queue_print' => ['page.queue_print', 'page.queue'],
            'queue_screen' => ['page.queue_manage', 'page.queue'],
            'queue_snapshot' => [null],
            'queue_public' => [null],
            'queue_tv' => [null],
            'queue_call_next' => ['page.queue_manage', 'page.queue'],
            'queue_done' => ['page.queue_manage', 'page.queue'],
            'queue_skip' => ['page.queue_manage', 'page.queue'],
            'queue_recall' => ['page.queue_manage', 'page.queue'],
            'queue_open_day' => ['page.queue_manage', 'page.queue'],
            'queue_reset' => ['page.queue_manage', 'page.queue'],

            // Tailoring split permissions with backward compatibility
            'tailoring' => ['page.tailoring_create', 'page.tailoring_orders', 'page.tailoring'],
            'tailoring_store' => ['page.tailoring_create', 'page.tailoring'],
            'tailoring_print' => ['page.tailoring_orders', 'page.tailoring'],
            'tailoring_ready' => ['page.tailoring_orders', 'page.tailoring'],

            'returns' => ['page.returns'],
            'return_show' => ['page.returns'],
            'return_process' => ['page.returns'],

            'reports' => ['page.reports'],
            'queue_reports' => ['page.reports'],

            'customers' => ['page.customers'],
            'customer_blacklist' => ['page.customers'],
            'customer_unblacklist' => ['page.customers'],

            'studio' => ['page.studio', 'page.studio_create', 'page.studio_manage'],
            'studio_store' => ['page.studio_create', 'page.studio'],
            'studio_update' => ['page.studio_manage', 'page.studio'],
            'studio_delete' => ['page.studio_manage', 'page.studio'],
            'studio_booked_slots' => ['page.studio', 'page.studio_create', 'page.studio_manage'],

            'settings_branding' => ['page.settings'],
            'settings_branding_save' => ['page.settings'],
            'settings_whatsapp' => ['page.settings'],
            'settings_whatsapp_save' => ['page.settings'],
            'queue_settings' => ['page.settings'],

            'audit' => ['page.audit'],

            'users' => ['page.users'],
            'user_create' => ['page.users'],
            'user_store' => ['page.users'],
            'user_edit' => ['page.users'],
            'user_update' => ['page.users'],
            'user_delete' => ['page.users'],
        ];

        $needs = $map[$page] ?? [null];
        if (in_array(null, $needs, true) && count($needs) === 1) return true;
        return $this->hasAnyPermission($needs);
    }

    public function requirePageAccess(string $page): void {
        $this->requireLogin();
        if (!$this->canAccess($page)) {
            http_response_code(403);
            echo '<!doctype html><html lang="ar" dir="rtl"><meta charset="utf-8"><title>403</title><body style="font-family:Tahoma,Arial;padding:30px;background:#f8fafc">';
            echo '<h2 style="color:#b42318">لا تملك صلاحية الوصول إلى هذه الصفحة</h2>';
            echo '<p><a href="' . e(base_url('?page=dashboard')) . '">العودة إلى لوحة التحكم</a></p>';
            echo '</body></html>';
            exit;
        }
    }
}
