<?php

namespace App\Http\Controllers\Sms;

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 SmsTemplateController extends Controller
{
    public function index(Request $request): Response
    {
        $schoolId = $request->user()->school_id;

        $templates = DB::table('sms_templates')
            ->where(function ($q) use ($schoolId): void {
                $q->where('school_id', $schoolId)->orWhereNull('school_id');
            })
            ->orderBy('key_name')
            ->get()
            ->map(fn ($t): array => [
                'id' => (int) $t->id,
                'keyName' => $t->key_name,
                'title' => $t->title,
                'body' => $t->body,
                'status' => $t->status,
                'isGlobal' => $t->school_id === null,
            ])->values();

        return Inertia::render('Sms/Templates', [
            'templates' => $templates,
        ]);
    }

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

        $data = $request->validate([
            'key_name' => ['required', 'string', 'max:120', 'regex:/^[a-z0-9_]+$/'],
            'title' => ['required', 'string', 'max:190'],
            'body' => ['required', 'string', 'max:2000'],
        ]);

        $exists = DB::table('sms_templates')
            ->where('school_id', $schoolId)
            ->where('key_name', $data['key_name'])
            ->exists();

        if ($exists) {
            return back()->withErrors(['key_name' => 'این کلید در مدرسه شما وجود دارد.']);
        }

        DB::table('sms_templates')->insert([
            'school_id' => $schoolId,
            'key_name' => $data['key_name'],
            'title' => $data['title'],
            'body' => $data['body'],
            'status' => 'active',
            'created_by' => $request->user()->id,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return back()->with('success', 'template SMS ساخته شد.');
    }

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

        $template = DB::table('sms_templates')
            ->where('id', $id)
            ->where('school_id', $schoolId)
            ->first();

        abort_unless($template, 404);

        $data = $request->validate([
            'title' => ['required', 'string', 'max:190'],
            'body' => ['required', 'string', 'max:2000'],
        ]);

        DB::table('sms_templates')->where('id', $id)->update([
            'title' => $data['title'],
            'body' => $data['body'],
            'updated_at' => now(),
        ]);

        return back()->with('success', 'template SMS به‌روز شد.');
    }

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

        $deleted = DB::table('sms_templates')
            ->where('id', $id)
            ->where('school_id', $schoolId)
            ->delete();

        abort_unless($deleted, 404);

        return back()->with('success', 'template SMS حذف شد.');
    }
}
