<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Shipment extends Model
{
    // ambil koneksi database kedua
    protected $connection = 'mysql_second';
    protected $table = 'air_way_bill_web_trackings_new';
    public $timestamps = false; 

    protected $fillable = [
        'id', 
        'air_way_bill_id', 
        'awb_number', 
        'customer_name', 
        'customer_city', 
        'customer_region', 
        'awb_number_code', 
        'date', 
        'status', 
        'receiver_name', 
        'receiver_city', 
        'receiver_region', 
        'received_by', 
        'received_date', 
        'ref_number', 
        'sent', 
        'status_description', 
        'last_update', 
        'url_img'
    ];

    protected $casts = [
        'date' => 'datetime',
        'received_date' => 'datetime',
        'last_update' => 'datetime',
        'sent' => 'boolean', // tinyint(1) biasanya boolean
    ];

    // --- ACCESSORS (Mapping Data agar Frontend React/Blade tidak error) ---
    
    public function getAwbAttribute() { return $this->awb_number; }
    public function getShipperAttribute() { return $this->customer_name; }
    public function getOriginAttribute() { return $this->customer_city; }
    public function getConsigneeAttribute() { return $this->receiver_name; }
    public function getDestinationAttribute() { return $this->receiver_city; }
    public function getImageUrlAttribute() { return $this->url_img; }
    
    // Mapping description history
    public function getDescriptionAttribute() { return $this->status_description; }
    
    /**
     * Mapping timestamp history.
     * PENTING: Ini hanya untuk OUTPUT JSON/Blade ($item->timestamp).
     * TIDAK BISA dipakai untuk sorting SQL (orderBy timestamp).
     * Untuk sorting, gunakan nama kolom asli: 'date'.
     */
    public function getTimestampAttribute() { return $this->date; }

    /**
     * RELASI HISTORY (SELF JOIN)
     * Mengambil semua baris dengan awb_number yang sama sebagai history.
     */
    public function history()
    {
        return $this->hasMany(Shipment::class, 'awb_number', 'awb_number')
                    ->orderBy('date', 'desc'); // PENTING: Pakai 'date', bukan 'timestamp'
    }
}