<?php

namespace App\Models;

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

class Job extends Model
{
    use SoftDeletes;

    protected $table = 'crm_jobs';

    protected $fillable = [
        'job_number', 'lead_id', 'contact_id', 'consultant_id', 'manager_id', 'designer_id',
        'stage', 'status', 'priority', 'source', 'project_type', 'design_style',
        'num_rooms', 'budget', 'job_value', 'deposit_amount', 'deposit_paid',
        'cm_paid', 'delivery_paid', 'final_paid', 'sale_date', 'expected_completion',
        'actual_completion', 'warranty_expiry', 'description', 'notes', 'next_action',
        'site_address', 'site_suburb', 'site_state', 'site_postcode',
    ];

    protected $casts = [
        'sale_date' => 'date',
        'expected_completion' => 'date',
        'actual_completion' => 'date',
        'warranty_expiry' => 'date',
        'deposit_paid' => 'boolean',
        'cm_paid' => 'boolean',
        'delivery_paid' => 'boolean',
        'final_paid' => 'boolean',
        'budget' => 'decimal:2',
        'job_value' => 'decimal:2',
        'deposit_amount' => 'decimal:2',
    ];

    public function contact() { return $this->belongsTo(Contact::class); }
    public function lead() { return $this->belongsTo(Lead::class); }
    public function consultant() { return $this->belongsTo(User::class, 'consultant_id'); }
    public function manager() { return $this->belongsTo(User::class, 'manager_id'); }
    public function designer() { return $this->belongsTo(User::class, 'designer_id'); }
    public function quotes() { return $this->hasMany(Quote::class); }
    public function quote() { return $this->hasOne(Quote::class)->latestOfMany(); }
    public function contracts() { return $this->hasMany(Contract::class); }
    public function contract() { return $this->hasOne(Contract::class)->latestOfMany(); }
    public function checkMeasures() { return $this->hasMany(CheckMeasure::class); }
    public function checkMeasure() { return $this->hasOne(CheckMeasure::class)->latestOfMany(); }
    public function deliveries() { return $this->hasMany(Delivery::class); }
    public function installations() { return $this->hasMany(Installation::class); }
    public function completions() { return $this->hasMany(Completion::class); }
    public function productionOrders() { return $this->hasMany(ProductionOrder::class); }
    public function worksOrders() { return $this->hasMany(WorksOrder::class); }
    public function timeEntries() { return $this->hasMany(TimeEntry::class); }
    public function variants() { return $this->hasMany(JobVariant::class); }
    public function jobInvoices() { return $this->hasMany(JobInvoice::class); }
    public function jobPoAllocations() { return $this->hasMany(JobPoAllocation::class); }

    /**
     * Trades users assigned to this job (pivot: job_trade_assignments).
     */
    public function tradeUsers()
    {
        return $this->belongsToMany(User::class, 'job_trade_assignments', 'job_id', 'user_id')
                    ->withTimestamps();
    }

    public function poAllocations() { return $this->hasMany(JobPoAllocation::class, 'job_id'); }
    public function processingOrders() { return $this->hasMany(ProcessingOrder::class); }
    public function tasks() { return $this->hasMany(Task::class); }

    public function getJobNumberPrefixAttribute(): string
    {
        return strtoupper(substr($this->job_number, 0, 1));
    }

    public function stageStep(): int
    {
        $stages = ['lead','consult','sold','contracts','cm','processing','delivery','installation','completion'];
        $idx = array_search($this->stage, $stages);
        return $idx !== false ? $idx + 1 : 1;
    }

    public function stageLabel(): string
    {
        return match($this->stage) {
            'lead'         => 'Lead',
            'consult'      => 'Consult',
            'sold'         => 'Sold',
            'contracts'    => 'Contracts',
            'cm'           => 'Check Measure',
            'processing'   => 'Processing',
            'delivery'     => 'Delivery',
            'installation' => 'Installation',
            'completion'   => 'Completion',
            default        => ucfirst($this->stage),
        };
    }

    public function stageColor(): string
    {
        return match($this->stage) {
            'lead'         => 'blue',
            'consult'      => 'purple',
            'sold'         => 'green',
            'contracts'    => 'yellow',
            'cm'           => 'orange',
            'processing'   => 'indigo',
            'delivery'     => 'teal',
            'installation' => 'emerald',
            'completion'   => 'gray',
            default        => 'gray',
        };
    }
}
