<?php

namespace App\Models;

use App\Models\Concerns\HasPublicId;
use App\Support\Decimal;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class TransportJob extends Model
{
    use HasPublicId;

    protected $table = 'transport_jobs';
    protected $fillable = ['public_id','company_id','branch_id','customer_id','contract_id','service_type_id','route_id','job_number','job_date','requested_date','customer_po','pickup_location','delivery_location','cargo_description','quantity','weight','volume','number_of_trips','vehicle_type','estimated_revenue','estimated_cost','actual_revenue','actual_cost','tax_code_id','status','delivery_status','billing_status','vendor_billing_status','internal_notes','customer_notes','assigned_user_id','created_by'];
    protected function casts(): array { return ['job_date'=>'date','requested_date'=>'date','quantity'=>'decimal:4','weight'=>'decimal:4','volume'=>'decimal:4','estimated_revenue'=>'decimal:4','estimated_cost'=>'decimal:4','actual_revenue'=>'decimal:4','actual_cost'=>'decimal:4']; }
    public function company(): BelongsTo { return $this->belongsTo(Company::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function customer(): BelongsTo { return $this->belongsTo(Party::class, 'customer_id'); }
    public function contract(): BelongsTo { return $this->belongsTo(Contract::class); }
    public function serviceType(): BelongsTo { return $this->belongsTo(ServiceType::class); }
    public function route(): BelongsTo { return $this->belongsTo(TransportRoute::class); }
    public function taxCode(): BelongsTo { return $this->belongsTo(TaxCode::class); }
    public function assignedUser(): BelongsTo { return $this->belongsTo(User::class, 'assigned_user_id'); }
    public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); }
    public function trips(): HasMany { return $this->hasMany(Trip::class); }
    public function charges(): HasMany { return $this->hasMany(JobCharge::class); }
    public function costs(): HasMany { return $this->hasMany(JobCost::class); }
    public function pods(): HasMany { return $this->hasMany(ProofOfDelivery::class); }
    public function invoices(): HasMany { return $this->hasMany(CustomerInvoice::class); }
    public function vendorBills(): HasMany { return $this->hasMany(VendorBill::class); }
    public function getProfitAttribute(): string { return Decimal::subtract((string) $this->actual_revenue, (string) $this->actual_cost); }
    public function getProfitPercentageAttribute(): string { return Decimal::compare((string) $this->actual_revenue, '0') === 0 ? '0.0000' : Decimal::multiply(Decimal::divide((string) $this->profit, (string) $this->actual_revenue), '100'); }
}
