<?php

namespace App\Utils;

class Auth {
    
    public static function check() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        return isset($_SESSION['user_id']);
    }

    public static function requireLogin() {
        if (!self::check()) {
            header("Location: /login");
            exit;
        }
    }

    public static function requireAdmin() {
        self::requireLogin();
        if ($_SESSION['role'] !== 'admin') {
            http_response_code(403);
            die("Forbidden: Admin access required.");
        }
    }

    public static function requireSuperAdmin() {
        self::requireLogin();
        if ($_SESSION['role'] !== 'superadmin') {
            http_response_code(403);
            die("Forbidden: Superadmin access required.");
        }
    }

    public static function login($user) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['tenant_id'] = $user['tenant_id'];
        $_SESSION['branch_id'] = $user['branch_id'] ?? null;
        $_SESSION['role'] = $user['role'];
        $_SESSION['name'] = $user['name'];

        $db = \App\Config\Database::getInstance()->getConnection();
        
        // Fetch Tenant Config
        $stmt = $db->prepare("SELECT name, currency_code, logo_path FROM tenants WHERE id = ?");
        $stmt->execute([$user['tenant_id']]);
        $tenant = $stmt->fetch();
        $_SESSION['currency_code'] = $tenant['currency_code'] ?? '$';
        $_SESSION['tenant_name'] = $tenant['name'] ?? 'NexCore';
        $_SESSION['tenant_logo'] = $tenant['logo_path'] ?? null;

        // Load Privileges
        $db = \App\Config\Database::getInstance()->getConnection();
        if ($user['role'] === 'admin' || $user['role'] === 'superadmin') {
            $_SESSION['privileges'] = ['*']; // Wildcard
        } else {
            $stmt = $db->prepare("
                SELECT p.slug FROM privileges p 
                JOIN user_privileges up ON p.id = up.privilege_id 
                WHERE up.user_id = ?
            ");
            $stmt->execute([$user['id']]);
            $_SESSION['privileges'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
        }
    }

    public static function hasPrivilege($slug) {
        if (!self::check()) return false;
        if ($_SESSION['role'] === 'admin' || (isset($_SESSION['privileges']) && in_array('*', $_SESSION['privileges']))) {
            return true;
        }
        return isset($_SESSION['privileges']) && in_array($slug, $_SESSION['privileges']);
    }

    public static function logout() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        session_destroy();
        header("Location: /login");
        exit;
    }

    public static function user() {
        if (self::check()) {
            return [
                'id' => $_SESSION['user_id'],
                'tenant_id' => $_SESSION['tenant_id'],
                'branch_id' => $_SESSION['branch_id'],
                'role' => $_SESSION['role'],
                'name' => $_SESSION['name']
            ];
        }
        return null;
    }
}
