<?php

namespace App\Controllers;

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

class PatientsController extends ResourceController
{
    protected $modelName = 'App\Models\PatientModel';

    /**
     * Count the total number of patients.
     *
     * @return ResponseInterface
     */
    public function count()
    {
        $total = $this->model->countAll();
        return $this->respond(['total' => $total]);
    }

    /**
     * Return an array of resource objects, themselves in array format.
     *
     * @return ResponseInterface
     */
    public function index()
    {
        $perPage = $this->request->getVar('limit') ?? 10;
        $offset  = $this->request->getVar('offset') ?? 1;
        $search = $this->request->getVar('search') ?? '';

        $data = [];
        if($search !== '') {
            $data = $this->model->like('name', $search)
                        ->orLike('phone', $search)
                        ->orderBy('id', 'DESC')
                        ->paginate($perPage, 'default', $offset);
        } else {
            $data = $this->model->orderBy('id', 'DESC')->paginate($perPage, 'default', $offset);
        }
        
        $response = [
            'data'      => $data,
            'pager'     => $this->model->pager->getDetails()
        ];

        return $this->respond($response);
    }

    /**
     * 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 === null) {
            return $this->failNotFound("Patient not found.");
        }

        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], 'Patient 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 === null) {
            return $this->failNotFound("Patient not found.");
        }

        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.');
        }

        $data = $this->model->find($id);
        if ($data === null) {
            return $this->failNotFound("Patient not found.");
        }

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

        return $this->respondUpdated(['id' => $id], 'Patient 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("Patient not found.");
        }

        if (!$this->model->delete($id)) {
            return $this->failServerError('Failed to delete patient.');
        }

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

    public function getPatientByNameOrPhone()
    {
        $name = trim($this->request->getVar('name'));
        $phone = trim($this->request->getVar('phone'));

        if (empty($name) && empty($phone)) {
            return $this->fail('Name or phone number is required.');
        }

        $builder = $this->model;

        if (!empty($name)) {
            $builder = $builder->like('name', $name);
        }

        if (!empty($phone)) {
            if (!empty($name)) {
                $builder = $builder->orLike('phone', $phone);
            } else {
                $builder = $builder->like('phone', $phone);
            }
        }

        $patients = $builder->findAll();

        if (empty($patients)) {
            return $this->failNotFound('No patients found with the provided name or phone number.');
        }

        return $this->respond($patients);
    }
}
