<?php

namespace App\Http\Controllers\Api\Admin;

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

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

        $query = SchoolClass::with(['school', 'sections']);

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

        // Apply filters
        if ($request->has('school_id') && $request->school_id) {
            $query->where('school_id', $request->school_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 class
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'school_id' => 'required|exists:schools,id',
            'name' => 'required|string|max:255',
            'code' => 'required|string|unique:school_classes,code',
            'order' => 'nullable|integer',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

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

        $class = SchoolClass::create($request->all());

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

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

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

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

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

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

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

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

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

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

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

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

        $class->delete();

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