<?php

namespace App\Models;

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

class SmartAttendance extends Model
{
    use HasFactory;

    protected $table = 'smart_attendances';
    
    protected $fillable = [
        'card_id',
        'student_id',
        'teacher_id',
        'attendance_date',
        'check_in_time',
        'check_out_time',
        'check_in_method', // card, fingerprint, face, manual
        'check_out_method',
        'check_in_device_id',
        'check_out_device_id',
        'status', // present, absent, late, half-day, holiday
        'working_hours',
        'overtime_hours',
        'latitude',
        'longitude',
        'location_name',
        'temperature',
        'remarks',
        'synced'
    ];

    protected $casts = [
        'attendance_date' => 'date',
        'check_in_time' => 'datetime',
        'check_out_time' => 'datetime',
        'working_hours' => 'decimal:2',
        'overtime_hours' => 'decimal:2',
        'temperature' => 'decimal:2',
        'synced' => 'boolean'
    ];

    public function card()
    {
        return $this->belongsTo(SmartCard::class, 'card_id');
    }

    public function student()
    {
        return $this->belongsTo(Student::class);
    }

    public function teacher()
    {
        return $this->belongsTo(Teacher::class);
    }

    // Calculate working hours
    public function calculateWorkingHours()
    {
        if ($this->check_in_time && $this->check_out_time) {
            $hours = $this->check_in_time->diffInMinutes($this->check_out_time) / 60;
            return round($hours, 2);
        }
        return 0;
    }

    // Determine status based on check-in time
    public function determineStatus($startTime = '09:00')
    {
        if (!$this->check_in_time) {
            return 'absent';
        }

        $checkIn = $this->check_in_time->format('H:i');
        $start = \Carbon\Carbon::parse($startTime);

        if ($this->check_in_time->gt($start->addMinutes(30))) {
            return 'late';
        }

        return 'present';
    }

    // Attendance status types
    public static function getStatusTypes()
    {
        return [
            'present' => 'উপস্থিত',
            'absent' => 'অনুপস্থিত',
            'late' => 'বিলম্বে',
            'half-day' => 'অর্ধদিবস',
            'holiday' => 'ছুটি'
        ];
    }
}