<br />
<b>Warning</b>:  Undefined variable $auth in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<br />
<b>Warning</b>:  Trying to access array offset on value of type null in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<?php

use Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

if (! function_exists('convert_amount')) {
    function convert_amount($amount) {
        $currency = "F CFA";
        if (is_numeric($amount)) {
            return number_format($amount, 2);
        }
        return 0;
    }
}
if (! function_exists('normalizePresenceDates')) {

    function normalizePresenceDates() {
        // Récupérer toutes les lignes avec p_date non null
        $presences = DB::table('presences')
            ->select('p_id', 'p_date')
            ->whereNotNull('p_date')
            ->get();

        foreach ($presences as $presence) {
            try {
                // Convertir la date en Carbon et formatter en Y-m-d
                $newDate = Carbon::parse($presence->p_date)->format('Y-m-d');

                // Mettre à jour la ligne
                DB::table('presences')
                    ->where('p_id', $presence->id)
                    ->update(['p_date' => $newDate]);

            } catch (\Exception $e) {
                // Si la date est invalide ou non parsable, on peut logguer
                Log::warning("Impossible de parser la date pour l'id {$presence->p_id}: {$presence->p_date}");
            }
        }

        return "Toutes les dates ont été normalisées au format Y-m-d.";
    }
}
if (! function_exists('convert_number')) {
    function convert_number($amount) {
        if (is_numeric($amount)) {
            //return number_format($amount, 2);
            return number_format($amount, 2, ',',' ');
        }
        return 0;
    }
}
if (! function_exists('getHoursByType')) {

    function getHoursByType(string $type): string
    {
        $arrived = '08:30';
        $arrived_am = '08:30 AM';
        $depart  = '15:30';
        $depart_pm  = '15:30 PM';

        if ($type === 'arrived') {
            return Carbon::createFromTimeString($arrived)->format('H:i');
        }

        if ($type === 'depart') {
            return Carbon::createFromTimeString($depart)->format('H:i');
        }
        if ($type === 'arrived_am') {
            return $arrived_am;
        }
        if ($type === 'depart_pm') {
            return $depart_pm;
        }

        return 'Type invalide';
    }
}
if (! function_exists('getLogo')) {
    function getLogo() {
        return asset('logo/pev.png');
    }
}

if (!function_exists('formatPresenceType')) {
    function formatPresenceType($type) {
        if ($type === 'AM') {
            return 'Entrée';
        } elseif ($type === 'PM') {
            return 'Sortie';
        } elseif ($type === 'PAUSE') {
            return 'Pause';
        } elseif ($type === 'AM-PM') {
            return 'Entrée / Sortie';
        }
        return $type ?: 'Tous';
    }
}
if (!function_exists('convertTo24Hour')) {
   function convertTo24Hour($time12h) {
        try {
            // Essayer le format h:i:s A
            $time = \Carbon\Carbon::createFromFormat('h:i:s A', $time12h);
            return $time->format('H:i:s');
        } catch (\Exception $e1) {
            try {
                // Essayer un autre format, par exemple h:i A
                $time = \Carbon\Carbon::createFromFormat('h:i A', $time12h);
                return $time->format('H:i');
            } catch (\Exception $e2) {
                return $time12h; // Retourner la valeur brute en cas d'erreur
            }
        }
    }
}
if (!function_exists('getArrivalStatus')) {
    function getArrivalStatus($arrivalTime, $referenceTime = '08:30')
    {
        // S'assurer que les heures sont au format H:i
        $arrival = Carbon::createFromFormat('H:i', $arrivalTime);
        $reference = Carbon::createFromFormat('H:i', $referenceTime);

        return $arrival->lessThanOrEqualTo($reference) ? 'À l\'heure' : 'En retard';
    }
}
if (!function_exists('getArrivalStatusWithMeridian')) {
    function getArrivalStatusWithMeridian($arrivalTime)
    {
        try {
            $arrivalTime = trim($arrivalTime);
            $referenceTime = trim(getHoursByType('arrived_am'));
            
            // Utiliser strtotime pour une conversion universelle
            $arrivalTimestamp = strtotime($arrivalTime);
            $referenceTimestamp = strtotime($referenceTime);
            
            if ($arrivalTimestamp === false) {
                throw new \Exception("Heure d'arrivée invalide: $arrivalTime");
            }
            
            if ($referenceTimestamp === false) {
                throw new \Exception("Heure de référence invalide: $referenceTime");
            }
            
            return $arrivalTimestamp <= $referenceTimestamp ? 'À l\'heure' : 'En retard';
            
        } catch (\Exception $e) {
            Log::error("Erreur dans getArrivalStatusWithMeridian: " . $e->getMessage());
            return 'Erreur';
        }
    }
}

