<?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 SettingsController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $this->currentSchoolId($request);

        $school = $schoolId
            ? DB::table('schools')->where('id', $schoolId)->first()
            : null;

        $allGrades = DB::table('grade_levels')->where('status', 'active')->orderBy('number')->get(['id', 'name_fa']);
        $enabledGradeIds = $schoolId
            ? DB::table('school_grade_levels')->where('school_id', $schoolId)->where('enabled', true)->pluck('grade_level_id')
            : collect();

        $schoolSettings = $schoolId
            ? DB::table('school_settings')->where('school_id', $schoolId)->first()
            : null;

        $requiredStudentFields = $schoolSettings && $schoolSettings->required_student_fields
            ? json_decode($schoolSettings->required_student_fields, true)
            : ['mobile', 'father_mobile', 'mother_mobile'];

        $absenceSmsMode = $schoolSettings?->absence_sms_mode ?? 'approval_required';

        return Inertia::render('School/Settings', [
            'school' => $school ? [
                'id' => (int) $school->id,
                'nameFa' => $school->name_fa,
                'nameEn' => $school->name_en ?? '',
                'schoolCode' => $school->school_code,
                'province' => $school->province ?? '',
                'city' => $school->city ?? '',
                'address' => $school->address ?? '',
                'phone' => $school->phone ?? '',
                'status' => $school->status,
            ] : null,
            'allGrades' => $allGrades->map(fn ($g) => ['id' => $g->id, 'label' => $g->name_fa])->values(),
            'enabledGradeIds' => $enabledGradeIds->values(),
            'requiredStudentFields' => $requiredStudentFields,
            'absenceSmsMode' => $absenceSmsMode,
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $schoolId = $this->currentSchoolId($request);
        abort_unless($schoolId, 422, 'مدرسه مشخص نیست.');

        $allowedStudentFields = ['mobile', 'national_code', 'father_mobile', 'mother_mobile', 'home_phone', 'address', 'birth_date', 'gender'];
        $allowedSmsModes = ['disabled', 'instant', 'approval_required'];

        $data = $request->validate([
            'name_fa' => ['required', 'string', 'max:190'],
            'name_en' => ['nullable', 'string', 'max:190'],
            'city' => ['nullable', 'string', 'max:120'],
            'province' => ['nullable', 'string', 'max:120'],
            'address' => ['nullable', 'string', 'max:1000'],
            'phone' => ['nullable', 'string', 'max:30'],
            'grade_ids' => ['nullable', 'array'],
            'grade_ids.*' => ['integer'],
            'required_student_fields' => ['nullable', 'array'],
            'required_student_fields.*' => ['string', 'in:'.implode(',', $allowedStudentFields)],
            'absence_sms_mode' => ['nullable', 'string', 'in:'.implode(',', $allowedSmsModes)],
        ]);

        DB::table('schools')->where('id', $schoolId)->update([
            'name_fa' => $data['name_fa'],
            'name_en' => $data['name_en'] ?? null,
            'city' => $data['city'] ?? null,
            'province' => $data['province'] ?? null,
            'address' => $data['address'] ?? null,
            'phone' => $data['phone'] ?? null,
            'updated_at' => now(),
        ]);

        $validGradeIds = DB::table('grade_levels')
            ->where('status', 'active')
            ->pluck('id')
            ->toArray();

        $selectedGradeIds = array_intersect((array) ($data['grade_ids'] ?? []), $validGradeIds);

        foreach ($validGradeIds as $gradeId) {
            $enabled = in_array($gradeId, $selectedGradeIds);
            $exists = DB::table('school_grade_levels')
                ->where('school_id', $schoolId)
                ->where('grade_level_id', $gradeId)
                ->exists();

            if ($exists) {
                DB::table('school_grade_levels')
                    ->where('school_id', $schoolId)
                    ->where('grade_level_id', $gradeId)
                    ->update(['enabled' => $enabled, 'updated_at' => now()]);
            } elseif ($enabled) {
                DB::table('school_grade_levels')->insert([
                    'school_id' => $schoolId,
                    'grade_level_id' => $gradeId,
                    'enabled' => true,
                    'enabled_by' => $request->user()?->id,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }

        $requiredFields = array_intersect($data['required_student_fields'] ?? [], $allowedStudentFields);
        $smsMode = $data['absence_sms_mode'] ?? 'approval_required';

        $settingsExists = DB::table('school_settings')->where('school_id', $schoolId)->exists();

        if ($settingsExists) {
            DB::table('school_settings')->where('school_id', $schoolId)->update([
                'required_student_fields' => json_encode(array_values($requiredFields), JSON_UNESCAPED_UNICODE),
                'absence_sms_mode' => $smsMode,
                'updated_at' => now(),
            ]);
        } else {
            DB::table('school_settings')->insert([
                'school_id' => $schoolId,
                'required_student_fields' => json_encode(array_values($requiredFields), JSON_UNESCAPED_UNICODE),
                'absence_sms_mode' => $smsMode,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

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