<?php

namespace App\Controllers\Base;

use Wibiesana\Padi\Core\Controller;
use Wibiesana\Padi\Core\Request;
use App\Models\IndustrialVisit;
use App\Resources\IndustrialVisitResource;

class IndustrialVisitController extends Controller
{
    protected IndustrialVisit $model;
    
    public function __construct(?Request $request = null)
    {
        parent::__construct($request);
        $this->model = new IndustrialVisit();
    }
    
    /**
     * Get all industrialvisits with pagination
     * GET /industrialvisits
     */
    public function index()
    {
        // Auto-generated eager loading
        $this->model->with(['company:id,name', 'teacherInCharge:id,name']);

        $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 IndustrialVisitResource::collection($result);
    }
    
    /**
     * Get all industrialvisits without pagination
     * GET /industrialvisits/all
     */
    public function all()
    {
        // Auto-generated eager loading
        $this->model->with(['company:id,name', 'teacherInCharge:id,name']);

        $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 IndustrialVisitResource::collection($this->model->search($search, $orderBy));
        }
        return IndustrialVisitResource::collection($this->model->all(['*'], $orderBy));
    }
    
    /**
     * Get single industrialvisit
     * GET /industrialvisits/{id}
     */
    public function show()
    {
        $id = $this->request->param('id');
        // Auto-generated eager loading
        $this->model->with(['company:id,name', 'teacherInCharge:id,name']);

        $industrialvisit = $this->model->find($id);
        
        if (!$industrialvisit) {
            throw new \Exception('IndustrialVisit not found', 404);
        }
        
        return IndustrialVisitResource::make($industrialvisit);
    }
    
    /**
     * Create new industrialvisit
     * POST /industrialvisits
     */
    public function store()
    {
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'teacher_in_charge_id' => 'integer',
            'class_name' => 'required|string|max:50',
            'visit_date' => 'required',
            'documentation_path' => 'string|max:255',
            'notes' => 'string',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $id = $this->model->create($validated);
            // Auto-generated eager loading
            
        // Auto-generated eager loading
        $this->model->with(['company:id,name', 'teacherInCharge:id,name']);

            $industrialvisit = $this->model->find($id);
            return $this->created(IndustrialVisitResource::make($industrialvisit));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to create industrialvisit', $e);
        }
    }
    
    /**
     * Update industrialvisit
     * PUT /industrialvisits/{id}
     */
    public function update()
    {
        $id = $this->request->param('id');
        $industrialvisit = $this->model->find($id);
        
        if (!$industrialvisit) {
            throw new \Exception('IndustrialVisit not found', 404);
        }
        
        $validated = $this->validate([
            'company_id' => 'required|integer',
            'teacher_in_charge_id' => 'integer',
            'class_name' => 'required|string|max:50',
            'visit_date' => 'required',
            'documentation_path' => 'string|max:255',
            'notes' => 'string',
            'created_by' => 'integer',
            'updated_by' => 'integer'
        ]);
        
        try {
            $this->model->update($id, $validated);
             // Auto-generated eager loading
            
        // Auto-generated eager loading
        $this->model->with(['company:id,name', 'teacherInCharge:id,name']);

            return IndustrialVisitResource::make($this->model->find($id));
        } catch (\PDOException $e) {
            $this->databaseError('Failed to update industrialvisit', $e);
        }
    }
    
    /**
     * Delete industrialvisit
     * DELETE /industrialvisits/{id}
     */
    public function destroy()
    {
        $id = $this->request->param('id');
        $industrialvisit = $this->model->find($id);
        
        if (!$industrialvisit) {
            throw new \Exception('IndustrialVisit not found', 404);
        }
        
        try {
            $this->model->delete($id);
            return $this->noContent();
        } catch (\PDOException $e) {
            $this->databaseError('Failed to delete industrialvisit', $e);
        }
    }
}