<?php

namespace App\Http\Controllers\Api\V1\Expense;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Expense\CashTransactionRequest;
use App\Http\Requests\Api\V1\Expense\CloseCashRegisterRequest;
use App\Http\Requests\Api\V1\Expense\OpenCashRegisterRequest;
use App\Services\CashRegisterService;
use App\Services\ResponseService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CashRegisterController extends Controller
{
    public function __construct(
        private CashRegisterService $cashRegisterService,
        private ResponseService $responseService
    ) {}

    public function index(Request $request): JsonResponse
    {
        $filters = $request->only(['branch_id', 'user_id', 'status', 'start_date', 'end_date']);
        $registers = $this->cashRegisterService->getAllRegisters($filters);
        return $this->responseService->success($registers, 'Cash registers retrieved successfully');
    }

    public function show(int $id): JsonResponse
    {
        $register = $this->cashRegisterService->getRegisterById($id);

        if (!$register) {
            return $this->responseService->error('Cash register not found', 404);
        }

        return $this->responseService->success($register, 'Cash register retrieved successfully');
    }

    public function open(OpenCashRegisterRequest $request, int $branchId): JsonResponse
    {
        $result = $this->cashRegisterService->openRegister(
            $branchId,
            auth()->id(),
            $request->input('opening_balance'),
            $request->input('date')
        );

        if (isset($result['error'])) {
            return $this->responseService->error($result['error'], 400);
        }

        return $this->responseService->success($result, 'Cash register opened successfully', 201);
    }

    public function close(CloseCashRegisterRequest $request, int $id): JsonResponse
    {
        $result = $this->cashRegisterService->closeRegister(
            $id,
            $request->input('actual_balance'),
            $request->input('notes')
        );

        if (isset($result['error'])) {
            return $this->responseService->error($result['error'], 400);
        }

        return $this->responseService->success($result, 'Cash register closed successfully');
    }

    public function addCash(CashTransactionRequest $request, int $id): JsonResponse
    {
        $result = $this->cashRegisterService->recordSimpleTransaction(
            $id,
            'cash_in',
            $request->input('amount'),
            $request->input('notes')
        );

        if (!$result || isset($result['error'])) {
            return $this->responseService->error($result['error'] ?? 'Failed to add cash', 400);
        }

        return $this->responseService->success($result, 'Cash added successfully');
    }

    public function removeCash(CashTransactionRequest $request, int $id): JsonResponse
    {
        $result = $this->cashRegisterService->recordSimpleTransaction(
            $id,
            'cash_out',
            $request->input('amount'),
            $request->input('notes')
        );

        if (!$result || isset($result['error'])) {
            return $this->responseService->error($result['error'] ?? 'Failed to remove cash', 400);
        }

        return $this->responseService->success($result, 'Cash removed successfully');
    }

    public function transactions(int $id): JsonResponse
    {
        $register = $this->cashRegisterService->getRegisterById($id);

        if (!$register) {
            return $this->responseService->error('Cash register not found', 404);
        }

        return $this->responseService->success($register->transactions, 'Cash register transactions retrieved successfully');
    }

    public function currentByBranch(int $branchId): JsonResponse
    {
        $register = $this->cashRegisterService->getCurrentOpenRegister($branchId);

        if (!$register) {
            return $this->responseService->error('No open cash register found for this branch', 404);
        }

        // Ensure expected_balance is calculated fresh
        $register->refresh();
        $register->updateExpectedBalance();
        $register->refresh();

        return $this->responseService->success($register, 'Current cash register retrieved successfully');
    }

    public function summary(int $id): JsonResponse
    {
        $summary = $this->cashRegisterService->getRegisterSummary($id);

        if (!$summary) {
            return $this->responseService->error('Cash register not found', 404);
        }

        return $this->responseService->success($summary, 'Cash register summary retrieved successfully');
    }
}
