<?php

namespace App\Http\Controllers;

use App\Domain\Financial\Models\Payment;
use App\Domain\POS\Models\POSTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class ReportPrintController extends Controller
{
    public function dailyFinancial(Request $request)
    {
        Gate::authorize('reports.view');

        $date = $request->get('date', now()->toDateString());
        $branchId = session('active_branch_id');

        $payments = Payment::where('direction', 'inbound')->where('status', 'confirmed')
            ->whereDate('payment_date', $date)
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->with(['createdBy', 'invoice'])
            ->orderBy('payment_date')
            ->get();

        $posTransactions = POSTransaction::whereDate('processed_at', $date)
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->with('user')
            ->orderBy('processed_at')
            ->get();

        $totalPayments = $payments->sum('amount');
        $totalPOS = $posTransactions->sum('total_amount');
        $grandTotal = $totalPayments + $totalPOS;

        $methodBreakdown = $payments->groupBy(fn ($p) => $p->method?->value ?? 'other')
            ->map(fn ($group) => [
                'count' => $group->count(),
                'total' => $group->sum('amount'),
            ]);

        return view('reports.daily-financial-print', [
            'date' => $date,
            'payments' => $payments,
            'posTransactions' => $posTransactions,
            'totalPayments' => $totalPayments,
            'totalPOS' => $totalPOS,
            'grandTotal' => $grandTotal,
            'methodBreakdown' => $methodBreakdown,
        ]);
    }
}
