<?php defined('BASEPATH') or exit('No direct script access allowed');

class Progress_model extends CI_Model
{
    protected $table = 'transaksi_progress';

    public function get_by_invoice($id_invoice)
    {
        return $this->db->get_where($this->table, ['id_invoice' => (int)$id_invoice])->row_array();
    }

    public function save($id_invoice, array $indices, $pct, $user_id = null)
    {
        $data = [
            'id_invoice'   => (int)$id_invoice,
            'checks_json'  => json_encode(array_values(array_map('intval', $indices))),
            'progress_pct' => (int)max(0, min(100, (int)$pct)),
            'updated_by'   => $user_id ? (int)$user_id : null,
        ];

        // upsert
        $exists = $this->db->get_where($this->table, ['id_invoice' => (int)$id_invoice])->row_array();
        if ($exists) {
            $this->db->where('id_invoice', (int)$id_invoice)->update($this->table, $data);
        } else {
            $this->db->insert($this->table, $data);
        }

        return $this->get_by_invoice($id_invoice);
    }
}
