<?php

namespace App\Http\Controllers\Company\Accounting;

use App\Http\Controllers\Controller;
use App\Models\ChequeBook;
use App\Models\Setting;
use App\Services\ChequeBookService;
use Illuminate\Http\Request;

class VoucherChequeBookController extends Controller
{
    public function __construct(
        private readonly ChequeBookService $chequeBooks,
    ) {
    }

    private function companyId(): int
    {
        return auth()->user()->company_id;
    }

    private function gate(): void
    {
        if (!auth()->user()->hasPermission('vouchers', 'view')
            && !auth()->user()->hasPermission('vouchers', 'create')) {
            abort(403);
        }
    }

    private function requireChequeRegister(): void
    {
        if (Setting::get($this->companyId(), 'use_cheque_register', '0') !== '1') {
            abort(404);
        }
    }

    public function forAccount(int $account)
    {
        $this->gate();
        $this->requireChequeRegister();

        $companyId = $this->companyId();
        if (!$this->chequeBooks->isBankAccount($companyId, $account)) {
            return response()->json(['books' => []]);
        }

        $books = $this->chequeBooks->booksForAccount($companyId, $account)->map(fn (ChequeBook $book) => [
            'id' => $book->id,
            'label' => trim("Book {$book->book_no} ({$book->leaf_start}–{$book->leaf_end})"),
            'book_no' => $book->book_no,
            'bank' => $book->bank,
            'branch' => $book->branch,
            'leaf_start' => $book->leaf_start,
            'leaf_end' => $book->leaf_end,
            'total_leaves' => $book->total_leaves,
        ]);

        return response()->json(['books' => $books->values()]);
    }

    public function leaves(Request $request, ChequeBook $chequeBook)
    {
        $this->gate();
        $this->requireChequeRegister();

        $companyId = $this->companyId();
        if ($chequeBook->company_id !== $companyId) {
            abort(403);
        }

        $excludeVoucherId = $request->integer('voucher_id') ?: null;
        $leaves = $this->chequeBooks->availableLeafNumbers($companyId, $chequeBook, $excludeVoucherId);

        return response()->json([
            'leaves' => array_map(fn ($leaf) => [
                'value' => (string) $leaf,
                'label' => (string) $leaf,
            ], $leaves),
        ]);
    }
}
