<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreVoucherRequest;
use App\Models\Account;
use App\Models\Party;
use App\Services\AccountService;
use Illuminate\Http\Request;

class AccountController extends Controller
{
    public function __construct(protected AccountService $accountService)
    {
    }

    public function index(Request $request)
    {
        $accounts = $this->accountService->getAccounts();
        $daily = $this->accountService->getDailyTransactions($request);

        return view('accounts.index', compact('accounts', 'daily'));
    }

    public function cashBook(Request $request)
    {
        $data = $this->accountService->getCashBook($request);
        return view('accounts.cash_book', $data);
    }

    public function bankBook(Request $request)
    {
        $data = $this->accountService->getBankBook($request);
        return view('accounts.bank_book', $data);
    }

    public function receiptForm()
    {
        $accounts = Account::active()->orderBy('name')->get();
        $customers = Party::customers()->active()->orderBy('name')->get();

        return view('accounts.receipt', compact('accounts', 'customers'));
    }

    public function storeReceipt(StoreVoucherRequest $request)
    {
        $voucher = $this->accountService->createReceipt($request->validated());

        return redirect()
            ->route('accounts.index')
            ->with('success', "Receipt {$voucher->voucher_no} created successfully.");
    }

    public function paymentForm()
    {
        $accounts = Account::active()->orderBy('name')->get();
        $suppliers = Party::suppliers()->active()->orderBy('name')->get();

        return view('accounts.payment', compact('accounts', 'suppliers'));
    }

    public function storePayment(StoreVoucherRequest $request)
    {
        $voucher = $this->accountService->createPayment($request->validated());

        return redirect()
            ->route('accounts.index')
            ->with('success', "Payment {$voucher->voucher_no} created successfully.");
    }
}
