<?php

namespace App\Controllers;

use App\Models\ValueSet\ValueSetDefModel;
use App\Traits\ResponseTrait;

class ValueSetDefController extends \CodeIgniter\Controller
{
    use ResponseTrait;

    protected $model;

    public function __construct()
    {
        $this->model = new ValueSetDefModel();
    }

    public function index()
    {
        $search = $this->request->getGet('search') ?? null;
        $limit = (int) ($this->request->getGet('limit') ?? 100);
        $page = (int) ($this->request->getGet('page') ?? 1);
        $offset = ($page - 1) * $limit;

        $rows = $this->model->getValueSetDefs($search);

        $paged = array_slice($rows, $offset, $limit);

        return $this->respond([
            'status' => 'success',
            'data' => $paged,
            'meta' => [
                'total' => count($rows),
                'page' => $page,
                'limit' => $limit
            ]
        ], 200);
    }

    public function show($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            return $this->failNotFound("ValueSet definition not found: $id");
        }

        $itemCount = $this->model->db->table('valueset')
            ->select('COUNT(*) as ItemCount')
            ->where('VSetID', $id)
            ->where('EndDate IS NULL')
            ->get()
            ->getRowArray()['ItemCount'] ?? 0;

        $row['ItemCount'] = (int) $itemCount;

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

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

        $data = [
            'SiteID' => $input['SiteID'] ?? 1,
            'VSName' => $input['VSName'] ?? '',
            'VSDesc' => $input['VSDesc'] ?? ''
        ];

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

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

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

        $existing = $this->model->find($id);
        if (!$existing) {
            return $this->failNotFound("ValueSet definition not found: $id");
        }

        $data = [];
        if (isset($input['VSName'])) $data['VSName'] = $input['VSName'];
        if (isset($input['VSDesc'])) $data['VSDesc'] = $input['VSDesc'];
        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->model->update($id, $data);
            if (!$updated) {
                return $this->failValidationErrors($this->model->errors());
            }

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

    public function delete($id = null)
    {
        $existing = $this->model->find($id);
        if (!$existing) {
            return $this->failNotFound("ValueSet definition not found: $id");
        }

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