<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\Controller;

class AuthController extends Controller
{
    protected $helpers = ['form', 'url'];

    public function login()
    {
        if (session()->get('user_id')) {
            return redirect()->to('/dashboard');
        }

        if ($this->request->getMethod() === 'post') {
            $rules = [
                'email' => 'required|valid_email',
                'password' => 'required|min_length[6]',
            ];

            if (!$this->validate($rules)) {
                return view('auth/login', ['validation' => $this->validator, 'error' => null]);
            }

            $email = $this->request->getPost('email');
            $password = $this->request->getPost('password');
            $remember = $this->request->getPost('remember');

            $userModel = new UserModel();
            $user = $userModel->findByEmail($email);

            if (!$user) {
                return view('auth/login', ['validation' => null, 'error' => 'Email ou mot de passe incorrect']);
            }

            if ($userModel->isLocked($user['id'])) {
                return view('auth/login', ['validation' => null, 'error' => 'Compte temporairement verrouille. Reessayez dans 30 minutes.']);
            }

            if (!password_verify($password, $user['password_hash'])) {
                $userModel->incrementFailedAttempts($user['id']);
                return view('auth/login', ['validation' => null, 'error' => 'Email ou mot de passe incorrect']);
            }

            $userModel->updateLogin($user['id']);

            session()->set([
                'user_id' => $user['id'],
                'user_email' => $user['email'],
                'user_name' => $user['first_name'] . ' ' . $user['last_name'],
                'user_role' => $user['role'],
                'company_id' => 1,
            ]);

            if ($remember) {
                $token = bin2hex(random_bytes(32));
                $userModel->update($user['id'], ['remember_token' => $token]);
                set_cookie('remember_token', $token, 30 * 24 * 60 * 60);
            }

            return redirect()->to('/dashboard');
        }

        return view('auth/login', ['validation' => null, 'error' => null]);
    }

    public function logout()
    {
        session()->destroy();
        delete_cookie('remember_token');
        return redirect()->to('/login');
    }

    public function forgotPassword()
    {
        if ($this->request->getMethod() === 'post') {
            $email = $this->request->getPost('email');
            $userModel = new UserModel();
            $user = $userModel->findByEmail($email);

            if ($user) {
                $token = bin2hex(random_bytes(32));
                session()->setFlashdata('success', 'Si cet email existe, un lien de reinitialisation a ete envoye.');
            } else {
                session()->setFlashdata('success', 'Si cet email existe, un lien de reinitialisation a ete envoye.');
            }

            return redirect()->to('/login');
        }

        return view('auth/forgot');
    }
}
