<?php

namespace App\Http\Controllers;

use App\Models\PaymentLedger;
use App\Models\Buyer;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class PaymentLedgerController extends Controller
{
    public function index()
    {
        $ledgers = PaymentLedger::with('buyer')
            ->orderBy('current_balance', 'desc')
            ->paginate(20);

        return view('admin.payment.ledger.index', compact('ledgers'));
    }

    public function show(Buyer $buyer)
    {
        $ledger = PaymentLedger::getOrCreateForBuyer($buyer->id);
        $advancePayments = $buyer->advancePayments()
            ->with(['orderConfirmation', 'allocations.factory'])
            ->latest()
            ->get();
            
        $allocations = \App\Models\PaymentAllocation::whereHas('advancePayment', function($q) use ($buyer) {
            $q->where('buyer_id', $buyer->id);
        })->with(['factory', 'orderConfirmation', 'advancePayment'])
        ->latest()
        ->get();

        return view('admin.payment.ledger.show', compact('buyer', 'ledger', 'advancePayments', 'allocations'));
    }

    public function updateAllLedgers()
    {
        PaymentLedger::updateAllLedgers();

        return back()->with('success', 'All payment ledgers updated successfully.');
    }

    public function buyerReport(Buyer $buyer)
    {
        $ledger = PaymentLedger::getOrCreateForBuyer($buyer->id);
        $advancePayments = $buyer->advancePayments()
            ->with(['orderConfirmation', 'allocations.factory'])
            ->latest()
            ->get();
            
        $allocations = \App\Models\PaymentAllocation::whereHas('advancePayment', function($q) use ($buyer) {
            $q->where('buyer_id', $buyer->id);
        })->with(['factory', 'orderConfirmation', 'advancePayment'])
        ->latest()
        ->get();

        $pdf = PDF::loadView('admin.payment.ledger.buyer-report', compact('buyer', 'ledger', 'advancePayments', 'allocations'));
        
        return $pdf->download("ledger-report-{$buyer->company_name}.pdf");
    }
}