<?php

namespace App\Livewire\CustomerPortal;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\ServiceOrder;
use Illuminate\Support\Facades\Auth;

class Invoices extends Component
{
    use WithPagination;

    public $filterStatus = '';
    public $customer;

    public function mount()
    {
        $this->customer = Auth::user();
    }

    public function render()
    {
        $invoices = collect();
        
        // Find customer by email
        $customer = \App\Models\Customer::where('email', $this->customer->email)->first();
        
        if ($customer) {
            $query = ServiceOrder::with(['vehicle', 'customer'])
                ->where('customer_id', $customer->id)
                ->whereNotNull('completed_at')
                ->orderBy('completed_at', 'desc');

            if ($this->filterStatus) {
                $query->where('status', $this->filterStatus);
            }

            $invoices = $query->paginate(10);
        }

        return view('livewire.customer-portal.invoices', [
            'invoices' => $invoices
        ])->layout('layouts.customer-portal-app');
    }

    public function updatingFilterStatus()
    {
        $this->resetPage();
    }
}
