<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreSmsProfileRequest;
use App\Http\Requests\TestSendSmsRequest;
use App\Jobs\SendSmsJob;
use App\Models\SmsProfile;
use App\Models\SmsSender;
use App\Services\Sms\SmsService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;

class SmsProfileController extends Controller
{
    public function index(Request $request)
    {
        $profiles = SmsProfile::query()->with(['senders:id,profile_id,sname,active'])->orderBy('name')->get([
            'id', 'uuid', 'name', 'active', 'api_username', 'default_sender_id', 'settings', 'created_at', 'updated_at',
        ]);

        // Inertia requests must receive an Inertia response
        if ($request->headers->has('X-Inertia')) {
            return Inertia::render('Admin/SmsProfiles/Index', [
                'initialProfiles' => $profiles,
            ]);
        }

        // JSON/AJAX API
        if ($request->wantsJson() || $request->expectsJson()) {
            return response()->json(['profiles' => $profiles]);
        }

        // Default to Inertia page for normal browser navigation
        return Inertia::render('Admin/SmsProfiles/Index', [
            'initialProfiles' => $profiles,
        ]);
    }

    public function store(StoreSmsProfileRequest $request)
    {
        $data = $request->validated();
        $profile = new SmsProfile;
        $profile->uuid = (string) Str::uuid();
        $profile->name = $data['name'];
        $profile->active = (bool) ($data['active'] ?? true);
        $profile->api_username = $data['api_username'];
        // write-only attribute setter will encrypt and store to encrypted_api_password
        $profile->api_password = $data['api_password'];
        $profile->save();

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

        return back()->with('success', 'SMS profil je ustvarjen.');
    }

    public function testSend(SmsProfile $profile, TestSendSmsRequest $request, SmsService $sms)
    {
        $data = $request->validated();
        $sender = null;
        if (! empty($data['sender_id'])) {
            $sender = SmsSender::query()->where('id', $data['sender_id'])->where('profile_id', $profile->id)->firstOrFail();
        }

        // Queue the SMS send (admin test send - no activity created)
        SendSmsJob::dispatch(
            profileId: $profile->id,
            to: (string) $data['to'],
            content: (string) $data['message'],
            senderId: $sender?->id,
            countryCode: $data['country_code'] ?? null,
            deliveryReport: (bool) ($data['delivery_report'] ?? false),
            clientReference: null,
        );

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

        return back()->with('success', 'Testni SMS je bil dodan v čakalno vrsto.');
    }

    public function balance(SmsProfile $smsProfile, SmsService $sms)
    {
        try {
            $balance = (string) $sms->getCreditBalance($smsProfile);

            return response()->json(['balance' => $balance]);
        } catch (\Throwable $e) {
            // Return a graceful payload so UI doesn't break; also include message for optional UI/tooling
            return response()->json([
                'balance' => '—',
                'error' => 'Unable to fetch balance: '.$e->getMessage(),
            ]);
        }
    }

    public function price(SmsProfile $smsProfile, SmsService $sms)
    {
        $quotes = $sms->getPriceQuotes($smsProfile);

        return response()->json(['quotes' => $quotes]);
    }
}
