<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\ResponseInterface;

class UsersController extends ResourceController
{
    protected $modelName = 'App\Models\UserModel';

    /**
     * Return an array of resource objects, themselves in array format.
     *
     * @return ResponseInterface
     */
    public function index()
    {
        $data = $this->model->findAll();
        foreach ($data as &$user) {
            unset($user['password']);
        }
        return $this->respond($data);
    }

    /**
     * Return the properties of a resource object.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function show($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        $data = $this->model->find($id);
        if (!$data) {
            return $this->failNotFound('Resource not found');
        }

        unset($data['password']);
        return $this->respond($data);
    }

    /**
     * Return a new resource object, with default properties.
     *
     * @return ResponseInterface
     */
    public function new()
    {
        return $this->respond($this->model->getDefaultValues());
    }

    /**
     * Create a new resource object, from "posted" parameters.
     *
     * @return ResponseInterface
     */
    public function create()
    {
        $data = $this->request->getVar();
        if (!$this->model->insert($data)) {
            return $this->failValidationErrors($this->model->errors());
        }

        $id = $this->model->insertID();
        return $this->respondCreated(['id' => $id], 'User created successfully');
    }

    /**
     * Return the editable properties of a resource object.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function edit($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        $data = $this->model->find($id);
        if (!$data) {
            return $this->failNotFound('User not found');
        }

        unset($data['password']);
        return $this->respond($data);
    }

    /**
     * Add or update a model resource, from "posted" properties.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function update($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        if (!$this->model->find($id)) {
            return $this->failNotFound('User not found');
        }

        $data = $this->request->getVar();
        if (!$this->model->update($id, $data)) {
            return $this->failValidationErrors($this->model->errors());
        }

        return $this->respondUpdated($this->model->find($id), 'User updated successfully');
    }

    /**
     * Delete the designated resource object from the model.
     *
     * @param int|string|null $id
     *
     * @return ResponseInterface
     */
    public function delete($id = null)
    {
        if ($id === null) {
            return $this->failNotFound('No ID provided');
        }

        if (!$this->model->find($id)) {
            return $this->failNotFound('User not found');
        }

        if (!$this->model->delete($id)) {
            return $this->fail('Failed to delete user');
        }

        return $this->respondDeleted(['id' => $id], 'User deleted successfully');
    }

    /**
     * Login the user and return a JWT token.
     *
     * @return ResponseInterface
     */
    public function login()
    {
        $username = $this->request->getVar('username');
        $password = $this->request->getVar('password');

        if (!$username || !$password) {
            return $this->failValidationErrors(['username' => 'Username is required', 'password' => 'Password is required']);
        }

        $user = $this->model->where('username', $username)->first();
        if (!$user || !password_verify($password, $user['password'])) {
            return $this->failUnauthorized('Invalid username or password');
        }
        unset($user['password']);

        $token = service('jwt')->encode(['id' => $user['id'], 'role' => $user['role']]);
        if (!$token) {
            return $this->failServerError('Failed to create JWT token');
        }

        $cookie = [
            'name'   => 'token',
            'value'  => $token,
            'expire' => 604800, // 7 days
            'secure' => getenv('CI_ENVIRONMENT') === 'production', // Use secure cookies in production
            'httponly' => true,
        ];
        $this->response->setCookie($cookie);

        return $this->respond(['user' => $user, 'message' => 'Login successful']);
    }

    /**
     * Logout the user by clearing the JWT cookie.
     *
     * @return ResponseInterface
     */
    public function logout()
    {
        $cookie = [
            'name'   => 'token',
            'value'  => '',
            'expire' => -1,
            'secure' => getenv('CI_ENVIRONMENT') === 'production', // Use secure cookies in production
            'httponly' => true,
        ];
        $this->response->setCookie($cookie);

        return $this->respondDeleted([], 'Logout successful');
    }

    /**
     * Check the login status of the user.
     *
     * @return ResponseInterface
     */
    public function status()
    {
        $this->respond(['status' => 'ok', 'message' => 'User is logged in']);
    }
}
