<?php
namespace App\Controllers;

use App\Traits\PatchValidationTrait;
use App\Traits\ResponseTrait;
use App\Controllers\BaseController;
use App\Models\Location\LocationModel;

class LocationController extends BaseController {
    use ResponseTrait;
    use PatchValidationTrait;

    protected $model;
    protected $rules;
    protected $patchRules;

    public function __construct() {
        $this->model = new LocationModel();
        $this->rules = [
            'LocCode' => 'required|max_length[6]',
            'LocFull' => 'required',
        ];
        $this->patchRules = [
            'SiteID' => 'permit_empty|is_natural_no_zero',
            'LocCode' => 'permit_empty|max_length[6]',
            'Parent' => 'permit_empty|is_natural',
            'LocFull' => 'permit_empty',
            'Description' => 'permit_empty|max_length[255]',
            'LocType' => 'permit_empty',
            'Street1' => 'permit_empty|max_length[255]',
            'Street2' => 'permit_empty|max_length[255]',
            'City' => 'permit_empty|max_length[255]',
            'Province' => 'permit_empty|max_length[255]',
            'PostCode' => 'permit_empty|max_length[20]',
            'GeoLocationSystem' => 'permit_empty|max_length[255]',
            'GeoLocationData' => 'permit_empty|max_length[255]',
            'Phone' => 'permit_empty|max_length[20]',
            'Email' => 'permit_empty|valid_email|max_length[255]',
        ];
    }

    public function index() {
        $LocName = $this->request->getVar('LocName');
        $LocCode = $this->request->getVar('LocCode');
        $rows = $this->model->getLocations($LocCode,$LocName);
        if (empty($rows)) {
            return $this->respond([ 'status'  => 'success', 'message' => "no Data.", 'data' => [] ], 200);
        }

        return $this->respond([ 'status' => 'success', 'message'=> "fetch success", 'data' => $rows ], 200);
    }
        
    public function show($LocationID = null) {
        $row = $this->model->getLocation($LocationID);
        if (empty($row)) {
            return $this->respond([ 'status'  => 'success', 'message' => "no Data.", 'data' => null ], 200);
        }

        return $this->respond([ 'status' => 'success', 'message'=> "fetch success", 'data' => $row ], 200);
    }

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

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

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

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

        $validationInput = array_intersect_key($input, $this->patchRules);
        if ($validationInput === []) {
            return $this->respond([
                'status' => 'failed',
                'message' => 'No valid fields provided for update.',
                'data' => []
            ], 422);
        }

        if (!$this->validateData($validationInput, $this->patchRules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $input['LocationID'] = $id;
        try {
            $result = $this->model->saveLocation($input);
            return $this->respond([ 'status'  => 'success', 'message' => 'data updated successfully', 'data' => $result ], 200);
        } catch (\Throwable $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

    public function delete() {
        $input = $this->request->getJSON(true);
        try {
            $LocationID = $input["LocationID"];
            $this->model->deleteLocation($LocationID);
            return $this->respondDeleted([ 'status' => 'success', 'message' => "Location with {$LocationID} deleted successfully." ]);
        } catch (\Throwable $e) {
            return $this->failServerError('Something went wrong: ' . $e->getMessage());
        }
    }

}
