<?php
// public/debug.php — DELETE AFTER DEBUGGING
error_reporting(E_ALL);
ini_set('display_errors', '1');

echo '<h2>PHP: ' . PHP_VERSION . '</h2>';
echo '<h3>Session Test</h3>';

session_start(['cookie_httponly'=>true,'cookie_samesite'=>'Lax']);
$_SESSION['test'] = 'ok';
echo 'Session write: ' . ($_SESSION['test'] === 'ok' ? '✅' : '❌') . '<br>';
echo 'Session ID: ' . session_id() . '<br>';

echo '<h3>Config Load</h3>';
try {
    require_once __DIR__.'/../config/app.php';
    echo 'config/app.php: ✅<br>';
} catch (Throwable $e) {
    echo 'config/app.php ERROR: ' . $e->getMessage() . '<br>';
}

echo '<h3>DB Connection</h3>';
try {
    $pdo = db();
    echo 'DB connect: ✅<br>';
    $v = $pdo->query('SELECT VERSION()')->fetchColumn();
    echo 'MySQL version: ' . $v . '<br>';
    
    // Check tables exist
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    echo 'Tables: ' . implode(', ', $tables) . '<br>';
    
    // Check users table
    if (in_array('users', $tables)) {
        $count = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        echo 'Users count: ' . $count . '<br>';
        $u = $pdo->query("SELECT id,name,email,role FROM users LIMIT 3")->fetchAll();
        foreach($u as $row) {
            echo '- ' . $row['email'] . ' (' . $row['role'] . ')<br>';
        }
    } else {
        echo '❌ users table MISSING — run schema.sql!<br>';
    }
} catch (Throwable $e) {
    echo 'DB ERROR: ' . $e->getMessage() . '<br>';
}

echo '<h3>CSRF Test</h3>';
echo 'CSRF token: ' . csrf() . '<br>';

echo '<h3>Password Test</h3>';
$hash = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi';
echo 'password_verify demo123: ' . (password_verify('demo123', $hash) ? '✅' : '❌') . '<br>';

echo '<h3>POST Auth Test</h3>';
echo '<form method="POST">
  <input type="hidden" name="csrf" value="'.csrf().'">
  <input type="hidden" name="email" value="owner@demo.com">
  <input type="hidden" name="password" value="demo123">
  <button type="submit">Test Login POST</button>
</form>';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo '<br>POST received ✅<br>';
    echo 'csrf match: ' . ($_POST['csrf'] === csrf() ? '✅' : '❌ MISMATCH — Session issue!') . '<br>';
    try {
        require_once __DIR__.'/../app/Models/User.php';
        $user = User::findByEmail($_POST['email']);
        echo 'User found: ' . ($user ? '✅ '.$user['role'] : '❌ NOT FOUND') . '<br>';
        if ($user) {
            echo 'Password OK: ' . (password_verify($_POST['password'], $user['password']) ? '✅' : '❌') . '<br>';
        }
    } catch(Throwable $e) {
        echo 'Error: ' . $e->getMessage() . '<br>';
    }
}
