<?php

namespace App\Controllers\Base;

use Wibiesana\Padi\Core\Controller;
use Wibiesana\Padi\Core\Request;
use App\Models\SarprasItem;
use App\Resources\SarprasItemResource;

class SarprasItemController extends Controller
{
    protected SarprasItem $model;
    
    public function __construct(?Request $request = null)
    {
        parent::__construct($request);
        $this->model = new SarprasItem();
    }
    
    /**
     * Get all sarprasitems with pagination
     * GET /sarprasitems
     */
    public function index()
    {
        $page = max(1, (int)$this->request->query('page', 1)); // Min page 1
        $perPage = min(100, max(1, (int)$this->request->query('per-page', 25))); // Max 100 per page
        $search = $this->request->query('search');
        
        // Handle Sorting
        $sortBy = $this->request->query('sort_by');
        $order = $this->request->query('order', 'asc');
        $orderBy = null;

        if ($sortBy) {
            $direction = strtolower($order) === 'desc' ? 'DESC' : 'ASC';
            $orderBy = "{$sortBy} {$direction}";
        }

        if ($search) {
            // Limit search query length to prevent abuse
            $search = substr($search, 0, 255);
            $result = $this->model->searchPaginate($search, $page, $perPage, $orderBy);
        } else {
            $result = $this->model->paginate($page, $perPage, [], $orderBy);
        }

        return SarprasItemResource::collection($result);
    }
    
    /**
     * Get all sarprasitems without pagination
     * GET /sarprasitems/all
     */
    public function all()
    {
        $search = $this->request->query('search');

        // Handle Sorting
        $sortBy = $this->request->query('sort_by');
        $order = $this->request->query('order', 'asc');
        $orderBy = null;

        if ($sortBy) {
            $direction = strtolower($order) === 'desc' ? 'DESC' : 'ASC';
            $orderBy = "{$sortBy} {$direction}";
        }

        if ($search) {
             return SarprasItemResource::collection($this->model->search($search, $orderBy));
        }
        return SarprasItemResource::collection($this->model->all(['*'], $orderBy));
    }
    
    /**
     * Get single sarprasitem
     * GET /sarprasitems/{id}
     */
    public function show()
    {
        $id = $this->request->param('id');
        $sarprasitem = $this->model->find($id);
        
        if (!$sarprasitem) {
            throw new \Exception('SarprasItem not found', 404);
        }
        
        return SarprasItemResource::make($sarprasitem);
    }
    
    /**
     * Create new sarprasitem
     * POST /sarprasitems
     */
    public function store()
    {
        $validated = $this->validate([
            'kode_barang' => 'required|string|max:50|unique:sarpras_items,kode_barang',
            'nama_barang' => 'required|string|max:100',
            'kategori' => 'required|string|max:50',
            'spesifikasi' => 'string',
            'kondisi' => 'string|max:50',
            'status' => 'string|max:20',
            'lokasi_ruang' => 'string|max:100',
            'lokasi_rak' => 'string|max:100',
            'stok_total' => 'integer',
            'stok_tersedia' => 'integer',
            'gambar' => 'string|max:255',
            'qr_code_string' => 'string|max:255',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $id = $this->model->create($validated);
            // Auto-generated eager loading
            
            $sarprasitem = $this->model->find($id);
            return $this->created(SarprasItemResource::make($sarprasitem));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create sarprasitem', $e);
        }
    }
    
    /**
     * Update sarprasitem
     * PUT /sarprasitems/{id}
     */
    public function update()
    {
        $id = $this->request->param('id');
        $sarprasitem = $this->model->find($id);
        
        if (!$sarprasitem) {
            throw new \Exception('SarprasItem not found', 404);
        }
        
        $validated = $this->validate([
            'kode_barang' => 'required|string|max:50|unique:sarpras_items,kode_barang,' . $id,
            'nama_barang' => 'required|string|max:100',
            'kategori' => 'required|string|max:50',
            'spesifikasi' => 'string',
            'kondisi' => 'string|max:50',
            'status' => 'string|max:20',
            'lokasi_ruang' => 'string|max:100',
            'lokasi_rak' => 'string|max:100',
            'stok_total' => 'integer',
            'stok_tersedia' => 'integer',
            'gambar' => 'string|max:255',
            'qr_code_string' => 'string|max:255',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $this->model->update($id, $validated);
             // Auto-generated eager loading
            
            return SarprasItemResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update sarprasitem', $e);
        }
    }
    
    /**
     * Delete sarprasitem
     * DELETE /sarprasitems/{id}
     */
    public function destroy()
    {
        $id = $this->request->param('id');
        $sarprasitem = $this->model->find($id);
        
        if (!$sarprasitem) {
            throw new \Exception('SarprasItem not found', 404);
        }
        
        try {
            $this->model->delete($id);
            return $this->noContent();
        } catch (\PDOException $e) {
            $this->databaseError('Failed to delete sarprasitem', $e);
        }
    }
}