<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

header('Content-Type: text/plain; charset=utf-8');

echo "Locative login debug\n";
echo "====================\n\n";

try {
    echo "Step 1: session_start... ";
    session_start();
    echo "OK\n";

    echo "Step 2: require files... ";
    require_once dirname(__DIR__) . '/app/Database.php';
    require_once dirname(__DIR__) . '/app/helpers.php';
    require_once dirname(__DIR__) . '/app/Auth.php';
    echo "OK\n";

    echo "Step 3: current path... ";
    echo current_path() . "\n";

    echo "Step 4: base URL... ";
    echo app_base_path() . "\n";

    echo "Step 5: database quick query... ";
    $statement = Database::connection()->query('SELECT COUNT(*) AS total FROM users');
    $row = $statement->fetch();
    echo "OK users=" . ($row['total'] ?? 0) . "\n";

    echo "Step 6: Auth::check... ";
    $checked = Auth::check();
    echo ($checked ? 'LOGGED' : 'GUEST') . "\n";

    echo "Step 7: render login view... ";
    $pageTitle = 'Connexion - Locative';
    $error = null;
    ob_start();
    require dirname(__DIR__) . '/resources/views/auth/login.php';
    $html = ob_get_clean();
    echo "OK html_length=" . strlen($html) . "\n";

    echo "\nDebug finished OK.\n";
} catch (Throwable $e) {
    echo "\nFAILED\n";
    echo get_class($e) . ': ' . $e->getMessage() . "\n";
    echo $e->getFile() . ':' . $e->getLine() . "\n";
}
