<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Csrf;
use App\Helpers\SessionHelper;
use App\Models\Role;
use App\Models\User;
use PDO;

class AuthController extends Controller
{
    public function __construct(private PDO $pdo)
    {
    }

    public function showLogin(): void
    {
        if (SessionHelper::user()) {
            header('Location: index.php?route=dashboard');
            return;
        }
        $this->view('auth/login', [
            'csrf' => Csrf::field(),
            'error' => SessionHelper::flash('error'),
        ]);
    }

    public function login(): void
    {
        if (!Csrf::validate($_POST['_token'] ?? null)) {
            SessionHelper::flash('error', 'Invalid CSRF token');
            header('Location: index.php?route=login');
            exit;
        }

        $loginId = trim($_POST['login_id'] ?? '');
        $password = $_POST['password'] ?? '';

        if (!preg_match('/^\d{12}$/', $loginId) || !$password) {
            SessionHelper::flash('error', 'Sila masukkan ID dan kata laluan.');
            header('Location: index.php?route=login');
            exit;
        }

        $userModel = new User($this->pdo);
        $user = $userModel->findByLoginId($loginId);

        if (!$user || !password_verify($password, $user['password'])) {
            SessionHelper::flash('error', 'ID atau kata laluan salah');
            header('Location: index.php?route=login');
            exit;
        }

        if ((int) $user['active'] !== 1) {
            SessionHelper::flash('error', 'Account disabled');
            header('Location: index.php?route=login');
            exit;
        }

        SessionHelper::setUser([
            'id' => $user['id'],
            'name' => $user['name'],
            'login_id' => $user['login_id'],
            'email' => $user['email'],
            'role' => $user['role_name'],
        ]);

        header('Location: index.php?route=dashboard');
    }

    public function logout(): void
    {
        SessionHelper::destroy();
        header('Location: index.php?route=login');
    }
}

