<?php

namespace App\Models;

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

class KurirAssignment extends Model
{
    use HasFactory;

    protected $table = 'kurir_assignments';

    protected $fillable = [
        'pesanan_id',
        'kurir_id',
        'status',
        'catatan',
        'foto_bukti',
        'tanggal_diterima'
    ];

    protected $casts = [
        'tanggal_diterima' => 'datetime',
        'created_at'       => 'datetime',
        'updated_at'       => 'datetime'
    ];

    /**
     * Relasi ke pesanan
     */
    public function pesanan()
    {
        return $this->belongsTo(Pesanan::class);
    }

    /**
     * Relasi ke kurir (user) - pakai foreign key kurir_id ke primary key ID
     */
    public function kurir()
    {
        return $this->belongsTo(User::class, 'kurir_id', 'ID');
    }

    /**
     * Get status badge color
     */
    public function getStatusColorAttribute()
    {
        return match($this->status) {
            'ditugaskan' => 'info',
            'dijemput'   => 'warning',
            'diantar'    => 'primary',
            'selesai'    => 'success',
            default      => 'secondary'
        };
    }

    /**
     * Get status icon
     */
    public function getStatusIconAttribute()
    {
        return match($this->status) {
            'ditugaskan' => 'fa-clipboard-list',
            'dijemput'   => 'fa-box',
            'diantar'    => 'fa-truck',
            'selesai'    => 'fa-check-circle',
            default      => 'fa-circle'
        };
    }

    /**
     * Cek apakah assignment bisa diupdate ke status tertentu
     */
    public function canUpdateTo($newStatus)
    {
        return match($this->status) {
            'ditugaskan' => $newStatus === 'dijemput',
            'dijemput'   => $newStatus === 'diantar',
            'diantar'    => $newStatus === 'selesai',
            default      => false
        };
    }

    /**
     * Get daftar status selanjutnya yang tersedia
     */
    public function getNextStatusesAttribute()
    {
        return match($this->status) {
            'ditugaskan' => ['dijemput'],
            'dijemput'   => ['diantar'],
            'diantar'    => ['selesai'],
            default      => []
        };
    }
}