<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class WorkOrder extends Model
{
    use HasFactory;

    protected $fillable = [
        'work_order_number',
        'job_card_id',
        'estimate_id',
        'service_coordinator_id',
        'assigned_technician_id',
        'priority',
        'status',
        'work_description',
        'special_instructions',
        'safety_requirements',
        'estimated_start_time',
        'estimated_completion_time',
        'actual_start_time',
        'actual_completion_time',
        'quality_check_required',
        'quality_checked_by_id',
        'quality_check_date',
        'quality_check_notes',
        'customer_notification_required',
        'notes',
        'completion_percentage',
    ];

    protected $casts = [
        'estimated_start_time' => 'datetime',
        'estimated_completion_time' => 'datetime',
        'actual_start_time' => 'datetime',
        'actual_completion_time' => 'datetime',
        'quality_check_date' => 'datetime',
        'quality_check_required' => 'boolean',
        'customer_notification_required' => 'boolean',
        'completion_percentage' => 'decimal:2',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($workOrder) {
            if (empty($workOrder->work_order_number)) {
                $workOrder->work_order_number = 'WO-' . date('Y') . '-' . str_pad(
                    static::whereYear('created_at', now()->year)->count() + 1, 
                    6, 
                    '0', 
                    STR_PAD_LEFT
                );
            }
        });
    }

    public function jobCard(): BelongsTo
    {
        return $this->belongsTo(JobCard::class);
    }

    public function estimate(): BelongsTo
    {
        return $this->belongsTo(Estimate::class);
    }

    public function serviceCoordinator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'service_coordinator_id');
    }

    public function assignedTechnician(): BelongsTo
    {
        return $this->belongsTo(Technician::class, 'assigned_technician_id');
    }

    public function qualityCheckedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'quality_checked_by_id');
    }

    public function timesheets(): HasMany
    {
        return $this->hasMany(Timesheet::class);
    }

    public function tasks(): HasMany
    {
        return $this->hasMany(WorkOrderTask::class);
    }

    public function parts(): BelongsToMany
    {
        return $this->belongsToMany(Part::class, 'work_order_parts')
            ->withPivot(['quantity_used', 'unit_cost', 'status', 'allocated_at', 'used_at'])
            ->withTimestamps();
    }
}
