<?php

namespace App\Http\Controllers\Api\Admin;

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

class SubjectController extends ApiController
{
    /**
     * Display a listing of subjects 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 = Subject::with(['school']);

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

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

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

        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 subject
     */
    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:subjects,code',
            'type' => 'nullable|in:theory,practical,both',
            'description' => 'nullable|string',
            'credit_hours' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

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

        $subject = Subject::create($request->all());

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

    /**
     * Display the specified subject
     */
    public function show($id)
    {
        $subject = Subject::with(['school', 'teachers'])->find($id);

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

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

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

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

        $validator = Validator::make($request->all(), [
            'school_id' => 'sometimes|exists:schools,id',
            'name' => 'sometimes|string|max:255',
            'code' => 'sometimes|string|unique:subjects,code,' . $id,
            'type' => 'nullable|in:theory,practical,both',
            'description' => 'nullable|string',
            'credit_hours' => 'nullable|integer',
            'is_active' => 'boolean',
        ]);

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

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

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

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

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

        $subject->delete();

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