<?php

require_once __DIR__ . '/../models/UserModel.php';

class AuthController {
    private $userModel;

    public function __construct($db) {
        $this->userModel = new UserModel($db);
    }

    // Mostrar el formulario de login
    public function login() {
        require 'Views/loginForm.php';
    }

    // Procesar el login
    public function authenticate() {
        if (isset($_POST['email']) && isset($_POST['password'])) {
            $email = $_POST['email'];
            $password = $_POST['password'];

            // Verificar los datos en la base de datos
            $user = $this->userModel->getUserByEmail($email);

            if ($user && $user['contraseña'] === $password) { 
                session_start();
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['nombre'];
                header('Location: index.php');
                exit;
            } else {
                // Error de autenticación
                echo "<script>alert('Credenciales incorrectas.'); window.location.href='index.php';</script>";
            }
        } else {
            echo "<script>alert('Por favor, complete todos los campos.'); window.location.href='index.php';</script>";
        }
    }

    //cerrar sesión
    public function logout() {
        session_start();
        session_destroy();
        header('Location: index.php');
        exit;
    }
}
?>