<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreSmsTemplateRequest;
use App\Http\Requests\TestSendSmsTemplateRequest;
use App\Http\Requests\UpdateSmsTemplateRequest;
use App\Models\SmsProfile;
use App\Models\SmsSender;
use App\Models\SmsTemplate;
use App\Services\Sms\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class SmsTemplateController extends Controller
{
    public function index(Request $request)
    {
        $templates = SmsTemplate::query()
            ->with(['defaultProfile:id,name', 'defaultSender:id,sname'])
            ->orderBy('name')
            ->get(['id', 'uuid', 'name', 'slug', 'content', 'variables_json', 'is_active', 'default_profile_id', 'default_sender_id', 'created_at']);

        $profiles = SmsProfile::query()->orderBy('name')->get(['id', 'name']);
        $senders = SmsSender::query()->orderBy('sname')->get(['id', 'profile_id', 'sname', 'active']);

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json([
                'templates' => $templates,
                'profiles' => $profiles,
                'senders' => $senders,
            ]);
        }

        return Inertia::render('Admin/SmsTemplates/Index', [
            'initialTemplates' => $templates,
            'profiles' => $profiles,
            'senders' => $senders,
        ]);
    }

    public function create()
    {
        $profiles = SmsProfile::query()->orderBy('name')->get(['id', 'name']);
        $senders = SmsSender::query()->orderBy('sname')->get(['id', 'profile_id', 'sname', 'active']);
        $actions = \App\Models\Action::query()
            ->with(['decisions:id,name'])
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/SmsTemplates/Edit', [
            'template' => null,
            'profiles' => $profiles,
            'senders' => $senders,
            'actions' => $actions,
        ]);
    }

    public function edit(SmsTemplate $smsTemplate)
    {
        $profiles = SmsProfile::query()->orderBy('name')->get(['id', 'name']);
        $senders = SmsSender::query()->orderBy('sname')->get(['id', 'profile_id', 'sname', 'active']);
        $actions = \App\Models\Action::query()
            ->with(['decisions:id,name'])
            ->orderBy('name')
            ->get(['id', 'name']);

        return Inertia::render('Admin/SmsTemplates/Edit', [
            'template' => $smsTemplate->only(['id', 'uuid', 'name', 'slug', 'content', 'variables_json', 'is_active', 'default_profile_id', 'default_sender_id', 'allow_custom_body', 'action_id', 'decision_id']),
            'profiles' => $profiles,
            'senders' => $senders,
            'actions' => $actions,
        ]);
    }

    public function store(StoreSmsTemplateRequest $request)
    {
        $data = $request->validated();
        $tpl = new SmsTemplate;
        $tpl->uuid = (string) Str::uuid();
        $tpl->name = $data['name'];
        $tpl->slug = $data['slug'];
        $tpl->content = $data['content'] ?? '';
        $tpl->variables_json = $data['variables_json'] ?? null;
        $tpl->is_active = (bool) ($data['is_active'] ?? true);
        $tpl->default_profile_id = $data['default_profile_id'] ?? null;
        $tpl->default_sender_id = $data['default_sender_id'] ?? null;
        $tpl->allow_custom_body = (bool) ($data['allow_custom_body'] ?? false);
        $tpl->action_id = $data['action_id'] ?? null;
        $tpl->decision_id = $data['decision_id'] ?? null;
        $tpl->save();

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['template' => $tpl], 201);
        }

        return redirect()->route('admin.sms-templates.edit', $tpl);
    }

    public function update(UpdateSmsTemplateRequest $request, SmsTemplate $smsTemplate)
    {
        $data = $request->validated();
        $smsTemplate->forceFill([
            'name' => $data['name'],
            'slug' => $data['slug'],
            'content' => $data['content'] ?? '',
            'variables_json' => $data['variables_json'] ?? null,
            'is_active' => (bool) ($data['is_active'] ?? $smsTemplate->is_active),
            'default_profile_id' => $data['default_profile_id'] ?? null,
            'default_sender_id' => $data['default_sender_id'] ?? null,
            'allow_custom_body' => (bool) ($data['allow_custom_body'] ?? $smsTemplate->allow_custom_body),
            'action_id' => $data['action_id'] ?? null,
            'decision_id' => $data['decision_id'] ?? null,
        ])->save();

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['template' => $smsTemplate]);
        }

        return back()->with('success', 'SMS predloga je posodobljena.');
    }

    public function toggle(Request $request, SmsTemplate $smsTemplate)
    {
        $smsTemplate->is_active = ! $smsTemplate->is_active;
        $smsTemplate->save();

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['template' => $smsTemplate]);
        }

        return back()->with('success', 'Stanje predloge je posodobljeno.');
    }

    public function destroy(Request $request, SmsTemplate $smsTemplate)
    {
        $smsTemplate->delete();

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['deleted' => true]);
        }

        return back()->with('success', 'Predloga je izbrisana.');
    }

    public function sendTest(TestSendSmsTemplateRequest $request, SmsTemplate $smsTemplate, SmsService $sms)
    {
        $data = $request->validated();

        $profile = null;
        if (! empty($data['profile_id'])) {
            $profile = SmsProfile::query()->findOrFail($data['profile_id']);
        }
        $sender = null;
        if (! empty($data['sender_id'])) {
            $sender = SmsSender::query()->findOrFail($data['sender_id']);
        }

        $variables = (array) ($data['variables'] ?? []);

        if (! empty($data['custom_content']) && $smsTemplate->allow_custom_body) {
            // Use custom content when allowed
            if (! $profile) {
                $profile = $smsTemplate->defaultProfile;
            }
            if (! $profile) {
                throw new \InvalidArgumentException('SMS profile is required to send a message.');
            }
            $log = $sms->sendRaw(
                profile: $profile,
                to: $data['to'],
                content: (string) $data['custom_content'],
                sender: $sender,
                countryCode: $data['country_code'] ?? null,
                deliveryReport: (bool) ($data['delivery_report'] ?? false),
            );
            $log->template_id = $smsTemplate->id;
            $log->save();
        } else {
            $log = $sms->sendFromTemplate(
                template: $smsTemplate,
                to: $data['to'],
                variables: $variables,
                profile: $profile,
                sender: $sender,
                countryCode: $data['country_code'] ?? null,
                deliveryReport: (bool) ($data['delivery_report'] ?? false),
            );
        }

        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['log' => $log]);
        }

        return back()->with('success', 'Testni SMS je bil poslan.');
    }
}
