<?php

namespace App\Http\Controllers;

use App\Enums\AdType;
use App\Models\AdPlatform;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

class AdPlatformController extends Controller
{
    public function index(): Response
    {
        $platforms = AdPlatform::orderBy('ad_type')->orderBy('sort_order')->get();

        return Inertia::render('ad_platforms/Index', [
            'platforms' => $platforms,
            'adTypes' => collect(AdType::cases())->map(fn ($t) => ['value' => $t->value, 'label' => $t->label(), 'active' => $t->isActive()]),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:60'],
            'ad_type' => ['required', 'in:'.implode(',', array_column(AdType::cases(), 'value'))],
            'countries' => ['nullable', 'string', 'max:100'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);

        $data['slug'] = Str::slug($data['name']);
        $data['is_active'] = $data['is_active'] ?? true;
        $data['sort_order'] = $data['sort_order'] ?? 0;

        AdPlatform::create($data);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Platform berhasil dibuat.')]);

        return to_route('ad-platforms.index');
    }

    public function update(Request $request, AdPlatform $adPlatform): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:60'],
            'ad_type' => ['required', 'in:'.implode(',', array_column(AdType::cases(), 'value'))],
            'countries' => ['nullable', 'string', 'max:100'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);

        $data['slug'] = Str::slug($data['name']);
        $data['is_active'] = $data['is_active'] ?? true;

        $adPlatform->update($data);

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Platform berhasil diperbarui.')]);

        return to_route('ad-platforms.index');
    }

    public function destroy(AdPlatform $adPlatform): RedirectResponse
    {
        $adPlatform->delete();

        Inertia::flash('toast', ['type' => 'success', 'message' => __('Platform berhasil dihapus.')]);

        return to_route('ad-platforms.index');
    }
}
