<?php
// auth.php - Auth helpers com roles, expiry e CSRF
session_start();

define('USERS_FILE', __DIR__ . '/users.json');

// API do seu serviço (token mantido no servidor, não exposto ao cliente)
define('API_BASE_URL', 'https://cfc.itech2.uk/jogos/api.php');
define('API_TOKEN', 'MGNjYjZiZmY4NjAxOGEzNjhiNjA2YTU0YTJjY2FiZDkwZDRjOTU5MTFlNTI0M2Y3');

// TMDB (adicionada conforme solicitado)
define('TMDB_API_KEY', 'faba88fcdf33b87cd9df61d68092b1b1');
define('TMDB_IMAGE_BASE', 'https://image.tmdb.org/t/p');


// --- users persistence ---
function load_users() {
    if (!file_exists(USERS_FILE)) {
        file_put_contents(USERS_FILE, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    }
    $json = file_get_contents(USERS_FILE);
    $arr = json_decode($json, true);
    return is_array($arr) ? $arr : [];
}

function save_users(array $users) {
    file_put_contents(USERS_FILE, json_encode($users, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function find_user($usernameOrEmail) {
    $users = load_users();
    foreach ($users as $u) {
        if (isset($u['username']) && strcasecmp($u['username'], $usernameOrEmail) === 0) return $u;
        if (isset($u['email']) && strcasecmp($u['email'], $usernameOrEmail) === 0) return $u;
    }
    return null;
}

function find_user_by_id($id) {
    $users = load_users();
    foreach ($users as $u) {
        if (isset($u['id']) && $u['id'] == $id) return $u;
    }
    return null;
}

function update_user_by_id($id, $patch) {
    $users = load_users();
    $changed = false;
    foreach ($users as &$u) {
        if ($u['id'] == $id) {
            foreach ($patch as $k=>$v) {
                if (in_array($k, ['id','created_at'])) continue;
                $u[$k] = $v;
            }
            $changed = true;
            break;
        }
    }
    if ($changed) save_users($users);
    return $changed;
}

function delete_user_by_id($id) {
    $users = load_users();
    $out = [];
    $deleted = false;
    foreach ($users as $u) {
        if ($u['id'] == $id) { $deleted = true; continue; }
        $out[] = $u;
    }
    if ($deleted) save_users($out);
    return $deleted;
}

function register_user($username, $email, $password, $role='revendedor', $master_id=null, $expires_at=null, &$error = null) {
    $username = trim($username);
    $email = trim($email);
    if ($username === '' || $email === '' || $password === '') {
        $error = 'Preencha todos os campos.';
        return false;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Email inválido.';
        return false;
    }
    $users = load_users();
    foreach ($users as $u) {
        if (isset($u['username']) && strcasecmp($u['username'], $username) === 0) { $error = 'Nome de usuário já existe.'; return false; }
        if (isset($u['email']) && strcasecmp($u['email'], $email) === 0) { $error = 'Email já cadastrado.'; return false; }
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
    $id = ($role === 'master' ? 'master_' : 'user_') . time() . '_' . bin2hex(random_bytes(3));
    $user = [
        'id' => $id,
        'username' => $username,
        'email' => $email,
        'password_hash' => $hash,
        'role' => $role,
        'master_id' => $master_id,
        'expires_at' => $expires_at ? date(DATE_ATOM, strtotime($expires_at)) : null,
        'active' => true,
        'created_at' => date(DATE_ATOM)
    ];
    $users[] = $user;
    save_users($users);
    return $user;
}

function verify_user($usernameOrEmail, $password) {
    $u = find_user($usernameOrEmail);
    if (!$u) return false;
    if (!isset($u['password_hash'])) return false;

    if (!empty($u['expires_at'])) {
        $exp = strtotime($u['expires_at']);
        if ($exp !== false && time() > $exp) {
            if (!empty($u['active'])) {
                update_user_by_id($u['id'], ['active' => false]);
                $u['active'] = false;
            }
        }
    }

    if (empty($u['active'])) return 'blocked';

    return password_verify($password, $u['password_hash']) ? $u : false;
}

function login_user($user) {
    $_SESSION['user'] = [
        'id' => $user['id'],
        'username' => $user['username'],
        'email' => $user['email'],
        'role' => $user['role'],
    ];
    session_regenerate_id(true);
}

function logout_user() {
    unset($_SESSION['user']);
    session_regenerate_id(true);
}

function require_login() {
    if (empty($_SESSION['user'])) {
        header('Location: login.php');
        exit;
    }
    $u = find_user_by_id($_SESSION['user']['id']);
    if (!$u) {
        logout_user();
        header('Location: login.php');
        exit;
    }
    if (empty($u['active'])) {
        logout_user();
        die('Conta bloqueada. Contate o administrador.');
    }
    if (!empty($u['expires_at'])) {
        $exp = strtotime($u['expires_at']);
        if ($exp !== false && time() > $exp) {
            update_user_by_id($u['id'], ['active'=>false]);
            logout_user();
            die('Conta expirada e bloqueada. Contate o administrador.');
        }
    }
}

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

function is_master() {
    $u = current_user();
    return $u && isset($u['role']) && $u['role'] === 'master';
}

function list_revendedores_by_master($master_id) {
    $users = load_users();
    $out = [];
    foreach ($users as $u) {
        if (isset($u['master_id']) && $u['master_id'] === $master_id) $out[] = $u;
    }
    return $out;
}

function csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], (string)$token);
}