<?php

namespace App\Controllers;

use App\Models\ModelCustomModel;
use App\Models\JenisKainModel;
use App\Models\CustomerModel;

class Api extends BaseController
{
    protected $modelModel;
    protected $fabricModel;

    public function __construct()
    {
        $this->modelModel = new ModelCustomModel();
        $this->fabricModel = new JenisKainModel();
    }

    /**
     * Get all models for grid display
     */
    public function models()
    {
        $models = $this->modelModel->findAll();
        return $this->response->setJSON($models);
    }

    /**
     * Get single model by code
     */
    public function model($kodeModel)
    {
        $model = $this->modelModel->where('kode_model', $kodeModel)->first();
        if ($model) {
            return $this->response->setJSON($model);
        }
        return $this->response->setStatusCode(404)->setJSON(['error' => 'Model not found']);
    }

    /**
     * Get all fabrics for grid display
     */
    public function fabrics()
    {
        $fabrics = $this->fabricModel->findAll();
        return $this->response->setJSON($fabrics);
    }

    /**
     * Get single fabric by code
     */
    public function fabric($kodeFabric)
    {
        $fabric = $this->fabricModel->where('kode_jenis_kain', $kodeFabric)->first();
        if ($fabric) {
            return $this->response->setJSON($fabric);
        }
        return $this->response->setStatusCode(404)->setJSON(['error' => 'Fabric not found']);
    }

    /**
     * Search customers by query (GET param `query`)
     */
    public function customers()
    {
        $query = $this->request->getGet('query');
        $customerModel = new CustomerModel();
        if ($query) {
            $results = $customerModel->like('nama', $query)->orderBy('nama', 'asc')->findAll(10);
        } else {
            $results = $customerModel->orderBy('nama', 'asc')->findAll(20);
        }
        // Return minimal fields
        $out = array_map(function ($c) {
            return ['id_customer' => $c->id_customer, 'nama' => $c->nama, 'telepon' => $c->telepon];
        }, $results);
        return $this->response->setJSON($out);
    }

    /**
     * Create a customer via AJAX (POST)
     */
    public function createCustomer()
    {
        $data = [
            'nama' => $this->request->getPost('nama'),
            'telepon' => $this->request->getPost('telepon') ?? null,
        ];
        $customerModel = new CustomerModel();
        $id = $customerModel->insert($data);
        if ($id) {
            $created = $customerModel->find($id);
            return $this->response->setJSON(['success' => true, 'customer' => $created]);
        }
        return $this->response->setStatusCode(500)->setJSON(['success' => false, 'message' => 'Gagal menyimpan customer']);
    }
}
