<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreSmsSenderRequest;
use App\Http\Requests\UpdateSmsSenderRequest;
use App\Models\SmsProfile;
use App\Models\SmsSender;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SmsSenderController extends Controller
{
    public function index(Request $request)
    {
        $senders = SmsSender::query()
            ->with(['profile:id,name'])
            ->orderBy('id', 'desc')
            ->get(['id', 'profile_id', 'sname', 'phone_number', 'description', 'active', 'created_at']);

        $profiles = SmsProfile::query()->orderBy('name')->get(['id', 'name']);

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

    public function store(StoreSmsSenderRequest $request)
    {
        $data = $request->validated();
        $sender = SmsSender::create([
            'profile_id' => $data['profile_id'],
            'sname' => $data['sname'],
            'phone_number' => $data['phone_number'] ?? null,
            'description' => $data['description'] ?? null,
            'active' => (bool) ($data['active'] ?? true),
        ]);

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

        return back()->with('success', 'Pošiljatelj je ustvarjen.');
    }

    public function update(UpdateSmsSenderRequest $request, SmsSender $smsSender)
    {
        $data = $request->validated();
        $smsSender->forceFill([
            'profile_id' => $data['profile_id'],
            'sname' => $data['sname'],
            'phone_number' => $data['phone_number'] ?? null,
            'description' => $data['description'] ?? null,
            'active' => (bool) ($data['active'] ?? $smsSender->active),
        ])->save();

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

        return back()->with('success', 'Pošiljatelj je posodobljen.');
    }

    public function toggle(Request $request, SmsSender $smsSender)
    {
        $smsSender->active = ! $smsSender->active;
        $smsSender->save();

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

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

    public function destroy(Request $request, SmsSender $smsSender)
    {
        $smsSender->delete();

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

        return back()->with('success', 'Pošiljatelj je izbrisan.');
    }
}
