<?php

namespace App\Http\Controllers\Api\Admin;

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

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

        $query = FeeStructure::with(['class', 'academicYear', 'feeType']);

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

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

        if ($request->has('academic_year_id') && $request->academic_year_id) {
            $query->where('academic_year_id', $request->academic_year_id);
        }

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

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

    /**
     * Store a newly created fee structure
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:school_classes,id',
            'academic_year_id' => 'required|exists:academic_years,id',
            'fee_type_id' => 'required|exists:fee_types,id',
            'amount' => 'required|numeric|min:0',
            'due_date' => 'nullable|date',
            'description' => 'nullable|string',
        ]);

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

        $feeStructure = FeeStructure::create($request->all());

        return $this->successResponse(
            $feeStructure->load(['class', 'academicYear', 'feeType']),
            'Fee structure created successfully',
            201
        );
    }

    /**
     * Display the specified fee structure
     */
    public function show($id)
    {
        $feeStructure = FeeStructure::with(['class', 'academicYear', 'feeType'])->find($id);

        if (!$feeStructure) {
            return $this->errorResponse('Fee structure not found', 404);
        }

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

    /**
     * Update the specified fee structure
     */
    public function update(Request $request, $id)
    {
        $feeStructure = FeeStructure::find($id);

        if (!$feeStructure) {
            return $this->errorResponse('Fee structure not found', 404);
        }

        $validator = Validator::make($request->all(), [
            'class_id' => 'sometimes|exists:school_classes,id',
            'academic_year_id' => 'sometimes|exists:academic_years,id',
            'fee_type_id' => 'sometimes|exists:fee_types,id',
            'amount' => 'sometimes|numeric|min:0',
            'due_date' => 'nullable|date',
            'description' => 'nullable|string',
        ]);

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

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

        return $this->successResponse(
            $feeStructure->load(['class', 'academicYear', 'feeType']),
            'Fee structure updated successfully'
        );
    }

    /**
     * Remove the specified fee structure
     */
    public function destroy($id)
    {
        $feeStructure = FeeStructure::find($id);

        if (!$feeStructure) {
            return $this->errorResponse('Fee structure not found', 404);
        }

        $feeStructure->delete();

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