<?php
// admin/auth.php  –  Login + session guard + permission gates
require_once __DIR__ . '/../config.php';
session_name(SESSION_NAME);
session_start();

function is_logged_in(): bool {
    return !empty($_SESSION['admin_id']);
}

function require_login(): void {
    if (!is_logged_in()) {
        header('Location: login.php');
        exit;
    }
}

// ── Permission helpers ───────────────────────────────────────
// Permissions are loaded into the session at login time (see
// attempt_login) so every request can check them without a DB
// round-trip. The session holds:
//   $_SESSION['perm_menu'], ['perm_orders'], ['perm_settings']
//   $_SESSION['is_super']
//
// A super admin bypasses every per-section check and is the only
// role that can manage users.

function current_permissions(): array {
    return [
        'menu'     => !empty($_SESSION['perm_menu'])     || !empty($_SESSION['is_super']),
        'orders'   => !empty($_SESSION['perm_orders'])   || !empty($_SESSION['is_super']),
        'settings' => !empty($_SESSION['perm_settings']) || !empty($_SESSION['is_super']),
        'users'    => !empty($_SESSION['is_super']),
        'super'    => !empty($_SESSION['is_super']),
    ];
}

// The branch this user is scoped to. NULL = all branches (super
// admins, and any user explicitly left unassigned). Branch-scoped
// admin views use this to filter what the user sees.
function current_branch_id(): ?int {
    return isset($_SESSION['branch_id']) && $_SESSION['branch_id'] !== null
        ? (int)$_SESSION['branch_id'] : null;
}

function has_permission(string $section): bool {
    $perms = current_permissions();
    return !empty($perms[$section]);
}

// Hard gate for a page or API action. If the logged-in user lacks
// the permission, stop immediately. For API calls we emit JSON;
// for pages we send a 403 with a short message.
function require_permission(string $section): void {
    require_login();
    if (!has_permission($section)) {
        // Detect API context: admin_api.php defines json_out().
        if (function_exists('json_out')) {
            json_out(['error' => 'You do not have permission for this action'], 403);
        }
        http_response_code(403);
        echo 'Access denied — you do not have permission to view this section.';
        exit;
    }
}

function attempt_login(string $username, string $password): bool {
    // Pull permission columns alongside the hash so we can populate
    // the session in one query. is_active gates disabled accounts.
    $stmt = db()->prepare(
        'SELECT id, username, display_name, password_hash,
                perm_menu, perm_orders, perm_settings, is_super, is_active, branch_id
         FROM admin_users WHERE username=? LIMIT 1'
    );
    $stmt->execute([trim($username)]);
    $row = $stmt->fetch();

    if (!$row) return false;

    // Disabled accounts cannot log in even with a correct password.
    if (isset($row['is_active']) && (int)$row['is_active'] !== 1) {
        return false;
    }

    if (password_verify($password, $row['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['admin_id']      = $row['id'];
        $_SESSION['admin_user']    = $row['display_name'] ?: trim($username);
        $_SESSION['admin_login']   = trim($username);
        // Permission flags — cast to int so session holds clean 0/1.
        $_SESSION['perm_menu']     = (int)($row['perm_menu']     ?? 0);
        $_SESSION['perm_orders']   = (int)($row['perm_orders']   ?? 0);
        $_SESSION['perm_settings'] = (int)($row['perm_settings'] ?? 0);
        $_SESSION['is_super']      = (int)($row['is_super']      ?? 0);
        // Branch scope — NULL means all-branches access.
        $_SESSION['branch_id']     = isset($row['branch_id']) && $row['branch_id'] !== null
                                     ? (int)$row['branch_id'] : null;
        return true;
    }
    return false;
}

function logout(): void {
    session_unset();
    session_destroy();
    header('Location: login.php');
    exit;
}
