<?php

namespace App\Livewire\CustomerPortal;

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

class Appointments extends Component
{
    use WithPagination;

    public $filterStatus = '';
    public $filterDate = '';

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

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

    public function render()
    {
        $user = Auth::user();
        $customer = Customer::where('email', $user->email)->first();

        $appointments = collect();
        
        if ($customer) {
            $appointments = Appointment::where('customer_id', $customer->id)
                ->when($this->filterStatus, function ($query) {
                    $query->where('status', $this->filterStatus);
                })
                ->when($this->filterDate, function ($query) {
                    $query->whereDate('scheduled_datetime', $this->filterDate);
                })
                ->with(['vehicle', 'assignedTechnician'])
                ->orderBy('scheduled_datetime', 'desc')
                ->paginate(10);
        }

        return view('livewire.customer-portal.appointments', compact('appointments'))
            ->layout('layouts.customer-portal-app');
    }
}
