<?php

namespace App\Models;

use CodeIgniter\Model;

class RevisiModel extends Model
{
    protected $table            = 'tabel_revisi';
    protected $primaryKey       = 'id_revisi';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'no_order_custom',
        'user_id',
        'user_name',
        'perubahan_data',
    ];

    // 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 = true;

    /**
     * Get revisions by order number
     */
    public function getRevisionsByOrder($noOrderCustom, $userRole = null, $userId = null)
    {
        $builder = $this->where('no_order_custom', $noOrderCustom);

        // Filter by user for customers
        if ($userRole === 'customer' && $userId) {
            $builder->where('user_id', $userId);
        }

        return $builder->orderBy('created_at', 'DESC')->findAll();
    }

    /**
     * Save revision record
     */
    public function saveRevision($noOrderCustom, $userId, $userName, $changesData)
    {
        return $this->insert([
            'no_order_custom' => $noOrderCustom,
            'user_id'         => $userId,
            'user_name'       => $userName,
            'perubahan_data'  => json_encode($changesData),
        ]);
    }
}
