<?php

namespace App\Models;

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

class Order extends Model
{
    use HasFactory;

    protected $table = 'orders';
    protected $primaryKey = 'order_id';

    protected $fillable = [
        'user_id',
        'status',
        'total_price',
        'order_note',
        // Kolom pengiriman baru (dari migration)
        'tracking_number',
        'courier_code',
        'courier_name',
        'shipping_cost',
        'total_weight',
        'estimated_days',
        'shipping_zone',
        'address_id',
    ];

    protected $casts = [
        'total_price'   => 'decimal:2',
        'shipping_cost' => 'integer',
        'total_weight'  => 'integer',
        'created_at'    => 'datetime',
        'updated_at'    => 'datetime',
    ];

    // ── Relationships ──────────────────────────────────────────────────────────

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function items()
    {
        return $this->hasMany(OrderItem::class, 'order_id', 'order_id');
    }

    public function payment()
    {
        return $this->hasOne(Payment::class, 'order_id', 'order_id');
    }

    public function stockHistories()
    {
        return $this->morphMany(StockHistory::class, 'reference');
    }

    public function address()
    {
        return $this->belongsTo(\App\Models\Address::class, 'address_id');
    }

    // ── Status Constants ───────────────────────────────────────────────────────

    const STATUS_PROCESSING = 'processing'; // Pesanan disiapkan / COD langsung proses
    const STATUS_SHIPPED    = 'shipped';    // Sudah dikirim, dalam perjalanan
    const STATUS_DELIVERED  = 'delivered';  // Tiba di kota / sedang diantar
    const STATUS_COMPLETED  = 'completed';  // Diterima customer, selesai
    const STATUS_CANCELLED  = 'cancelled';  // Dibatalkan

    // ── Status Scopes ──────────────────────────────────────────────────────────

    public function scopeProcessing($query) { return $query->where('status', self::STATUS_PROCESSING); }
    public function scopeShipped($query)    { return $query->where('status', self::STATUS_SHIPPED); }
    public function scopeDelivered($query)  { return $query->where('status', self::STATUS_DELIVERED); }
    public function scopeCompleted($query)  { return $query->where('status', self::STATUS_COMPLETED); }
    public function scopeCancelled($query)  { return $query->where('status', self::STATUS_CANCELLED); }

    // ── Status Check Methods ───────────────────────────────────────────────────

    public function isProcessing() { return $this->status === self::STATUS_PROCESSING; }
    public function isShipped()    { return $this->status === self::STATUS_SHIPPED; }
    public function isDelivered()  { return $this->status === self::STATUS_DELIVERED; }
    public function isCompleted()  { return $this->status === self::STATUS_COMPLETED; }
    public function isCancelled()  { return $this->status === self::STATUS_CANCELLED; }

    // Alias agar controller lama yang pakai isProcess() tidak error
    public function isProcess()    { return $this->isProcessing(); }

    // ── Status Update Methods ──────────────────────────────────────────────────

    public function markAsShipped()   { $this->update(['status' => self::STATUS_SHIPPED]); }
    public function markAsDelivered() { $this->update(['status' => self::STATUS_DELIVERED]); }
    public function markAsCompleted() { $this->update(['status' => self::STATUS_COMPLETED]); }
    public function markAsCancelled() { $this->update(['status' => self::STATUS_CANCELLED]); }

    // ── Accessors ──────────────────────────────────────────────────────────────

    public function getStatusBadgeAttribute(): string
    {
        return [
            'processing' => 'badge-warning',
            'shipped'    => 'badge-primary',
            'delivered'  => 'badge-info',
            'completed'  => 'badge-success',
            'cancelled'  => 'badge-danger',
        ][$this->status] ?? 'badge-secondary';
    }

    public function getStatusTextAttribute(): string
    {
        return [
            'processing' => 'Sedang Diproses',
            'shipped'    => 'Dikirim',
            'delivered'  => 'Dalam Pengantaran',
            'completed'  => 'Selesai',
            'cancelled'  => 'Dibatalkan',
        ][$this->status] ?? $this->status;
    }

    /**
     * Langkah tracking yang sudah selesai berdasarkan status saat ini.
     * Dipakai oleh view order.show (user).
     */
    public function getCompletedTrackingSteps(): array
    {
        $steps = [
            'processing' => ['processing'],
            'shipped'    => ['processing', 'shipped'],
            'delivered'  => ['processing', 'shipped', 'delivered'],
            'completed'  => ['processing', 'shipped', 'delivered', 'completed'],
            'cancelled'  => ['cancelled'],
        ];

        return $steps[$this->status] ?? [];
    }

        /**
     * Nama kurir yang bersih untuk ditampilkan ke user.
     */
    public function getCourierDisplayAttribute(): string
    {
        if ($this->courier_name) {
            return $this->courier_name;
        }
        if ($this->courier_code) {
            return strtoupper(str_replace('_', ' ', $this->courier_code));
        }
        return '-';
    }
 
    /**
     * URL tracking di website ekspedisi.
     */
    public function getTrackingUrlAttribute(): ?string
    {
        if (!$this->tracking_number || !$this->courier_code) {
            return null;
        }
 
        $resi = urlencode($this->tracking_number);
 
        // Tentukan prefix kurir
        if (str_starts_with($this->courier_code, 'jne')) {
            return "https://www.jne.co.id/id/tracking/trace?awbNumber={$resi}";
        }
        if (str_starts_with($this->courier_code, 'jnt')) {
            return "https://www.jet.co.id/track?awb={$resi}";
        }
        if (str_starts_with($this->courier_code, 'sicepat')) {
            return "https://www.sicepat.com/checkAwb?awb={$resi}";
        }
 
        return null;
    }
 
    /**
     * Apakah sudah ada nomor resi.
     */
    public function hasTrackingNumber(): bool
    {
        return !empty($this->tracking_number);
    }
 
    /**
     * Label status pengiriman lebih deskriptif.
     */
    public function getShippingStatusTextAttribute(): string
    {
        return match ($this->status) {
            'processing' => 'Sedang Dikemas',
            'shipped'    => 'Dalam Perjalanan',
            'delivered'  => 'Hampir Tiba',
            'completed'  => 'Telah Diterima',
            'cancelled'  => 'Dibatalkan',
            default      => ucfirst($this->status),
        };
    }
 
    /**
     * Apakah ongkir gratis.
     */
    public function getIsFreeShippingAttribute(): bool
    {
        return (int) $this->shipping_cost === 0 &&
               isset($this->total_price) &&
               (float) $this->total_price > 0;
    }
 
    /**
     * Subtotal produk saja (total_price - shipping_cost).
     */
    public function getProductSubtotalAttribute(): float
    {
        return max(0, (float) $this->total_price - (int) $this->shipping_cost);
    }
}