<?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 Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class Attendance extends Model implements Auditable
{
    use HasFactory, \OwenIt\Auditing\Auditable;

    protected $fillable = [
        'uid',
        'name',
        'status',
        'employee',
        'employee_id',
        'employee_pid',
        'type',
        'date',
        'start',
        'break',
        'breakDuration',
        'end',
        'lateWith',
        'outEarlierWith',
        'workedRegularHours',
        'workedSuppDayHours',
        'workedSuppNightHours',
        'workedSuppHolyDaysHours',
        'workedWeekendHours',
        'comment',
    ];

    protected $casts = [
        'date' => 'datetime',
        'start' => 'datetime',
        'end' => 'datetime',
        'break' => 'datetime',
    ];


    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) {
            // Generate UID if not set
            if (empty($model->uid)) {
                $model->uid = (string) Str::ulid();
            }

            // Safely extract employee info
            if (!empty($model->employee)) {
                $employee = $model->employee;

                $model->name = $employee['name'] ?? null;
                $model->employee_id = $employee['id'] ?? null;
                $model->employee_pid = $employee['pid'] ?? null;
            }

            // Compute break duration
            if (!empty($model->break)) {
                $model->breakDuration = self::convertTimeToHours($model->break);
            }

            // Calculate worked regular hours
            if (!empty($model->start) && !empty($model->end)) {
                $model->workedRegularHours = self::convertTimeToHours($model->end)
                    - self::convertTimeToHours($model->start)
                    - ($model->breakDuration ?? 0);
            }
        });

        static::updating(function ($model) {
            // Update employee info safely
            if ($model->isDirty('employee') && !empty($model->employee)) {
                $employee = $model->employee;

                $model->name = $employee['name'] ?? null;
                $model->employee_id = $employee['id'] ?? null;
                $model->employee_pid = $employee['pid'] ?? null;
            }

            // Update break duration if break changed
            if ($model->isDirty('break') && !empty($model->break)) {
                $model->breakDuration = self::convertTimeToHours($model->break);
            }

            // Recalculate worked hours if start or end changed
            if ($model->isDirty('start') || $model->isDirty('end')) {
                $model->workedRegularHours =
                    (self::convertTimeToHours($model->end) ?? 0)
                    - (self::convertTimeToHours($model->start) ?? 0)
                    - ($model->breakDuration ?? 0);
            }
        });
    }



    protected static function convertTimeToHours($datetime)
    {
        try {
            $time = Carbon::parse($datetime);

            // Extract hours and minutes only
            $hours = $time->format('H');
            $minutes = $time->format('i');

            return floatval($hours) + (floatval($minutes) / 60);
        } catch (\Exception $e) {
            return 0;
        }
    }


}
