<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Database;

class Auth implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $token = $_COOKIE['auth_token'] ?? null;

        // Aucun token → logout CI4 et redirection
        if (!$token) {

            session()->destroy();

            setcookie(
                'derniere_page',
                $_SERVER['REQUEST_URI'],
                time() + 3600,
                '/'
            );

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

        $db = Database::connect();

        $row = $db->table('auth_tokens')
            ->where('token', $token)
            ->where('expires_at >', date('Y-m-d H:i:s'))
            ->get()
            ->getRow();

        // Token invalide → logout CI4
        if (!$row) {

            session()->destroy();

            setcookie(
                'derniere_page',
                $_SERVER['REQUEST_URI'],
                time() + 3600,
                '/'
            );

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

        // Charger utilisateur
        $user = $db->table('usa_usagers')
            ->where('usa_id', $row->user_id)
            ->get()
            ->getRow();

        if (!$user) {

            session()->destroy();

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

        // Si session CI4 inexistante → la créer
        if (!session()->get('usa_id')) {

            session()->set([
                'usa_id'  => $user->usa_id,
                'usa_nom' => $user->usa_nom
            ]);
        }
}


    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
    }
}