<?php

namespace App\Jobs;

use App\Models\Analytic;
use App\Models\Complaint;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ProcessAnalyticsJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        public Carbon $date
    ) {}

    public function handle(): void
    {
        $date = $this->date->format('Y-m-d');
        
        // Process analytics for all Polda
        $poldas = \App\Models\Polda::where('is_active', true)->get();
        
        foreach ($poldas as $polda) {
            $this->processForPolda($polda, $date);
        }
    }

    private function processForPolda($polda, string $date): void
    {
        $complaints = Complaint::where('polda_id', $polda->id)
            ->whereDate('created_at', $date)
            ->get();

        $stats = [
            'total_complaints' => $complaints->count(),
            'emergency_complaints' => $complaints->whereIn('category', [
                'emergency_police',
                'emergency_medical',
                'emergency_fire',
                'emergency_disaster'
            ])->count(),
            'non_emergency_complaints' => $complaints->where('category', 'non_emergency')->count(),
            'completed_complaints' => $complaints->where('status', 'completed')->count(),
        ];

        // Calculate response time
        $responseTimes = $complaints->whereNotNull('dispatched_at')
            ->map(fn($c) => $c->dispatched_at->diffInMinutes($c->received_at))
            ->filter();

        $resolutionTimes = $complaints->whereNotNull('resolved_at')
            ->map(fn($c) => $c->resolved_at->diffInMinutes($c->received_at))
            ->filter();

        Analytic::updateOrCreate(
            [
                'date' => $date,
                'polda_id' => $polda->id,
                'polres_id' => null,
                'polsek_id' => null,
            ],
            [
                'total_complaints' => $stats['total_complaints'],
                'emergency_complaints' => $stats['emergency_complaints'],
                'non_emergency_complaints' => $stats['non_emergency_complaints'],
                'completed_complaints' => $stats['completed_complaints'],
                'average_response_time' => $responseTimes->avg(),
                'average_resolution_time' => $resolutionTimes->avg(),
            ]
        );
    }
}
