<?php

namespace App\Http\Controllers\Customer;

use App\Core\Repositories\InvoiceRepository;
use App\Core\Repositories\PaymentRepository;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class CustomerDashboardController extends Controller
{
    public function __construct(
        private InvoiceRepository $invoiceRepository,
        private PaymentRepository $paymentRepository
    ) {}

    /**
     * Display the customer dashboard
     */
    public function index(): View
    {
        $customer = Auth::guard('customer')->user();

        // Get customer's invoices
        $invoices = $this->invoiceRepository->getPaginated(10, [
            'customer_id' => $customer->id,
        ]);

        // Get customer's payments
        $payments = $this->paymentRepository->getPaginated(10, [
            'customer_id' => $customer->id,
        ]);

        // Calculate statistics
        $totalInvoices = $customer->invoices()->count();
        $paidInvoices = $customer->invoices()->where('status', 'paid')->count();
        $pendingInvoices = $customer->invoices()->where('status', 'pending')->count();
        $overdueInvoices = $customer->invoices()
            ->where('status', 'pending')
            ->where('due_date', '<', now())
            ->count();

        $totalPaid = $customer->payments()
            ->where('status', 'completed')
            ->sum('amount');

        $totalOutstanding = $customer->invoices()
            ->where('status', 'pending')
            ->sum('total');

        return view('customer.dashboard', [
            'customer' => $customer,
            'invoices' => $invoices,
            'payments' => $payments,
            'totalInvoices' => $totalInvoices,
            'paidInvoices' => $paidInvoices,
            'pendingInvoices' => $pendingInvoices,
            'overdueInvoices' => $overdueInvoices,
            'totalPaid' => $totalPaid,
            'totalOutstanding' => $totalOutstanding,
        ]);
    }
}
