<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Finance\CloseCashSessionRequest;
use App\Http\Requests\Finance\OpenCashSessionRequest;
use App\Models\Branch;
use App\Models\CashSession;
use App\Services\TenantFinanceService;
use Illuminate\Http\Request;

class CashSessionController extends Controller
{
    public function __construct(private readonly TenantFinanceService $finance) {}

    public function index(Request $request)
    {
        $tenantId = $request->user()->tenant_id;
        $sessions = CashSession::query()
            ->where('tenant_id', $tenantId)
            ->with('cashier')
            ->latest('opening_time')
            ->paginate(25);
        $branches = Branch::where('tenant_id', $tenantId)->where('status', 'active')->orderBy('name')->get();
        $openSession = CashSession::query()
            ->where('tenant_id', $tenantId)
            ->where('cashier_user_id', $request->user()->id)
            ->where('status', 'open')
            ->first();

        return view('tenant.billing.cash_sessions.index', compact('sessions', 'branches', 'openSession'));
    }

    public function open(OpenCashSessionRequest $request)
    {
        $branch = Branch::where('tenant_id', $request->user()->tenant_id)->findOrFail($request->integer('branch_id'));
        $this->finance->openCashSession(
            $request->user()->tenant,
            $branch,
            $request->user(),
            $request->validated('opening_cash'),
            $request->integer('counter_id') ?: null
        );

        return back()->with('status', 'Cash drawer opened. Collections are now tracked for this shift.');
    }

    public function close(CloseCashSessionRequest $request, int $id)
    {
        $session = CashSession::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->findOrFail($id);
        $this->finance->closeCashSession(
            $request->user()->tenant,
            $session,
            $request->user(),
            $request->validated('actual_cash'),
            $request->validated('cash_out') ?? '0.00',
            $request->validated('variance_explanation')
        );

        return back()->with('status', 'Cash session closed and variance recorded.');
    }
}
