<?php

namespace App\Models;

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

class Visit extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'employee_id', 'client_id', 'governorate_id', 'city_id', 'area',
        'latitude', 'longitude', 'scheduled_date', 'scheduled_time', 'status',
        'started_at', 'completed_at', 'comments', 'employee_notes',
        'location_history', 'last_location_update', 'scheduled_end',
        'current_latitude', 'current_longitude', 'current_address',
        'checkpoints', 'start_latitude', 'start_longitude',
        'destination_latitude', 'destination_longitude'
    ];

    protected $casts = [
        'scheduled_date' => 'date',
        'scheduled_end' => 'datetime',
        'started_at' => 'datetime',
        'completed_at' => 'datetime',
        'latitude' => 'decimal:8',
        'longitude' => 'decimal:8',
        'current_latitude' => 'decimal:8',
        'current_longitude' => 'decimal:8',
        'location_history' => 'array',
        'checkpoints' => 'array',
        'last_location_update' => 'datetime'
    ];

    public function employee()
    {
        return $this->belongsTo(User::class, 'employee_id');
    }

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function governorate()
    {
        return $this->belongsTo(Governorate::class);
    }

    public function city()
    {
        return $this->belongsTo(City::class);
    }
    
    // Add this method to safely check if scheduled_end exists
    public function hasScheduledEnd()
    {
        return !empty($this->scheduled_end);
    }
}