<?php

namespace App\Models;

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

class Challan extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'challan_no', 'challan_date', 'party_id', 'sale_id',
        'vehicle_no', 'driver_name', 'driver_phone', 'transport',
        'status', 'delivery_date', 'remarks',
    ];

    protected $casts = [
        'challan_date'  => 'date',
        'delivery_date' => 'date',
    ];

    protected static function booted()
    {
        static::creating(function ($challan) {
            if (empty($challan->challan_no)) {
                $challan->challan_no = static::generateChallanNo();
            }
        });
    }

    public static function generateChallanNo(): string
    {
        $prefix = 'CHN-';
        $year   = date('Y');
        $latest = static::where('challan_no', 'like', "{$prefix}{$year}-%")
            ->orderBy('id', 'desc')
            ->first();

        $number = $latest ? ((int) substr($latest->challan_no, -3) + 1) : 1;
        return $prefix . $year . '-' . str_pad($number, 3, '0', STR_PAD_LEFT);
    }

    public function party()
    {
        return $this->belongsTo(Party::class);
    }

    public function sale()
    {
        return $this->belongsTo(Sale::class);
    }
}
