<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\Cash\DepositRequest;
use App\Http\Requests\Admin\Finance\Cash\WithdrawRequest;
use App\Http\Requests\Admin\Finance\UpdateCashTransactionRequest;
use App\Models\CashTransaction;
use App\Services\Finance\CashService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class CashController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly CashService $cashService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);
        $referenceType = $request->string('reference_type')->toString();
        $cashAccount = $this->cashService->getDefaultAccount();

        return Inertia::render('admin/finance/cash/Index', [
            'cashAccount' => $cashAccount,
            'transactions' => $this->cashService->paginateForIndex($cashAccount, $tableQuery, $referenceType),
            'filters' => $this->dataTableFilters($tableQuery, [
                'reference_type' => $referenceType,
            ]),
        ]);
    }

    public function update(UpdateCashTransactionRequest $request, CashTransaction $cashTransaction): RedirectResponse
    {
        $this->cashService->updateDeposit($cashTransaction, $request->validated());

        $this->flashUpdated('Setor kas');

        return redirect()->route('admin.finance.cash.index');
    }

    public function destroy(CashTransaction $cashTransaction): RedirectResponse
    {
        $this->cashService->deleteTransaction($cashTransaction);

        $this->flashDeleted('Setor kas');

        return redirect()->route('admin.finance.cash.index');
    }

    public function deposit(DepositRequest $request): RedirectResponse
    {
        $cashAccount = $this->cashService->getDefaultAccount();

        $this->cashService->deposit($cashAccount, $request->validated(), $request->user());

        $this->flashSuccess('Setor kas berhasil dicatat.');

        return redirect()->route('admin.finance.cash.index');
    }

    public function withdraw(WithdrawRequest $request): RedirectResponse
    {
        $cashAccount = $this->cashService->getDefaultAccount();

        $this->cashService->withdraw($cashAccount, $request->validated(), $request->user());

        $this->flashSuccess('Tarik kas berhasil dicatat.');

        return redirect()->route('admin.finance.cash.index');
    }
}
