<?php

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

class AuthController extends Controller
{
    public function logout(): void
    {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
        }
        session_destroy();
        $this->redirect('index.php?page=login');
    }

    public function register(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->render('registro', ['title' => 'PetCare | Registro']);
            return;
        }

        $data = [
            'nombre' => trim($_POST['nombre'] ?? ''),
            'email' => trim($_POST['email'] ?? ''),
            'telefono' => trim($_POST['telefono'] ?? ''),
            'ciudad' => trim($_POST['ciudad'] ?? ''),
            'tipo_mascota' => trim($_POST['tipo_mascota'] ?? ''),
            'password' => trim($_POST['password'] ?? '')
        ];

        if (!$data['nombre'] || !$data['email'] || !$data['telefono'] || !$data['ciudad'] || !$data['tipo_mascota'] || !$data['password']) {
            $this->render('registro', ['title' => 'PetCare | Registro', 'error' => 'Completa todos los campos.']);
            return;
        }

        if (UserModel::findByEmail($data['email'])) {
            $this->render('registro', ['title' => 'PetCare | Registro', 'error' => 'Ese correo ya está registrado.']);
            return;
        }

        if (UserModel::create($data)) {
            $user = UserModel::findByEmail($data['email']);
            $_SESSION['user'] = $user;
            $this->redirect('index.php?page=pedidos&auth=success&mode=register');
        }

        $this->render('registro', ['title' => 'PetCare | Registro', 'error' => 'No se pudo completar el registro.']);
    }

    public function login(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->render('login', ['title' => 'PetCare | Login']);
            return;
        }

        $identifier = trim($_POST['usuario'] ?? $_POST['email'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $user = UserModel::findByEmailOrName($identifier);

        if ($user) {
            $storedPassword = (string) ($user['password'] ?? '');
            $passwordMatches = password_verify($password, $storedPassword);
            $legacyPasswordMatches = !$passwordMatches && hash_equals($storedPassword, $password);

            if ($passwordMatches || $legacyPasswordMatches) {
                if ($legacyPasswordMatches) {
                    UserModel::updatePassword((int) ($user['id'] ?? 0), $password);
                    $user['password'] = password_hash($password, PASSWORD_BCRYPT);
                }

                $_SESSION['user'] = $user;
                $this->redirect('index.php?page=pedidos&auth=success&mode=login');
            }
        }

        $this->render('login', ['title' => 'PetCare | Login', 'error' => 'Credenciales inválidas']);
    }
}
