<?php

namespace App\Services;

use App\Models\Demande;
use App\Models\Dossier;
use App\Models\Rendezvous;
use App\Models\Ticket;
use Illuminate\Support\Facades\Cache;

class SidebarCache
{
    const CACHE_KEY = 'sidebar_counters_global';
    const CACHE_TTL = 300;

    public static function getAll()
    {
        return Cache::remember(self::CACHE_KEY, self::CACHE_TTL, function() {
            return self::recalculate();
        });
    }

    public static function clear()
    {
        Cache::forget(self::CACHE_KEY);
    }

    public static function recalculate()
    {
        $counts = [];

        // ========== SIMPLE COUNTS ==========
        $counts['demandes'] = Demande::where('status_rendezvous_id', 2)->count();
        $counts['rdv'] = Rendezvous::where('status_rendezvous_id', 2)->count();
        $counts['ticketcount'] = Ticket::where('status_rendezvous_id', 2)->count();
        $counts['ticketcountterminer'] = Ticket::where('status_rendezvous_id', 3)->count();
        
        $counts['dossiersfacture'] = Dossier::whereNull('facture')
            ->where('dossier_status_id', 2)
            ->where('update', 1)
            ->count();

        // ========== DOSSIER TYPES ==========
        $counts['tribunale'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->where('type_expertise_id', 9)
            ->count();
            
        $counts['douteux'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->where('sinistre_douteux', 1)
            ->count();
            
        $counts['rapide'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->where('type_expertise_id', 16)
            ->count();

        // ========== DOCUMENT COUNTS ==========
        $counts['docasigner'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('document', function ($query) {
                $query->where('type_document_id', 21)
                    ->where('signer', 0)
                    ->where('rejected', 0);
            })->count();

        $counts['docsigner'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('document', function ($query) {
                $query->where('type_document_id', 21)
                    ->where('signer', 1)
                    ->where('rejected', 0);
            })
            ->whereDoesntHave('onerapport', function ($query) {
                $query->whereIn('rapport_status_id', [2, 3]);
            })->count();

        // ========== EXPERTISE/CARENCE COUNTS ==========
        
        // Attente Photos Avant (no devis, no photos avant type 5)
        $counts['aexpcount'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereDoesntHave('devis')
            ->whereDoesntHave('document', function ($query) {
                $query->where('type_document_id', 5);
            })->count();

        // En Expertise (meeting en cours status 2)
        $counts['enexp'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('meeting', function ($query) {
                $query->where('meeting_status_id', 2);
            })->count();

        // Attente Devis (no devis at all)
        $counts['attdevis'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereDoesntHave('devis')
            ->count();

        // Attente Photos Après (devis accord, no facture, no photos après type 6)
        $counts['attexpap'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->where('type_expertise_id', '!=', 14)
            ->where('mode_id', '!=', 7)
            ->whereDoesntHave('document', function ($query) {
                $query->where('type_document_id', 6);
            })
            ->whereHas('onedevis', function ($query) {
                $query->where('devis_status_id', 2)
                    ->orWhere('devis_status_id', 7);
            })
            ->whereDoesntHave('facture')
            ->count();

        // Attente Facture (devis accord, has photos après, no facture)
        $counts['attfacture'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->where('type_expertise_id', '!=', 14)
            ->where('mode_id', '!=', 7)
            ->whereHas('document', function ($query) {
                $query->where('type_document_id', 6);
            })
            ->whereHas('onedevis', function ($query) {
                $query->where('devis_status_id', 2)
                    ->orWhere('devis_status_id', 7);
            })
            ->whereDoesntHave('facture')
            ->count();

        // Attente Rapport (devis & facture accord, no rapport)
        $counts['attrapport'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('devis', function ($query) {
                $query->where('devis_status_id', 2)
                    ->orWhere('devis_status_id', 7);
            })
            ->whereHas('facture', function ($query) {
                $query->where('devis_status_id', 2)
                    ->orWhere('devis_status_id', 7);
            })
            ->whereDoesntHave('rapport')
            ->count();

        // Attente Documents Base (missing doc types 1, 2, 3)
        $counts['basedoc'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereDoesntHave('document', function ($query) {
                $query->whereIn('type_document_id', [1, 2, 3]);
            })->count();

        // ========== DEVIS STATUS COUNTS ==========
        // Get all dossiers with devis and loop through (like original)
        $dossiersWithDevis = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('devis')
            ->with('onedevis')
            ->get();

        $counts['deuxdevis'] = 0;
        $counts['senddevis'] = 0;
        $counts['avisdevis'] = 0;
        $counts['traitdevis'] = 0;
        $counts['count'] = 0;
        $counts['controldevis'] = 0;
        $counts['attdevisav'] = 0;

        foreach ($dossiersWithDevis as $dossier) {
            if ($dossier->onedevis) {
                switch ($dossier->onedevis->devis_status_id) {
                    case 1:
                        $counts['deuxdevis']++;
                        break;
                    case 2:
                        $counts['senddevis']++;
                        break;
                    case 3:
                        $counts['avisdevis']++;
                        break;
                    case 4:
                        $counts['traitdevis']++;
                        break;
                    case 5:
                        $counts['count']++;
                        break;
                    case 8:
                        $counts['controldevis']++;
                        break;
                    case 9:
                        $counts['attdevisav']++;
                        break;
                }
            }
        }

        // ========== FACTURE STATUS COUNTS ==========
        $dossiersWithFacture = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereHas('facture')
            ->with('onefacture')
            ->get();

        $counts['deuxfacture'] = 0;
        $counts['avisfacture'] = 0;
        $counts['traitfacture'] = 0;
        $counts['count2'] = 0;
        $counts['attfactureap'] = 0;

        foreach ($dossiersWithFacture as $dossier) {
            if ($dossier->onefacture) {
                switch ($dossier->onefacture->devis_status_id) {
                    case 1:
                        $counts['deuxfacture']++;
                        break;
                    case 3:
                        $counts['avisfacture']++;
                        break;
                    case 4:
                        $counts['traitfacture']++;
                        break;
                    case 5:
                        $counts['count2']++;
                        break;
                    case 9:
                        $counts['attfactureap']++;
                        break;
                }
            }
        }

        // Sendfacture - special query (no rapport, facture status 2)
        $counts['sendfacture'] = Dossier::where('dossier_status_id', 2)
            ->where('update', 0)
            ->whereDoesntHave('rapport')
            ->whereHas('facture', function ($query) {
                $query->where('devis_status_id', 2);
            })->count();

        // ========== RAPPORT STATUS COUNTS ==========
        // Important: sendrapport does NOT filter by update=0 in the loop
        $dossiersWithRapport = Dossier::where('dossier_status_id', 2)
            ->whereHas('rapport')
            ->with('onerapport')
            ->get();

        $counts['deuxrapport'] = 0;
        $counts['sendrapport'] = 0;
        $counts['rapportasigner'] = 0;
        $counts['count3'] = 0;

        foreach ($dossiersWithRapport as $dossier) {
            if ($dossier->onerapport) {
                // sendrapport counts ALL with status 2 (no update check)
                if ($dossier->onerapport->rapport_status_id === 2) {
                    $counts['sendrapport']++;
                }
                
                // Others only count if update == 0
                if ($dossier->update == 0) {
                    switch ($dossier->onerapport->rapport_status_id) {
                        case 1:
                            $counts['deuxrapport']++;
                            break;
                        case 4:
                            $counts['rapportasigner']++;
                            break;
                        case 5:
                            $counts['count3']++;
                            break;
                    }
                }
            }
        }

        return $counts;
    }
}