<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class InvoiceController extends Controller
{
    public function index()
    {
        $invoices = Auth::user()->invoices()->latest('issue_date')->paginate(15);

        // Single query instead of 4 separate queries
        $rawStats = Auth::user()->invoices()
            ->selectRaw("
                COUNT(*) as total,
                SUM(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) as paid,
                SUM(CASE WHEN status IN ('SENT','OVERDUE','PENDING') THEN 1 ELSE 0 END) as unpaid,
                COALESCE(SUM(total_amount), 0) as total_amount
            ")->first();

        $stats = [
            'total' => $rawStats->total ?? 0,
            'paid' => $rawStats->paid ?? 0,
            'unpaid' => $rawStats->unpaid ?? 0,
            'total_amount' => $rawStats->total_amount ?? 0,
        ];

        return view('customer.invoices.index', compact('invoices', 'stats'));
    }

    public function show($id)
    {
        $invoice = Auth::user()->invoices()->with('items', 'payments')->findOrFail($id);

        return view('customer.invoices.show', compact('invoice'));
    }
}
