<?php

namespace App\Http\Controllers;

use App\Http\Requests\MasterBankAccountRequest;
use App\Models\MasterBankAccount;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MasterBankAccountController extends Controller
{
    public function index(Request $request): View
    {
        $query = MasterBankAccount::query();
        $search = $request->query('q');

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('bank_name', 'like', '%' . $search . '%')
                    ->orWhere('account_name', 'like', '%' . $search . '%')
                    ->orWhere('account_number', 'like', '%' . $search . '%');
            });
        }

        $banks = $query->orderByDesc('id')->paginate(10)->withQueryString();

        return view('master.banks.index', compact('banks', 'search'));
    }

    public function create(): View
    {
        return view('master.banks.create');
    }

    public function store(MasterBankAccountRequest $request): RedirectResponse
    {
        MasterBankAccount::create($request->validated());

        return redirect()->route('banks.index')->with('success', 'Akun bank berhasil ditambahkan.');
    }

    public function edit(MasterBankAccount $bank): View
    {
        return view('master.banks.edit', compact('bank'));
    }

    public function update(MasterBankAccountRequest $request, MasterBankAccount $bank): RedirectResponse
    {
        $bank->update($request->validated());

        return redirect()->route('banks.index')->with('success', 'Akun bank berhasil diperbarui.');
    }

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

        return redirect()->route('banks.index')->with('success', 'Akun bank berhasil dihapus.');
    }
}
