<?php

namespace App\Http\Controllers;

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

class BankController extends Controller
{
    public function index(Request $request): Response
    {
        $banks = Bank::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('banks/Index', [
            'banks' => $banks,
            'filters' => $request->only(['search']),
        ]);
    }

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

    public function edit(Bank $bank): Response
    {
        return Inertia::render('banks/Edit', [
            'bank' => $bank,
        ]);
    }

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

        $data['status'] = $data['status'] ?? true;

        Bank::create($data);

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

        return to_route('banks.index');
    }

    public function update(Request $request, Bank $bank): RedirectResponse
    {
        $data = $request->validate([
            'kode' => ['required', 'string', 'max:20', 'unique:banks,kode,'.$bank->id],
            'keterangan' => ['required', 'string', 'max:255'],
            'status' => ['nullable', 'boolean'],
        ]);

        $data['status'] = $data['status'] ?? true;

        $bank->update($data);

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

        return to_route('banks.index');
    }

    public function destroy(Bank $bank): RedirectResponse
    {
        $bank->delete();

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

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