<?php

namespace App\Models;

use CodeIgniter\Model;

class ProductionModel extends Model
{
    protected $table      = 'productions';
    protected $primaryKey = 'id_production';
    protected $returnType = 'array';

    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    protected $allowedFields = [
        'id_order',
        'scheduled_month',
        'production_number',
        'start_date',
        'finish_date',
        'status',
        'progress',
        'notes',
    ];

    public function generateProductionNumber(): string
    {
        $prefix = 'PRD-' . date('Ymd') . '-';

        $last = $this->like('production_number', $prefix, 'after')
            ->orderBy('id_production', 'DESC')
            ->first();

        if (!$last) {
            return $prefix . '0001';
        }

        $lastNumber = (int) substr($last['production_number'], -4);

        return $prefix . str_pad($lastNumber + 1, 4, '0', STR_PAD_LEFT);
    }
}
