<?php

namespace App\Models;

use CodeIgniter\Model;

class PengirimanModel extends Model
{
    protected $table            = 'tabel_pengiriman';
    protected $primaryKey       = 'kode_pengiriman';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $allowedFields    = [
        'kode_permintaan_custom',
        'no_pengiriman',
        'tanggal_pengiriman',
        'id_customer',
        'created_at',
        'created_by_role',
        'updated_at',
        'updated_by_role',
        'proses_at',
        'sampai_at',
        'status'
    ];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = false;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = false;

    // Callbacks
    protected $allowCallbacks = false;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function generatePengirimanNumber(string $prefix = 'KRM'): string
    {
        $datePart = date('Ymd');

        $fullPrefix = "{$prefix}/{$datePart}/";

        $latestInvoice = $this->db->table($this->table)
            ->like('no_pengiriman', $fullPrefix, 'after')
            ->orderBy('no_pengiriman', 'DESC')
            ->get(1)
            ->getRow();

        $lastNumber = 0;

        if ($latestInvoice) {
            $lastInvoiceNumber = $latestInvoice->no_pengiriman;
            $lastNumber = (int) substr($lastInvoiceNumber, -6);
        }

        $newNumber = $lastNumber + 1;
        $paddedNumber = str_pad($newNumber, 6, '0', STR_PAD_LEFT);

        $invoiceNumber = "{$prefix}/{$datePart}/{$paddedNumber}";

        return $invoiceNumber;
    }
}
