<?php

namespace App\Controllers;

use App\Config\Database;
use App\Utils\Auth;
use App\Utils\Flash;
use PDO;

class LoginController {

    public function index() {
        require_once __DIR__ . '/../../views/auth/login.php';
    }

    public function authenticate() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: /login");
            exit;
        }

        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        if (empty($email) || empty($password)) {
            Flash::set('error', 'Email and Password are required.');
            header("Location: /login");
            exit;
        }

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();

        if ($user && $user['status'] === 'inactive') {
            Flash::set('error', 'Your account is pending approval or inactive. Please contact the administrator.');
            header("Location: /login");
            exit;
        }

        if ($user && password_verify($password, $user['password_hash'])) {
            if ($user['status'] === 'suspended') {
                Flash::set('error', 'Your account has been suspended. Please contact the administrator.');
                header("Location: /login");
                exit;
            }
            
            Auth::login($user);
            if ($user['role'] === 'superadmin') {
                header("Location: /superadmin/dashboard");
            } else {
                header("Location: /dashboard");
            }
            exit;
        } else {
            Flash::set('error', 'Invalid email or password.');
            header("Location: /login");
            exit;
        }
    }

    public function logout() {
        Auth::logout();
    }
}
