<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/db.php';

function current_user() {
    return $_SESSION['user'] ?? null;
}

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

function has_role($roles) {
    $user = current_user();
    if (!$user) return false;
    if (is_string($roles)) $roles = [$roles];
    return in_array($user['role'], $roles, true);
}

function login($username, $password) {
    $mysqli = db();
    $stmt = $mysqli->prepare('SELECT id, username, password_hash, role, full_name, branch_id FROM users WHERE username = ? AND is_active = 1 LIMIT 1');
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
    if ($user && password_verify($password, $user['password_hash'])) {
        $_SESSION['user'] = [
            'id' => (int)$user['id'],
            'username' => $user['username'],
            'role' => $user['role'],
            'full_name' => $user['full_name']
        ];
        // Set branch only if user has one assigned (sales_user should have branch, admin/super_admin may not)
        $bid = isset($user['branch_id']) ? (int)$user['branch_id'] : 0;
        if ($bid > 0) {
            $_SESSION['branch_id'] = $bid;
            // fetch branch name for display
            $b = $mysqli->query('SELECT name FROM branches WHERE id='.(int)$bid)->fetch_assoc();
            $_SESSION['branch_name'] = $b ? $b['name'] : 'Branch ' . $bid;
        }
        return true;
    }
    return false;
}

function logout() {
    $_SESSION = [];
    if (ini_get('session.use_cookies')) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
            $params['path'], $params['domain'],
            $params['secure'], $params['httponly']
        );
    }
    session_destroy();
}
