<?php
defined('BASEPATH') or exit('No direct script access allowed');

use Restserver\Libraries\REST_Controller;

require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

class Users extends REST_Controller
{

	public function __construct()
	{
		parent::__construct();
		// Load the User_model
		$this->load->model('user_model');
		// Load the form validation library
		$this->load->library('form_validation');
		// Configure the validation rules
		$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[255]|strong_password');
		$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
	}

	public function index_get($id = NULL)
	{
		// Get a single user by ID
		if ($id !== NULL) {
			$user = $this->user_model->get_user($id);
			if ($user) {
				$this->response($user, REST_Controller::HTTP_OK);
			} else {
				$this->response([
					'status' => FALSE,
					'message' => 'User not found'
				], REST_Controller::HTTP_NOT_FOUND);
			}
		} else {
			// Get all users
			$users = $this->user_model->get_users();
			$this->response($users, REST_Controller::HTTP_OK);
		}
	}

	public function index_post()
	{
		// Create a new user
		$data = $this->post();

		if ($this->form_validation->set_data($data) == FALSE) {
			$this->response([
				'status' => FALSE,
				'message' => validation_errors()
			], REST_Controller::HTTP_BAD_REQUEST);
		} else {
			$user_id = $this->user_model->create_user($data);
			if ($user_id) {
				$this->response([
					'status' => TRUE,
					'message' => 'User created successfully',
					'data' => ['user_id' => $user_id]
				], REST_Controller::HTTP_CREATED);
			} else {
				$this->response([
					'status' => FALSE,
					'message' => "Oops Something went wrong. Please try again."
				], REST_Controller::HTTP_BAD_REQUEST);
			}
		}
		// $this->response([
		// 	'status' => TRUE,
		// 	'data' => ['data' => $password]
		// ]);
	}

	public function index_patch($id)
	{
		// Update an existing user by ID
		$data = $this->patch();
		$updated = $this->user_model->update_user($id, $data);
		if ($updated) {
			$this->response([
				'status' => TRUE,
				'message' => 'User updated successfully'
			], REST_Controller::HTTP_OK);
		} else {
			$this->response([
				'status' => FALSE,
				'message' => 'Oops Something went wrong. Please try again.'
			], REST_Controller::HTTP_NOT_FOUND);
		}
	}

	public function index_delete($id)
	{
		// Delete an existing user by ID
		$deleted = $this->user_model->delete_user($id);
		if ($deleted) {
			$this->response([
				'status' => TRUE,
				'message' => 'User deleted successfully'
			], REST_Controller::HTTP_OK);
		} else {
			$this->response([
				'status' => FALSE,
				'message' => 'Failed to delete user'
			], REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
		}
	}
}
