<?php

namespace App\Controllers\Auth;

use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\Auth\UsersModel;

class AuthController extends BaseController
{
    use ResponseTrait;

    protected $model;

    public function __construct()
    {
        $this->model = new UsersModel();
    }

    public function login()
    {
        if ($this->session->get('isLoggedIn')) {
            return redirect()->to('/');
        }

        return view('auth/login');
    }

    public function processLogin()
    {
        $input = $this->request->getJSON(true);

        if (!$input) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Invalid request'
            ], 400);
        }

        $username = $input['username'] ?? '';
        $password = $input['password'] ?? '';
        $remember = $input['remember'] ?? false;

        if (empty($username) || empty($password)) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Username and password are required'
            ], 400);
        }

        $user = $this->model->findByUsername($username);

        if (!$user) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Invalid username or password'
            ], 401);
        }

        if (!password_verify($password, $user['password'])) {
            return $this->respond([
                'status' => 'error',
                'message' => 'Invalid username or password'
            ], 401);
        }

        $this->session->set([
            'isLoggedIn' => true,
            'userId' => $user['userId'],
            'username' => $user['username']
        ]);

        if ($remember) {
            $token = bin2hex(random_bytes(32));
            $this->model->setRememberToken($user['userId'], $token);
            set_cookie('remember_token', $token, 60 * 60 * 24 * 30);
        }

        return $this->respond([
            'status' => 'success',
            'message' => 'Login successful',
            'redirect' => base_url('/')
        ], 200);
    }

    public function logout()
    {
        $userId = $this->session->get('userId');

        if ($userId) {
            $this->model->setRememberToken($userId, null);
        }

        delete_cookie('remember_token');
        $this->session->destroy();

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