<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Models\Section;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SectionController extends ApiController
{
    /**
     * Display a listing of sections with pagination and search
     */
    public function index(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $search = $request->get('search');
        $sortBy = $request->get('sort_by', 'name');
        $sortOrder = $request->get('sort_order', 'asc');

        $query = Section::with(['class', 'classTeacher']);

        // Apply search
        if ($search) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%");
            });
        }

        // Apply filters
        if ($request->has('class_id') && $request->class_id) {
            $query->where('class_id', $request->class_id);
        }

        if ($request->has('is_active')) {
            $query->where('is_active', $request->boolean('is_active'));
        }

        // Apply sorting
        $query = $this->applySorting($query, $sortBy, $sortOrder);

        return $this->paginatedResponse($query, $perPage);
    }

    /**
     * Store a newly created section
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:school_classes,id',
            'name' => 'required|string|max:255',
            'code' => 'required|string',
            'capacity' => 'nullable|integer',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $section = Section::create($request->all());

        return $this->successResponse(
            $section->load('class'),
            'Section created successfully',
            201
        );
    }

    /**
     * Display the specified section
     */
    public function show($id)
    {
        $section = Section::with(['class', 'classTeacher', 'students'])->find($id);

        if (!$section) {
            return $this->errorResponse('Section not found', 404);
        }

        return $this->successResponse($section);
    }

    /**
     * Update the specified section
     */
    public function update(Request $request, $id)
    {
        $section = Section::find($id);

        if (!$section) {
            return $this->errorResponse('Section not found', 404);
        }

        $validator = Validator::make($request->all(), [
            'class_id' => 'sometimes|exists:school_classes,id',
            'name' => 'sometimes|string|max:255',
            'code' => 'sometimes|string',
            'capacity' => 'nullable|integer',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $section->update($request->all());

        return $this->successResponse(
            $section->load('class'),
            'Section updated successfully'
        );
    }

    /**
     * Remove the specified section
     */
    public function destroy($id)
    {
        $section = Section::find($id);

        if (!$section) {
            return $this->errorResponse('Section not found', 404);
        }

        $section->delete();

        return $this->successResponse(null, 'Section deleted successfully');
    }
}
