<?php

namespace App\Controllers\Base;

use Wibiesana\Padi\Core\Controller;
use Wibiesana\Padi\Core\Request;
use App\Models\SarprasPeminjam;
use App\Resources\SarprasPeminjamResource;

class SarprasPeminjamController extends Controller
{
    protected SarprasPeminjam $model;
    
    public function __construct(?Request $request = null)
    {
        parent::__construct($request);
        $this->model = new SarprasPeminjam();
    }
    
    /**
     * Get all sarpraspeminjams with pagination
     * GET /sarpraspeminjams
     */
    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 SarprasPeminjamResource::collection($result);
    }
    
    /**
     * Get all sarpraspeminjams without pagination
     * GET /sarpraspeminjams/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 SarprasPeminjamResource::collection($this->model->search($search, $orderBy));
        }
        return SarprasPeminjamResource::collection($this->model->all(['*'], $orderBy));
    }
    
    /**
     * Get single sarpraspeminjam
     * GET /sarpraspeminjams/{id}
     */
    public function show()
    {
        $id = $this->request->param('id');
        $sarpraspeminjam = $this->model->find($id);
        
        if (!$sarpraspeminjam) {
            throw new \Exception('SarprasPeminjam not found', 404);
        }
        
        return SarprasPeminjamResource::make($sarpraspeminjam);
    }
    
    /**
     * Create new sarpraspeminjam
     * POST /sarpraspeminjams
     */
    public function store()
    {
        $validated = $this->validate([
            'tipe_peminjam' => 'required|string|max:20',
            'id_identitas' => 'required|string|max:50|unique:sarpras_peminjam,id_identitas',
            'nama_lengkap' => 'required|string|max:100',
            'kelas' => 'string|max:50',
            'jurusan' => 'string|max:100',
            'nomor_telepon' => 'string|max:25',
            'email' => 'string|max:100|email',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $id = $this->model->create($validated);
            // Auto-generated eager loading
            
            $sarpraspeminjam = $this->model->find($id);
            return $this->created(SarprasPeminjamResource::make($sarpraspeminjam));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create sarpraspeminjam', $e);
        }
    }
    
    /**
     * Update sarpraspeminjam
     * PUT /sarpraspeminjams/{id}
     */
    public function update()
    {
        $id = $this->request->param('id');
        $sarpraspeminjam = $this->model->find($id);
        
        if (!$sarpraspeminjam) {
            throw new \Exception('SarprasPeminjam not found', 404);
        }
        
        $validated = $this->validate([
            'tipe_peminjam' => 'required|string|max:20',
            'id_identitas' => 'required|string|max:50|unique:sarpras_peminjam,id_identitas,' . $id,
            'nama_lengkap' => 'required|string|max:100',
            'kelas' => 'string|max:50',
            'jurusan' => 'string|max:100',
            'nomor_telepon' => 'string|max:25',
            'email' => 'string|max:100|email',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $this->model->update($id, $validated);
             // Auto-generated eager loading
            
            return SarprasPeminjamResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update sarpraspeminjam', $e);
        }
    }
    
    /**
     * Delete sarpraspeminjam
     * DELETE /sarpraspeminjams/{id}
     */
    public function destroy()
    {
        $id = $this->request->param('id');
        $sarpraspeminjam = $this->model->find($id);
        
        if (!$sarpraspeminjam) {
            throw new \Exception('SarprasPeminjam not found', 404);
        }
        
        try {
            $this->model->delete($id);
            return $this->noContent();
        } catch (\PDOException $e) {
            $this->databaseError('Failed to delete sarpraspeminjam', $e);
        }
    }
}