<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Absensi extends Model
{
    use HasFactory;

    protected $table = 'absensi';

    protected $fillable = [
        'user_id',
        'admin_id',
        'nama_admin',
        'lokasi_input',
        'nama_karyawan',
        'tanggal',
        'jam_masuk',
        'foto_masuk',
        'jam_pulang',
        'foto_pulang',
        'total_jam',
        'jam_lembur',
        'status',
        'keterangan',
        'lokasi',
        'tipe_input',
    ];

    protected $casts = [
        'tanggal' => 'date',
        // 'jam_masuk' => 'datetime',
        // 'jam_pulang' => 'datetime',
        'total_jam' => 'decimal:2',
        'jam_lembur' => 'decimal:2',
    ];

    /**
     * Get the user that owns the attendance record.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Calculate total working hours
     */
    public function hitungTotalJam()
    {
        if ($this->jam_masuk && $this->jam_pulang) {
            $tanggal = $this->tanggal instanceof \Carbon\Carbon ? $this->tanggal->format('Y-m-d') : $this->tanggal;

            // Gunakan langsung jika sudah Carbon, jika tidak, parse
            $masuk = $this->jam_masuk instanceof \Carbon\Carbon
                ? $this->jam_masuk
                : (strpos($this->jam_masuk, ' ') !== false
                    ? \Carbon\Carbon::parse($this->jam_masuk)
                    : \Carbon\Carbon::parse($tanggal . ' ' . $this->jam_masuk));

            $pulang = $this->jam_pulang instanceof \Carbon\Carbon
                ? $this->jam_pulang
                : (strpos($this->jam_pulang, ' ') !== false
                    ? \Carbon\Carbon::parse($this->jam_pulang)
                    : \Carbon\Carbon::parse($tanggal . ' ' . $this->jam_pulang));

            if ($pulang->lessThan($masuk)) {
                $pulang->addDay();
            }

            $jamKerjaMulai = $masuk->copy()->setTime(9, 0, 0);
            $masukEfektif = $masuk->lt($jamKerjaMulai) ? $jamKerjaMulai : $masuk;

            if ($pulang->lte($masukEfektif)) {
                $this->total_jam = 0;
                $this->jam_lembur = 0;
            } else {
                $totalMenit = $pulang->diffInMinutes($masukEfektif, true); // hasil selalu positif
                $this->total_jam = round($totalMenit / 60, 2);
                $jamKerjaNormal = 8;
                if ($this->total_jam > $jamKerjaNormal) {
                    $this->jam_lembur = round($this->total_jam - $jamKerjaNormal, 2);
                } else {
                    $this->jam_lembur = 0;
                }
            }
            $this->save();
        }
    }

    /**
     * Check if attendance is complete (has both check-in and check-out)
     */
    public function isLengkap()
    {
        return $this->jam_masuk && $this->jam_pulang;
    }

    /**
     * Get formatted working hours
     */
    public function getTotalJamFormatted()
    {
        $jam = floor(abs($this->total_jam));
        $menit = round((abs($this->total_jam) - $jam) * 60);
        return "{$jam} jam {$menit} menit";
    }

    /**
     * Get formatted overtime hours
     */
    public function getJamLemburFormatted()
    {
        $jam = floor($this->jam_lembur);
        $menit = round(($this->jam_lembur - $jam) * 60);
        return "{$jam} jam {$menit} menit";
    }
}
