<?php

namespace App\Http\Controllers;

use App\Models\DailyClosing;
use App\Services\CashDrawerService;
use Illuminate\Http\Request;

class CashDrawerController extends Controller
{
    public function __construct(protected CashDrawerService $service)
    {
        $this->middleware('permission:cash.view')->only(['index', 'closings']);
        $this->middleware('permission:cash.manage')->only(['open', 'expense', 'cashMove']);
        $this->middleware('permission:cash.close')->only(['close']);
        $this->middleware('permission:expenses.create')->only(['expense']);
    }

    public function index()
    {
        $summary = $this->service->summary();
        $drawer = $this->service->current();
        $transactions = $drawer?->transactions()->with('user')->latest()->paginate(30);

        return view('cash.index', compact('summary', 'drawer', 'transactions'));
    }

    public function open(Request $request)
    {
        $data = $request->validate([
            'opening_balance' => ['required', 'numeric', 'min:0'],
        ]);
        $this->service->open($request->user(), (string) $data['opening_balance']);

        return back()->with('success', __('messages.drawer_opened'));
    }

    public function close(Request $request)
    {
        $data = $request->validate([
            'actual_cash' => ['required', 'numeric', 'min:0'],
            'notes' => ['nullable', 'string'],
        ]);
        $this->service->close($request->user(), (string) $data['actual_cash'], $data['notes'] ?? null);

        return back()->with('success', __('messages.drawer_closed'));
    }

    public function expense(Request $request)
    {
        $data = $request->validate([
            'amount' => ['required', 'numeric', 'min:0.01'],
            'description' => ['required', 'string', 'max:255'],
            'category' => ['nullable', 'string', 'max:100'],
            'payment_method' => ['required', 'in:cash,visa,bank,wallet,other'],
        ]);
        $this->service->addExpense($data, $request->user());

        return back()->with('success', __('messages.created'));
    }

    public function cashMove(Request $request)
    {
        $data = $request->validate([
            'type' => ['required', 'in:cash_in,cash_out'],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'description' => ['required', 'string', 'max:255'],
        ]);
        $this->service->record(
            \App\Enums\CashTransactionType::from($data['type']),
            (string) $data['amount'],
            \App\Enums\PaymentMethod::Cash,
            $request->user(),
            null,
            $data['description']
        );

        return back()->with('success', __('messages.created'));
    }

    public function closings()
    {
        $closings = DailyClosing::query()->with(['cashDrawer', 'closedByUser'])->latest('closing_date')->paginate(20);

        return view('cash.closings', compact('closings'));
    }
}
