<?php

namespace App\Models;

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

class MaintenanceRequest extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'company_id',
        'branch_id',
        'elevator_id',
        'customer_id',
        'request_number',
        'title',
        'description',
        'problem_details',
        'priority',
        'status',
        'requested_date',
        'scheduled_date',
        'completed_date',
        'completion_notes',
        'is_emergency',
        'assigned_team_id',
        'assigned_user_id',
        'created_by',
        'notes',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'requested_date' => 'datetime',
        'scheduled_date' => 'datetime',
        'completed_date' => 'datetime',
        'is_emergency' => 'boolean',
    ];

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

    /**
     * Get the branch associated with the maintenance request.
     */
    public function branch()
    {
        return $this->belongsTo(Branch::class);
    }

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

    /**
     * Get the customer associated with the maintenance request.
     */
    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    /**
     * Get the team assigned to the maintenance request.
     */
    public function assignedTeam()
    {
        return $this->belongsTo(MaintenanceTeam::class, 'assigned_team_id');
    }

    /**
     * Get the user assigned to the maintenance request.
     */
    public function assignedUser()
    {
        return $this->belongsTo(User::class, 'assigned_user_id');
    }

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

    /**
     * Get the maintenance logs associated with this request.
     */
    public function maintenanceLogs()
    {
        return $this->hasMany(MaintenanceLog::class, 'request_id');
    }

    /**
     * For backward compatibility
     */
    public function assignedTo()
    {
        return $this->assignedUser();
    }

    /**
     * For backward compatibility
     */
    public function createdBy()
    {
        return $this->creator();
    }
}
