<?php

namespace App\Models\HRM;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use OwenIt\Auditing\Contracts\Auditable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Carbon\Carbon;
class Leave extends Model implements Auditable
{

    use HasFactory,\OwenIt\Auditing\Auditable;
    protected $fillable = [
        'uid',
        'name',
        'status',
        'employee',
        'employee_id',
        'employee_pid',
        'type',
        'start',
        'end',
        'countedDays',
        'daysOriginOff',
        'concretDays',
        'comment',
        'replay',
    ];

    const STATUS_CONFIRMED = 'confirmed';
    const STATUS_ONGOING = 'ongoing';
    const STATUS_REJECTED = 'rejected';
    const STATUS_CANCELED = 'canceled';
    const STATUS_BACK = 'back';
    const STATUS_TAKEN = 'taken';
    const STATUS_DRAFT = 'draft';
    const STATUS_PENDING = 'pending';
    const STATUS_REQUESTED = 'requested';
    //requestExpired
    const STATUS_REQUEST_EXPIRED = 'requestExpired';

    protected $casts = [
        'start' => 'datetime',
        'end' => 'datetime',
        'countedDays' => 'integer',
    ];

    protected function employee(): Attribute
    {
        return Attribute::make(
            get: fn($value) => json_decode($value, true),
            set: fn($value) => json_encode($value),
        );
    }


    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->uid)) {
                $model->uid = (string) Str::ulid();
            }

            if (!empty($model->employee)) {
                $model->name = $model->employee['name'];
                $model->employee_id = $model->employee['id'];
            }

            // حساب الأيام
            $holidays = array_column(self::HOLIDAYS, 'date'); // مثال، ممكن تجيبهم من جدول عطلات
            $days = $model->calculateDays($holidays);
            $model->countedDays = $days['countedDays'];
            $model->concretDays = $days['concretDays'];

            $model->daysOriginOff = $model->generateDaysOriginOffText();
        });

        static::updating(function ($model) {
            if ($model->isDirty('employee')) {
                $model->name = $model->employee['name'];
                $model->employee_id = $model->employee['id'];
            }

            // إعادة حساب الأيام إذا تغيرت التواريخ
            if ($model->isDirty(['start', 'end'])) {
                $holidays = array_column(self::HOLIDAYS, 'date');
                $days = $model->calculateDays($holidays);
                $model->countedDays = $days['countedDays'];
                $model->concretDays = $days['concretDays'];

                $model->daysOriginOff = $model->generateDaysOriginOffText();
            }
        });
    }



    public function calculateDays($holidays = [])
    {
        $start = $this->start;
        $end = $this->end;

        if (!$start || !$end) {
            return [
                'countedDays' => 0,
                'concretDays' => 0,
            ];
        }

        $current = $start->copy();
        $countedDays = 0;
        $concretDays = 0;

        while ($current <= $end) {
            $dayOfWeek = $current->dayOfWeek; // 0 = dimanche, 6 = samedi
            $isHoliday = in_array($current->toDateString(), $holidays);

            // يوم العمل الفعلي: ماشي عيد وماشي الأحد
            if ($dayOfWeek !== 0 && !$isHoliday) {
                $countedDays++; // غادي يتحسب من رصيد العطلة
            }

            // الأيام الواقعية (concrete): كل يوم فيه عطلة مهما كان
            $concretDays++;

            $current->addDay();
        }

        return [
            'countedDays' => $countedDays,
            'concretDays' => $concretDays,
        ];
    }

    public function generateDaysOriginOffText()
    {
        $start = $this->start;
        $end = $this->end;

        if (!$start || !$end) {
            return '';
        }

        $holidays = self::HOLIDAYS;

        $current = $start->copy();
        $daysOriginOff = [];

        while ($current <= $end) {
            $dayOfWeek = $current->dayOfWeek; // 0 = dimanche, 6 = samedi
            $dateStr = $current->toDateString();

            // vérifier si c'est un holiday
            $holiday = collect($holidays)->firstWhere('date', $dateStr);

            if ($holiday) {
                $daysOriginOff[] = $holiday['name_fr'];
            } elseif ($dayOfWeek == 0) {
                // dimanche ou samedi
                $daysOriginOff[] ='Dimanche';
            }

            $current->addDay();
        }

        // créer une phrase standard
        if (count($daysOriginOff) > 0) {
            $text = 'Les jours repos inclus sont : ' . implode(', ', $daysOriginOff) . '.';
            return $text;
        }

        return '';
    }



    const HOLIDAYS = [
        ['date' => '2025-01-01', 'name_en' => 'New Year', 'name_fr' => 'Nouvel An', 'name_ar' => 'رأس السنة الميلادية'],
        ['date' => '2025-01-11', 'name_en' => 'Independence Manifesto', 'name_fr' => 'Manifeste de l’Indépendance', 'name_ar' => 'ذكرى تقديم وثيقة الاستقلال'],
        ['date' => '2025-01-14', 'name_en' => 'Amazigh New Year', 'name_fr' => 'Nouvel An Amazigh', 'name_ar' => 'رأس السنة الأمازيغية'],
        ['date' => '2025-03-31', 'name_en' => 'Eid al-Fitr', 'name_fr' => 'Aïd al-Fitr', 'name_ar' => 'عيد الفطر'],
        ['date' => '2025-04-01', 'name_en' => 'Eid al-Fitr Holiday', 'name_fr' => 'Jour férié Aïd al-Fitr', 'name_ar' => 'عطلة عيد الفطر'],
        ['date' => '2025-05-01', 'name_en' => 'Labour Day', 'name_fr' => 'Fête du Travail', 'name_ar' => 'عيد العمال'],
        ['date' => '2025-06-07', 'name_en' => 'Eid al-Adha', 'name_fr' => 'Aïd al-Adha', 'name_ar' => 'عيد الأضحى'],
        ['date' => '2025-06-08', 'name_en' => 'Eid al-Adha Holiday', 'name_fr' => 'Jour férié Aïd al-Adha', 'name_ar' => 'عطلة عيد الأضحى'],
        ['date' => '2025-06-09', 'name_en' => 'Eid al-Adha Holiday', 'name_fr' => 'Jour férié Aïd al-Adha', 'name_ar' => 'عطلة عيد الأضحى'],
        ['date' => '2025-06-27', 'name_en' => 'Islamic New Year', 'name_fr' => 'Nouvel An Islamique', 'name_ar' => 'رأس السنة الهجرية'],
        ['date' => '2025-07-30', 'name_en' => 'Throne Day', 'name_fr' => 'Fête du Trône', 'name_ar' => 'عيد العرش'],
        ['date' => '2025-08-14', 'name_en' => 'Green March Day', 'name_fr' => 'Fête de la Marche Verte', 'name_ar' => 'ذكرى المسيرة الخضراء'],
        ['date' => '2025-08-20', 'name_en' => 'Revolution of the King and the People', 'name_fr' => 'Révolution du Roi et du Peuple', 'name_ar' => 'ثورة الملك والشعب'],
        ['date' => '2025-08-21', 'name_en' => 'Youth Day', 'name_fr' => 'Fête de la Jeunesse', 'name_ar' => 'عيد الشباب'],
        ['date' => '2025-09-05', 'name_en' => 'Mawlid al-Nabi', 'name_fr' => 'Mawlid al-Nabi', 'name_ar' => 'المولد النبوي الشريف'],
        ['date' => '2025-11-06', 'name_en' => 'Green March Anniversary', 'name_fr' => 'Anniversaire de la Marche Verte', 'name_ar' => 'ذكرى المسيرة الخضراء'],
        ['date' => '2025-11-18', 'name_en' => 'Independence Day', 'name_fr' => 'Fête de l’Indépendance', 'name_ar' => 'عيد الاستقلال'],
    ];
}
