<?php

namespace App\Http\Controllers;

use App\Models\AdsPlacement;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdsPlacementController extends Controller
{
    public function index(Request $request): Response
    {
        $placements = AdsPlacement::query()
            ->when($request->string('search')->toString(), fn ($q, $search) => $q
                ->where('kode', 'like', "%{$search}%")
                ->orWhere('keterangan', 'like', "%{$search}%"))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return Inertia::render('placements/Index', [
            'placements' => $placements,
            'filters' => $request->only(['search']),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('placements/Create');
    }

    public function edit(AdsPlacement $placement): Response
    {
        return Inertia::render('placements/Edit', [
            'placement' => $placement,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'kode' => ['required', 'string', 'max:20', 'unique:ads_placements,kode'],
            'keterangan' => ['nullable', 'string', 'max:255'],
            'url' => ['nullable', 'string', 'max:500'],
        ]);

        AdsPlacement::create($data);

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

        return to_route('placements.index');
    }

    public function update(Request $request, AdsPlacement $placement): RedirectResponse
    {
        $data = $request->validate([
            'kode' => ['required', 'string', 'max:20', 'unique:ads_placements,kode,'.$placement->id],
            'keterangan' => ['nullable', 'string', 'max:255'],
            'url' => ['nullable', 'string', 'max:500'],
        ]);

        $placement->update($data);

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

        return to_route('placements.index');
    }

    public function destroy(AdsPlacement $placement): RedirectResponse
    {
        if ($placement->id === AdsPlacement::DEFAULT_ID) {
            Inertia::flash('toast', ['type' => 'error', 'message' => __('Placement default tidak dapat dihapus.')]);

            return to_route('placements.index');
        }

        $placement->delete();

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

        return to_route('placements.index');
    }
}
