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

class Progress extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // jika ada guard login di proyekmu, aktifkan:
        cek_session_login(0); // atau cek_session_login();
        $this->load->model('Progress_model', 'progress');
    }

    private function json($arr, $code = 200)
    {
        $this->output->set_content_type('application/json')->set_status_header($code)->set_output(json_encode($arr));
    }

    public function get()
    {
        $id_invoice = (int)$this->input->post('invoice');
        if ($id_invoice <= 0) return $this->json(['ok'=>false, 'msg'=>'invoice invalid'], 400);

        $row = $this->progress->get_by_invoice($id_invoice);
        if (!$row) {
            return $this->json(['ok'=>true, 'indices'=>[], 'pct'=>0]);
        }
        $indices = json_decode((string)$row['checks_json'], true);
        if (!is_array($indices)) $indices = [];
        return $this->json(['ok'=>true, 'indices'=>$indices, 'pct'=>(int)$row['progress_pct']]);
    }

    public function save()
    {
        $id_invoice = (int)$this->input->post('invoice');
        $indices    = $this->input->post('indices');
        $pct        = (int)$this->input->post('pct');

        if ($id_invoice <= 0) return $this->json(['ok'=>false, 'msg'=>'invoice invalid'], 400);
        if (!is_array($indices)) $indices = [];

        $uid = $this->session->idu ?? null;
        $saved = $this->progress->save($id_invoice, $indices, $pct, $uid);

        $outIdx = json_decode((string)$saved['checks_json'], true);
        if (!is_array($outIdx)) $outIdx = [];

        return $this->json([
            'ok'      => true,
            'invoice' => $id_invoice,
            'indices' => $outIdx,
            'pct'     => (int)$saved['progress_pct'],
            'updated' => $saved['updated_at'] ?? null,
        ]);
    }
}
