<?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());

        // No branch filter here on purpose. Payment and POSTransaction both
        // carry BranchScope, so the sheet is already the active branch's — and
        // the filter that used to be here read session('active_branch_id')
        // raw, which skipped the entitlement repair in BranchContext and, for
        // a stale null, printed every branch's takings on one page.
        $payments = Payment::where('direction', 'inbound')->where('status', 'confirmed')
            ->whereDate('payment_date', $date)
            ->with(['createdBy', 'invoice'])
            ->orderBy('payment_date')
            ->get();

        $posTransactions = POSTransaction::whereDate('processed_at', $date)
            ->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,
        ]);
    }
}
