<?php

namespace App\Controllers;

use App\Libraries\ValueSet;
use App\Models\ValueSet\ValueSetModel;
use App\Traits\ResponseTrait;

class ValueSetController extends \CodeIgniter\Controller
{
    use ResponseTrait;

    protected $dbModel;

    public function __construct()
    {
        $this->dbModel = new ValueSetModel();
    }

    public function index(?string $lookupName = null)
    {
        $search = $this->request->getGet('search') ?? null;
        
        if ($lookupName === null) {
            $all = ValueSet::getAll();
            $result = [];
            foreach ($all as $name => $entry) {
                if ($search) {
                    $nameLower = strtolower($name);
                    $labelLower = strtolower($entry['VSName'] ?? '');
                    $searchLower = strtolower($search);
                    if (strpos($nameLower, $searchLower) === false && strpos($labelLower, $searchLower) === false) {
                        continue;
                    }
                }
                $count = count($entry['values'] ?? []);
                $result[] = [
                    'value' => $name,
                    'label' => $entry['VSName'] ?? '',
                    'count' => $count
                ];
            }
            return $this->respond([
                'status' => 'success',
                'data' => $result
            ], 200);
        }

        $data = ValueSet::get($lookupName);
        if (!$data) {
            return $this->respond([
                'status' => 'error',
                'message' => "ValueSet '$lookupName' not found"
            ], 404);
        }

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

    public function refresh()
    {
        ValueSet::clearCache();
        return $this->respond([
            'status' => 'success',
            'message' => 'Cache cleared'
        ], 200);
    }

    public function items()
    {
        $search = $this->request->getGet('search') ?? $this->request->getGet('param') ?? null;
        $VSetID = $this->request->getGet('VSetID') ?? null;

        $rows = $this->dbModel->getValueSets($search, $VSetID);

        return $this->respond([
            'status' => 'success',
            'data' => $rows
        ], 200);
    }

    public function showItem($id = null)
    {
        $row = $this->dbModel->getValueSet($id);
        if (!$row) {
            return $this->failNotFound("ValueSet item not found: $id");
        }

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

    public function createItem()
    {
        $input = $this->request->getJSON(true);
        if (!$input) {
            return $this->failValidationErrors(['Invalid JSON input']);
        }

        $data = [
            'SiteID' => $input['SiteID'] ?? 1,
            'VSetID' => $input['VSetID'] ?? null,
            'VOrder' => $input['VOrder'] ?? 0,
            'VValue' => $input['VValue'] ?? '',
            'VDesc' => $input['VDesc'] ?? ''
        ];

        if ($data['VSetID'] === null) {
            return $this->failValidationErrors(['VSetID is required']);
        }

        try {
            $id = $this->dbModel->insert($data, true);
            if (!$id) {
                return $this->failValidationErrors($this->dbModel->errors());
            }

            $newRow = $this->dbModel->getValueSet($id);
            return $this->respondCreated([
                'status' => 'success',
                'message' => 'ValueSet item created',
                'data' => $newRow
            ]);
        } catch (\Exception $e) {
            return $this->failServerError('Failed to create: ' . $e->getMessage());
        }
    }

    public function updateItem($id = null)
    {
        $input = $this->request->getJSON(true);
        if (!$input) {
            return $this->failValidationErrors(['Invalid JSON input']);
        }

        $existing = $this->dbModel->getValueSet($id);
        if (!$existing) {
            return $this->failNotFound("ValueSet item not found: $id");
        }

        $data = [];
        if (isset($input['VSetID'])) $data['VSetID'] = $input['VSetID'];
        if (isset($input['VOrder'])) $data['VOrder'] = $input['VOrder'];
        if (isset($input['VValue'])) $data['VValue'] = $input['VValue'];
        if (isset($input['VDesc'])) $data['VDesc'] = $input['VDesc'];
        if (isset($input['SiteID'])) $data['SiteID'] = $input['SiteID'];

        if (empty($data)) {
            return $this->respond([
                'status' => 'success',
                'message' => 'No changes to update',
                'data' => $existing
            ], 200);
        }

        try {
            $updated = $this->dbModel->update($id, $data);
            if (!$updated) {
                return $this->failValidationErrors($this->dbModel->errors());
            }

            $newRow = $this->dbModel->getValueSet($id);
            return $this->respond([
                'status' => 'success',
                'message' => 'ValueSet item updated',
                'data' => $newRow
            ], 200);
        } catch (\Exception $e) {
            return $this->failServerError('Failed to update: ' . $e->getMessage());
        }
    }

    public function deleteItem($id = null)
    {
        $existing = $this->dbModel->getValueSet($id);
        if (!$existing) {
            return $this->failNotFound("ValueSet item not found: $id");
        }

        try {
            $this->dbModel->delete($id);
            return $this->respond([
                'status' => 'success',
                'message' => 'ValueSet item deleted'
            ], 200);
        } catch (\Exception $e) {
            return $this->failServerError('Failed to delete: ' . $e->getMessage());
        }
    }
}
