<?php

namespace App\Livewire\CustomerPortal;

use App\Models\JobCard;
use App\Models\Appointment;
use App\Models\Vehicle;
use App\Models\Estimate;
use App\Models\ServiceOrder;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class Dashboard extends Component
{
    public $stats = [];
    public $recentActivity = [];
    public $upcomingAppointments = [];
    public $activeJobCards = [];

    public function mount()
    {
        $user = Auth::user();
        
        // Get the customer record via the relationship
        $customer = $user->customer;
        
        if (!$customer) {
            // If no customer record exists but user has customer role, 
            // create customer record linked to the user
            if ($user->isCustomer()) {
                $nameParts = explode(' ', $user->name, 2);
                $firstName = $nameParts[0];
                $lastName = $nameParts[1] ?? '';
                
                $customer = \App\Models\Customer::create([
                    'user_id' => $user->id,
                    'first_name' => $firstName,
                    'last_name' => $lastName,
                    'email' => $user->email,
                    'phone' => $user->phone ?? '',
                    'address' => '',
                    'city' => '',
                    'state' => '',
                    'zip_code' => '',
                    'status' => 'active'
                ]);
            } else {
                // User doesn't have customer role, redirect to dashboard
                return redirect('/dashboard');
            }
        }

        $this->loadDashboardData($customer);
    }

    private function loadDashboardData($customer)
    {
        // Load statistics
        $this->stats = [
            'total_vehicles' => Vehicle::where('customer_id', $customer->id)->count(),
            'active_jobs' => JobCard::where('customer_id', $customer->id)
                ->whereNotIn('status', ['completed', 'cancelled'])
                ->count(),
            'pending_estimates' => Estimate::whereHas('jobCard', function($query) use ($customer) {
                $query->where('customer_id', $customer->id);
            })->whereIn('status', ['sent', 'viewed'])->count(),
            'completed_services' => JobCard::where('customer_id', $customer->id)
                ->where('status', 'completed')
                ->count(),
        ];

        // Load upcoming appointments
        $this->upcomingAppointments = Appointment::where('customer_id', $customer->id)
            ->where('scheduled_datetime', '>=', now())
            ->orderBy('scheduled_datetime')
            ->limit(5)
            ->get();

        // Load active job cards
        $this->activeJobCards = JobCard::where('customer_id', $customer->id)
            ->whereNotIn('status', ['completed', 'cancelled'])
            ->with(['vehicle', 'serviceAdvisor'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        // Load recent activity
        $this->recentActivity = collect()
            ->merge(
                JobCard::where('customer_id', $customer->id)
                    ->orderBy('updated_at', 'desc')
                    ->limit(3)
                    ->get()
                    ->map(function($jobCard) {
                        return [
                            'type' => 'job_card',
                            'title' => 'Job Card #' . $jobCard->id . ' ' . ucfirst(str_replace('_', ' ', $jobCard->status)),
                            'description' => 'Vehicle: ' . ($jobCard->vehicle->year ?? '') . ' ' . ($jobCard->vehicle->make ?? '') . ' ' . ($jobCard->vehicle->model ?? ''),
                            'date' => $jobCard->updated_at,
                            'status' => $jobCard->status,
                            'url' => route('customer-portal.status', $jobCard)
                        ];
                    })
            )
            ->merge(
                Estimate::whereHas('jobCard', function($query) use ($customer) {
                    $query->where('customer_id', $customer->id);
                })
                ->orderBy('updated_at', 'desc')
                ->limit(2)
                ->get()
                ->map(function($estimate) {
                    return [
                        'type' => 'estimate',
                        'title' => 'Estimate #' . $estimate->id . ' ' . ucfirst($estimate->status),
                        'description' => '$' . number_format($estimate->total_amount, 2),
                        'date' => $estimate->updated_at,
                        'status' => $estimate->status,
                        'url' => route('customer-portal.estimate', [$estimate->job_card_id, $estimate->id])
                    ];
                })
            )
            ->sortByDesc('date')
            ->take(5);
    }

    public function refreshDashboard()
    {
        $user = Auth::user();
        $customer = \App\Models\Customer::where('email', $user->email)->first();
        
        if ($customer) {
            $this->loadDashboardData($customer);
            session()->flash('message', 'Dashboard refreshed!');
        }
    }

    public function render()
    {
        return view('livewire.customer-portal.dashboard')
            ->layout('layouts.customer-portal-app');
    }
}
