<?php

namespace App\Http\Controllers;

use App\Models\Commission;

class CommissionReportController extends Controller
{
    // public function index()
    // {
    //     // Buyer
    //     $buyerPaid = Commission::where('buyer_commission', '>', 0)->get();
    //     $buyerUnpaid = Commission::where('buyer_commission', '=', 0)->get();


    //     // Seller
    //     $sellerPaid = Commission::where('seller_commission', '>', 0)->get();
    //     $sellerUnpaid = Commission::where('seller_commission', '=', 0)->get();

    //     // Receiver
    //     $receiverPaid = Commission::where(function ($q) {
    //         $q->where('buyer_commission', '>', 0)->orWhere('seller_commission', '>', 0);
    //     })->get();

    //     $receiverUnpaid = Commission::where(function ($q) {
    //         $q->where('buyer_commission', '=', 0)->orWhere('seller_commission', '=', 0);
    //     })->get();

    //     return view('commissions.reports', compact(
    //         'buyerPaid', 'buyerUnpaid',
    //         'sellerPaid', 'sellerUnpaid',
    //         'receiverPaid', 'receiverUnpaid'
    //     ));
    // }

    public function index()
    {
        // Fetch commissions
        $commissions = Commission::with('carSale')
            ->select('id', 'car_sale_id', 'date', 'buyer_commission', 'seller_commission', 'receiver_name')
            ->get();
    
        // Fetch expenses
        $expenses = Expense::with('expenseHead')
            ->select('id', 'expense_date as date', 'amount', 'description', 'expense_head_id')
            ->get();
    
        // Normalize into one collection
        $merged = collect();
    
        foreach ($commissions as $commission) {
            $merged->push([
                'type' => 'commission',
                'date' => $commission->date,
                'data' => $commission,
            ]);
        }
    
        foreach ($expenses as $expense) {
            $merged->push([
                'type' => 'expense',
                'date' => $expense->date,
                'data' => $expense,
            ]);
        }
    
        // Sort by date (latest first)
        $merged = $merged->sortByDesc('date');
    
        // Totals
        $totals = [
            'buyer_commission' => $commissions->sum('buyer_commission'),
            'seller_commission' => $commissions->sum('seller_commission'),
            'grand_total'      => $commissions->sum('buyer_commission') + $commissions->sum('seller_commission'),
        ];
    
        $totalExpenses = $expenses->sum('amount');
        $netTotal = $totals['grand_total'] - $totalExpenses;
    
        return view('commissions.reports', compact('merged', 'totals', 'totalExpenses', 'netTotal'));
    }
    
    
}
