<?php

namespace App\Livewire\Dashboard;

use App\Models\JobCard;
use App\Models\Estimate;
use App\Models\WorkOrder;
use Livewire\Component;
use Carbon\Carbon;

class PerformanceMetrics extends Component
{
    public function render()
    {
        $currentWeek = now()->startOfWeek();
        $lastWeek = now()->subWeek()->startOfWeek();
        
        $metrics = [
            'this_week' => [
                'jobs_completed' => JobCard::whereBetween('completion_datetime', [$currentWeek, $currentWeek->copy()->endOfWeek()])
                    ->where('status', 'completed')
                    ->count(),
                'revenue' => Estimate::whereBetween('customer_approved_at', [$currentWeek, $currentWeek->copy()->endOfWeek()])
                    ->where('customer_approval_status', 'approved')
                    ->sum('total_amount'),
                'avg_completion_time' => $this->getAverageCompletionTime($currentWeek, $currentWeek->copy()->endOfWeek()),
                'customer_satisfaction' => 4.2, // This would come from a customer feedback system
            ],
            'last_week' => [
                'jobs_completed' => JobCard::whereBetween('completion_datetime', [$lastWeek, $lastWeek->copy()->endOfWeek()])
                    ->where('status', 'completed')
                    ->count(),
                'revenue' => Estimate::whereBetween('customer_approved_at', [$lastWeek, $lastWeek->copy()->endOfWeek()])
                    ->where('customer_approval_status', 'approved')
                    ->sum('total_amount'),
            ],
        ];

        // Calculate growth percentages
        $metrics['growth'] = [
            'jobs' => $this->calculateGrowth($metrics['last_week']['jobs_completed'], $metrics['this_week']['jobs_completed']),
            'revenue' => $this->calculateGrowth($metrics['last_week']['revenue'], $metrics['this_week']['revenue']),
        ];

        return view('livewire.dashboard.performance-metrics', compact('metrics'));
    }

    private function getAverageCompletionTime($start, $end)
    {
        $completedJobs = JobCard::whereBetween('completion_datetime', [$start, $end])
            ->where('status', 'completed')
            ->whereNotNull('arrival_datetime')
            ->whereNotNull('completion_datetime')
            ->get();

        if ($completedJobs->isEmpty()) {
            return 0;
        }

        $totalHours = $completedJobs->sum(function ($job) {
            return $job->arrival_datetime->diffInHours($job->completion_datetime);
        });

        return round($totalHours / $completedJobs->count(), 1);
    }

    private function calculateGrowth($previous, $current)
    {
        if ($previous == 0) {
            return $current > 0 ? 100 : 0;
        }

        return round((($current - $previous) / $previous) * 100, 1);
    }
}
