<?php

namespace App\Modules\Auth\Controllers;

use Core\Controller\Controller;
use App\Modules\Auth\Services\AuthService;

class AuthController extends Controller
{
    private AuthService $service;

    public function __construct()
    {
        $this->service = new AuthService();
    }

    public function loginForm()
    {
        $this->authView('auth/login');
    }

    public function login()
    {
        $email = $_POST['email'] ?? '';
        $password = $_POST['password'] ?? '';

        if ($this->service->login($email, $password)) {
            //  header('Location: /driftly/public/account');
            redirect('/account');
            exit;
        }

        $this->authView('auth/login', [
            'error' => 'Invalid email or password.'
        ]);
    }
    public function logout()
    {
        unset($_SESSION['user_id']);

        session_regenerate_id(true);

        //  header('Location: /driftly/public/login');
        redirect('/login');
        exit;
    }

    public function registerForm()
    {
        $this->authView('auth/register');
    }

    public function register()
    {
        $result = $this->service->register($_POST);

        if (!$result['success']) {
            $this->authView('auth/register', [
                'error' => $result['message']
            ]);
            return;
        }

        //   header('Location: /driftly/public/login');
        redirect('/login');
        exit;
    }


}