<?php

namespace App\Controllers\Specimen;

use App\Traits\PatchValidationTrait;
use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\Specimen\SpecimenPrepModel;

class SpecimenPrepController extends BaseController {
    use ResponseTrait;
    use PatchValidationTrait;

    protected $db;
    protected $model;
    protected $rules;

    public function __construct() {
        $this->db = \Config\Database::connect();
        $this->model = new SpecimenPrepModel();
        $this->rules = [];
    }

    public function index() {
        try {
            $rows = $this->model->findAll();
            return $this->respond([ 'status' => 'success', 'message'=> "data fetched successfully", 'data'   => $rows ], 200);
        } catch (\Exception $e) {
            return $this->failServerError('Exception : '.$e->getMessage());
        }
    }

    public function show($id) {
        try {
            $row = $this->model->where('SpcPrpID', $id)->first();
            if (empty($row)) {
                return $this->respond([ 'status' => 'success', 'message'=> "data not found", 'data' => null ], 200);
            }
            return $this->respond([ 'status' => 'success', 'message'=> "data fetched successfully", 'data'   => $row ], 200);
        } catch (\Exception $e) {
            return $this->failServerError('Exception : '.$e->getMessage());
        }
    }

    public function create() {
        $input = $this->request->getJSON(true);
        if (!$this->validateData($input, $this->rules)) { return $this->failValidationErrors($this->validator->getErrors()); }
        try {
            $id = $this->model->insert($input);
            return $this->respondCreated([ 'status'  => 'success', 'message' => "data $id created successfully" ]);
        } catch (\Exception $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

    public function update($SpcPrpID = null) {
        $input = $this->requirePatchPayload($this->request->getJSON(true));
        if ($input === null) {
            return;
        }

        $id = $this->requirePatchId($SpcPrpID, 'SpcPrpID');
        if ($id === null) {
            return;
        }

        $existing = $this->model->where('SpcPrpID', $id)->first();
        if (!$existing) {
            return $this->respond([ 'status' => 'failed', 'message' => 'Specimen prep not found', 'data' => [] ], 404);
        }

        $input['SpcPrpID'] = $id;
        if ($this->rules !== [] && !$this->validateData($input, $this->rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }
        try {
            $this->model->update($id, $input);
            return $this->respondCreated([ 'status'  => 'success', 'message' => 'data updated successfully', 'data' => $id ], 201);
        } catch (\Exception $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

}
