<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\CashMovement;
use App\Support\Tenant;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CashMovementController extends Controller
{
    public function index(Request $request): View
    {
        $from = $request->date('from')?->startOfDay() ?? now()->startOfDay();
        $to = $request->date('to')?->endOfDay() ?? now()->endOfDay();

        $base = CashMovement::query()
            ->confirmed()
            ->whereBetween('occurred_at', [$from, $to]);

        $income = (clone $base)->income()->sum('amount');
        $expense = (clone $base)->expense()->sum('amount');
        $balance = $income - $expense;

        $todayBase = CashMovement::query()
            ->confirmed()
            ->whereBetween('occurred_at', [now()->startOfDay(), now()->endOfDay()]);

        $todayIncome = (clone $todayBase)->income()->sum('amount');
        $todayExpense = (clone $todayBase)->expense()->sum('amount');

        $movements = CashMovement::with(['user:id,name', 'booking:id,uuid,code'])
            ->when($request->filled('type'), fn ($query) => $query->where('type', (string) $request->query('type')))
            ->when($request->filled('payment_method'), fn ($query) => $query->where('payment_method', (string) $request->query('payment_method')))
            ->whereBetween('occurred_at', [$from, $to])
            ->latest('occurred_at')
            ->paginate(15)
            ->withQueryString();

        return view('tenant.cash.index', [
            'movements' => $movements,
            'from' => $from,
            'to' => $to,
            'income' => $income,
            'expense' => $expense,
            'balance' => $balance,
            'todayIncome' => $todayIncome,
            'todayExpense' => $todayExpense,
            'currency' => Tenant::current()?->currency ?? 'COP',
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'type' => ['required', 'in:income,expense'],
            'payment_method' => ['required', 'in:cash,card,transfer,online,other'],
            'category' => ['required', 'string', 'max:80'],
            'description' => ['required', 'string', 'max:255'],
            'reference' => ['nullable', 'string', 'max:80'],
            'amount' => ['required', 'numeric', 'min:1'],
            'occurred_at' => ['nullable', 'date'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        CashMovement::create($data + [
            'user_id' => auth()->id(),
            'currency' => Tenant::current()?->currency ?? 'COP',
            'occurred_at' => isset($data['occurred_at']) ? Carbon::parse($data['occurred_at']) : now(),
            'status' => 'confirmed',
        ]);

        return back()->with('success', $data['type'] === 'income' ? 'Ingreso registrado.' : 'Egreso registrado.');
    }

    public function void(CashMovement $movement): RedirectResponse
    {
        $movement->update(['status' => 'void']);

        return back()->with('success', 'Movimiento anulado correctamente.');
    }
}
