<?php
namespace Tshen\Controllers;
use Tshen\Database; use function Tshen\view; use function Tshen\redirect;

class AuthController {
    public function login() { return view('auth/login', ['title' => 'Login']); }
    public function register() { return view('auth/register', ['title' => 'Register']); }
    public function doLogin() {
        if (!\Tshen\csrf_check()) { return view('auth/login', ['title' => 'Login', 'error' => 'Invalid request']); }
        $email = $_POST['email'] ?? ''; $pass = $_POST['password'] ?? '';
        $row = Database::run('SELECT id,email,password,role FROM users WHERE email = ?', [$email])->fetch();
        if ($row && password_verify($pass, $row['password'])) {
            $_SESSION['user'] = ['id' => $row['id'], 'email' => $row['email']];
            $_SESSION['role'] = $row['role'];
            redirect('/');
        }
        return view('auth/login', ['title' => 'Login', 'error' => 'Invalid credentials']);
    }
    public function doRegister() {
        if (!\Tshen\csrf_check()) { return view('auth/register', ['title' => 'Register', 'error' => 'Invalid request']); }
        $email = trim($_POST['email'] ?? ''); $pass = $_POST['password'] ?? '';
        if (!$email || !$pass) { return view('auth/register', ['title'=>'Register','error'=>'Missing fields']); }
        // Prevent duplicate accounts
        $existing = Database::run('SELECT id FROM users WHERE email = ?', [$email])->fetch();
        if ($existing) {
            return view('auth/register', ['title' => 'Register', 'error' => 'Email already registered']);
        }
        $hash = password_hash($pass, PASSWORD_DEFAULT);
        try {
            Database::run('INSERT INTO users (email,password,role,credits) VALUES (?,?,?,?)', [$email,$hash,'user',0]);
        } catch (\PDOException $e) {
            // Graceful fallback if race-condition inserts occur
            return view('auth/register', ['title' => 'Register', 'error' => 'Could not create account. Try a different email.']);
        }
        return view('auth/login', ['title' => 'Login', 'success' => 'Account created']);
    }
    public function logout() { session_destroy(); redirect('/'); }
}