<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\MaintenanceSchedule;

class ElevatorMaintenance extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_id',
        'elevator_id',
        'schedule_id',
        'maintenance_type',
        'description',
        'scheduled_date',
        'completion_date',
        'technician_id',
        'estimated_duration',
        'actual_duration',
        'priority',
        'status',
        'notes',
        'created_by',
        'completed_by',
    ];

    protected $casts = [
        'scheduled_date' => 'datetime',
        'completion_date' => 'datetime',
    ];

    /**
     * Get the elevator that owns the maintenance.
     */
    public function elevator()
    {
        return $this->belongsTo(Elevator::class);
    }

    /**
     * Get the technician that is assigned to the maintenance.
     */
    public function technician()
    {
        return $this->belongsTo(User::class, 'technician_id');
    }

    /**
     * Get the user that created the maintenance.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get the user that completed the maintenance.
     */
    public function completedBy()
    {
        return $this->belongsTo(User::class, 'completed_by');
    }

    /**
     * Get the maintenance schedule that generated this maintenance operation.
     * 
     * Nota: Este método ahora soporta tanto ElevatorMaintenanceSchedule como MaintenanceSchedule
     * dependiendo del tipo de programación que generó esta operación de mantenimiento.
     */
    public function schedule()
    {
        // Primero intentamos buscar en las programaciones periódicas (deshabilitadas)
        $schedule = $this->belongsTo(ElevatorMaintenanceSchedule::class, 'schedule_id')->first();

        // Si no encontramos nada, buscamos en las programaciones vinculadas a contratos
        if (!$schedule) {
            $schedule = $this->belongsTo(MaintenanceSchedule::class, 'schedule_id')->first();
        }

        return $schedule;
    }

    /**
     * Get the maintenance contract schedule that generated this maintenance operation.
     */
    public function maintenanceSchedule()
    {
        return $this->belongsTo(MaintenanceSchedule::class, 'schedule_id');
    }

    /**
     * Get the company that owns the maintenance.
     */
    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Get the parts used in this maintenance.
     */
    public function parts()
    {
        return $this->belongsToMany(ElevatorPart::class, 'maintenance_parts', 'maintenance_id', 'part_id')
            ->withPivot('quantity')
            ->withTimestamps();
    }

    /**
     * Get the attachments for this maintenance.
     */
    public function attachments()
    {
        return $this->hasMany(MaintenanceAttachment::class, 'maintenance_id');
    }

    /**
     * Get the maintenance type name in Arabic.
     *
     * @return string
     */
    public function getMaintenanceTypeName()
    {
        $types = [
            'preventive' => 'صيانة دورية',
            'corrective' => 'صيانة أعطال',
            'emergency' => 'صيانة طارئة',
            'inspection' => 'فحص دوري',
            'upgrade' => 'ترقية',
        ];

        return $types[$this->maintenance_type] ?? $this->maintenance_type;
    }

    /**
     * Check if this maintenance is for a breakdown/fault repair.
     *
     * @return bool
     */
    public function isBreakdownMaintenance()
    {
        return $this->maintenance_type === 'corrective' || $this->maintenance_type === 'emergency';
    }

    /**
     * Check if this maintenance is a periodic/scheduled maintenance.
     *
     * @return bool
     */
    public function isPeriodicMaintenance()
    {
        return $this->maintenance_type === 'preventive' || $this->maintenance_type === 'inspection';
    }
}
