<?php

namespace App\Filters;

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

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $session = session();

        if (!$session->get('user_id')) {
            // Check remember token
            $rememberToken = get_cookie('remember_token');
            if ($rememberToken) {
                $userModel = new \App\Models\UserModel();
                $user = $userModel->where('remember_token', $rememberToken)->where('is_active', 1)->first();
                if ($user) {
                    $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,
                    ]);
                    return;
                }
            }

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

        // Check role permissions
        if ($arguments) {
            $userRole = $session->get('user_role');
            if (!in_array($userRole, $arguments)) {
                return redirect()->to('/dashboard')->with('error', 'Acces non autorise');
            }
        }
    }

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