<?php

namespace App\Http\Controllers\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class SubjectController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $subjects = $schoolId
            ? DB::table('subjects')
                ->where('school_id', $schoolId)
                ->orderBy('name')
                ->get(['id', 'name', 'code', 'weekly_hours', 'status'])
            : collect();

        return Inertia::render('School/Subjects', [
            'subjects' => $subjects->map(fn ($subject): array => [
                'id' => $subject->id,
                'name' => $subject->name,
                'code' => $subject->code ?? '',
                'weeklyHours' => $subject->weekly_hours ?? '',
                'status' => $subject->status === 'active' ? 'فعال' : 'غیرفعال',
            ])->values(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'code' => ['nullable', 'string', 'max:40'],
            'weekly_hours' => ['nullable', 'integer', 'min:1', 'max:40'],
        ]);

        if (! empty($data['code'])) {
            $exists = DB::table('subjects')
                ->where('school_id', $schoolId)
                ->where('code', $data['code'])
                ->exists();

            if ($exists) {
                return back()->withErrors(['code' => 'کد درس تکراری است.'])->withInput();
            }
        }

        DB::table('subjects')->insert([
            'school_id' => $schoolId,
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'weekly_hours' => $data['weekly_hours'] ?? null,
            'status' => 'active',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->route('school.subjects')->with('success', 'درس ثبت شد.');
    }

    public function update(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $exists = DB::table('subjects')->where('id', $id)->where('school_id', $schoolId)->exists();
        abort_unless($exists, 404, 'درس یافت نشد.');

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'code' => ['nullable', 'string', 'max:40'],
            'weekly_hours' => ['nullable', 'integer', 'min:1', 'max:40'],
        ]);

        if (! empty($data['code'])) {
            $codeConflict = DB::table('subjects')
                ->where('school_id', $schoolId)
                ->where('code', $data['code'])
                ->where('id', '!=', $id)
                ->exists();

            if ($codeConflict) {
                return back()->withErrors(['code' => 'این کد درس برای درس دیگری ثبت شده است.'])->withInput();
            }
        }

        DB::table('subjects')->where('id', $id)->update([
            'name' => $data['name'],
            'code' => $data['code'] ?? null,
            'weekly_hours' => $data['weekly_hours'] ?? null,
            'updated_at' => now(),
        ]);

        return redirect()->route('school.subjects')->with('success', 'اطلاعات درس بروز شد.');
    }

    public function destroy(Request $request, int $id): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);

        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $subject = DB::table('subjects')->where('id', $id)->where('school_id', $schoolId)->first();
        abort_unless($subject, 404, 'درس یافت نشد.');

        DB::table('subjects')->where('id', $id)->delete();

        return redirect()->route('school.subjects')->with('success', 'درس حذف شد.');
    }
}
