<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\User;
use App\Models\Warehouse;
use App\Models\PartyType;

class Supplier extends Model
{
    use SoftDeletes;

    /** Non-standard table name */
    protected $table = 'rm_suppliers';

    /** Primary key (defaults are fine, kept explicit for clarity) */
    protected $primaryKey = 'id';
    public $incrementing = true;
    protected $keyType = 'int';

    /** Mass-assignable columns */
    protected $fillable = [
        'supplierid',
        'name',
        'account_id',
        'company_name',
        'personal_phone',
        'bussiness_phone',
        'supplier_type',
        'email',
        'address',
        'opening_balance',
        'current_balance',
        'due_limit',
        'remarks',
        'discount_type',
        'discount',
        'assume_rate',
        'image',
        'status',
        'created_by',
        'updated_by',
        'party_type_id',
        'bag_warehouse_id',
        'bag_opening',
    ];

    /** Appended accessors */
    protected $appends = ['image_url'];

    /** Default attributes (extra safety) */
    protected $attributes = [
        'current_balance' => 0.00,
        'status'          => 0,
    ];

    /** Useful type casts */
    protected $casts = [
        'opening_balance'  => 'decimal:2',
        'current_balance'  => 'decimal:2',
        'due_limit'        => 'decimal:2',
        'discount'         => 'decimal:2',
        'assume_rate'      => 'decimal:4',
        'bag_opening'      => 'decimal:2',
        'status'           => 'integer',
        'party_type_id'    => 'integer',
        'bag_warehouse_id' => 'integer',
        'created_by'       => 'integer',
        'updated_by'       => 'integer',
        'bussiness_phone'  => 'integer',
    ];

    /* ===================== Relationships ===================== */

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

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

    public function bagWarehouse()
    {
        return $this->belongsTo(Warehouse::class, 'bag_warehouse_id');
    }

    public function partyType()
    {
        return $this->belongsTo(PartyType::class, 'party_type_id');
    }

    /* ===================== Accessors ===================== */

    /**
     * Public URL for the supplier image (if stored as path).
     */
    public function getImageUrlAttribute(): ?string
    {
        $img = $this->image ?? null;
        if (!$img) return null;

        // If already a full URL, return as-is
        if (str_starts_with($img, 'http://') || str_starts_with($img, 'https://')) {
            return $img;
        }

        // Relative path stored
        return asset($img);
    }

    /* ===================== Mutators / Guards ===================== */

    /**
     * ❗ Never allow changing supplierid once the model exists.
     *    This prevents accidental NULL/overwrite on update.
     */
    public function setSupplieridAttribute($value): void
    {
        if ($this->exists) {
            // Ignore any attempt to change supplierid on updates
            return;
        }
        $this->attributes['supplierid'] = $value;
    }

    /* ===================== Model Events ===================== */

    protected static function booted(): void
    {
        static::creating(function (self $m) {
            if ($uid = auth()->id()) {
                $m->created_by = $m->created_by ?? $uid;
                $m->updated_by = $m->updated_by ?? $uid;
            }
        });

        static::updating(function (self $m) {
            if ($uid = auth()->id()) {
                $m->updated_by = $uid;
            }
        });
    }
}