if (! function_exists('getNameCabinet')) {
    function getNameCabinet() {
        return "SYGEIP PRO";
    }
}
if (! function_exists('getFetchImage')) {
    function getFetchImage($image) {
        return "https://pia-soft.com/sygeip_pev/images/".$image;
    }
}
if (! function_exists('getFetchImageOthers')) {
    function getFetchImageOthers($image) {
        return "https://pia-soft.com/sygeip_pev/img_autres/".$image;
    }
}


if (!function_exists('isExpired')) {
    /**
     * Vérifie si une date est expirée (antérieure à aujourd'hui)
     * 
     * @param string|Carbon $date La date à vérifier
     * @return bool true si la date est expirée, false sinon
     */
    function isExpired($date)
    {
        // Convertir en instance Carbon si nécessaire
        $givenDate = $date instanceof Carbon ? $date : Carbon::parse($date);
        
        // Obtenir la date d'aujourd'hui sans l'heure
        $today = Carbon::today();
        
        // Retourner true si la date donnée est antérieure à aujourd'hui
        return $givenDate->lt($today);
    }
}

// Version alternative avec plus d'options
if (!function_exists('checkExpiration')) {
    /**
     * Vérifie l'état d'expiration d'une date avec plus d'options
     * 
     * @param string|Carbon $date La date à vérifier
     * @param bool $includeTime Inclure l'heure dans la comparaison
     * @return array Informations détaillées sur l'expiration
     */
    function checkExpiration($date, $includeTime = false)
    {
        $givenDate = $date instanceof Carbon ? $date : Carbon::parse($date);
        $now = $includeTime ? Carbon::now() : Carbon::today();
        
        return [
            'is_expired' => $givenDate->lt($now),
            'is_today' => $givenDate->isSameDay($now),
            'is_future' => $givenDate->gt($now),
            'days_until_expiry' => $now->diffInDays($givenDate, false),
            'human_readable' => $givenDate->diffForHumans($now)
        ];
    }
}


if (! function_exists('getFolderTypes')) {
    function getFolderTypes() {
        return [
            'cv' => 'CV',
            'integration_act' => 'Acte d\'intégration',
            'work_contract' => 'Contrat de travail',
            'internship_agreement' => 'Accord de stage',
            'service_start_attestation' => 'Attestation de prise de service',
            'appointment_act' => 'Acte de nomination',
            'assignment_act' => 'Acte d\'affectation',
            'effective_presence_attestation' => 'Attestation de présence effective',
            'distinctions_prizes' => 'Distinction et prix',
            'sanctions' => 'Sanctions',
            'diplomas_certificates' => 'Diplômes et certificats',
            'cni' => 'CNI',
            'birth_certificate' => 'Acte de naissance',
            'marriage_certificate' => 'Acte de mariage',
            'ice_form' => 'Formulaire ICE'
        ];
    }
}

if (! function_exists('getFolderTypeName')) {
    function getFolderTypeName($type) {
        $types = getFolderTypes();
        return $types[$type] ?? $type;
    }
}

if (! function_exists('generateFolderOptions')) {
    function generateFolderOptions($selected = '') {
        $options = '<option value