<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\School;
use Illuminate\Http\Request;

class SchoolController extends Controller
{
    public function index(Request $request)
    {
        $filters = [
            'name' => trim((string)$request->get('name','')),
            'code' => trim((string)$request->get('code','')),
            'city' => trim((string)$request->get('city','')),
        ];

        $q = \App\Models\School::query()
            ->withCount(['students as students_count' => function ($qq) {
                $qq->where('role', '!=', 'admin');
            }])
            ->orderByDesc('created_at');

        if ($filters['name'] !== '') {
            $needle = '%'.mb_strtolower($filters['name']).'%';
            $q->whereRaw('LOWER(name) LIKE ?', [$needle]);
        }
        if ($filters['code'] !== '') {
            $needle = '%'.mb_strtolower($filters['code']).'%';
            $q->whereRaw('LOWER(code) LIKE ?', [$needle]);
        }
        if ($filters['city'] !== '') {
            $needle = '%'.mb_strtolower($filters['city']).'%';
            $q->whereRaw('LOWER(city) LIKE ?', [$needle]);
        }

        $schools = $q->paginate(20)->appends($filters);

        return view('admin.schools.index', compact('schools','filters'));
    }


    // For Edit modal (JSON)
    public function show(School $school)
    {
        return response()->json([
            'id'        => $school->id,
            'name'      => $school->name,
            'short_name'=> $school->short_name,
            'code'      => $school->code,
            'city'      => $school->city,
            'country'   => $school->country,
            'is_active' => (bool)$school->is_active,
        ]);
    }

    public function store(Request $request)
    {
        $data = $this->validated($request);
        School::create($data);
        return back()->with('status', __('app.admin.schools.flash.created'));
    }

    public function update(Request $request, School $school)
    {
        $data = $this->validated($request, $school);
        $school->update($data);
        return back()->with('status', __('app.admin.schools.flash.updated'));
    }

    public function destroy(School $school)
    {
        $school->delete(); // users.school_id will be set null (FK nullOnDelete)
        return back()->with('status', __('app.admin.schools.flash.deleted'));
    }

    private function validated(Request $request, ?School $school=null): array
    {
        $id = $school?->id ?? 'NULL';
        return $request->validate([
            'name'       => ['required','string','max:255',"unique:schools,name,{$id}"],
            'short_name' => ['nullable','string','max:255'],
            'code'       => ['nullable','string','max:32',"unique:schools,code,{$id}"],
            'city'       => ['nullable','string','max:255'],
            'country'    => ['nullable','string','max:255'],
            'is_active' => ['required','boolean'], // was sometimes|boolean
        ]);
    }
}
