<?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;

class GasOrder extends Model
{
    use HasFactory;

    protected $fillable = [
        'customer_id',
        'driver_id',
        'gas_office_id',
        'order_number',
        'subtotal',
        'delivery_fee',
        'tax',
        'total',
        'platform_fee',
        'platform_fee_calculated',
        'delivery_address',
        'delivery_latitude',
        'delivery_longitude',
        'status',
        'preferred_delivery_time',
        'actual_delivery_time',
        'special_instructions',
        'payment_method',
        'payment_status',
        'is_urgent',
        'customer_rating',
        'customer_feedback',
        'wheel_milestone_pending',
        'wheel_promo_fee_amount',
        'wheel_result',
        'wheel_spun_at',
    ];

    protected $casts = [
        'subtotal' => 'decimal:2',
        'delivery_fee' => 'decimal:2',
        'tax' => 'decimal:2',
        'total' => 'decimal:2',
        'platform_fee' => 'decimal:2',
        'platform_fee_calculated' => 'boolean',
        'delivery_latitude' => 'decimal:8',
        'delivery_longitude' => 'decimal:8',
        'customer_rating' => 'decimal:2',
        'is_urgent' => 'boolean',
        'preferred_delivery_time' => 'datetime',
        'actual_delivery_time' => 'datetime',
        'wheel_milestone_pending' => 'boolean',
        'wheel_promo_fee_amount' => 'decimal:2',
        'wheel_result' => 'integer',
        'wheel_spun_at' => 'datetime',
    ];

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

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

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

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

    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeByCustomer($query, $customerId)
    {
        return $query->where('customer_id', $customerId);
    }

    public function scopeUrgent($query)
    {
        return $query->where('is_urgent', true);
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeActive($query)
    {
        return $query->whereIn('status', ['pending', 'confirmed', 'preparing', 'picked_up']);
    }

    /**
     * Get platform fee record for this order.
     */
    public function platformFee()
    {
        return $this->morphOne(PlatformFee::class, 'order', 'order_type', 'order_id');
    }
}
