<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * @property CI_DB $db
 * @property CI_Input $input
 * @property CI_Output $output
 * @property CI_Session $session
 */
class Register extends CI_Controller {

    private $tableMaster = 'users';

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->output->set_content_type('application/json');
    }

    // Tangkap semua request
    public function _remap($method, $params = []) {
        if(method_exists($this, $method)){
            return call_user_func_array([$this, $method], $params);
        }
        echo json_encode(['status'=>'error','message'=>'Method tidak ditemukan']);
    }

    private function getJsonInput() {
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) {
            echo json_encode([
                'status' => false,
                'message' => 'JSON kosong atau tidak valid'
            ]);
            exit;
        }
        return $data;
    }

    // Register user baru
    public function insert() {
        $data = $this->getJsonInput();

// generate id_user jika kosong
if (empty($data['id_user'])) {
    do {
        // 3 huruf + 3 angka
        $huruf = 'USR';
        $angka = mt_rand(100, 999); // 3 digit angka

        $data['id_user'] = $huruf . $angka;

        $cek = $this->db
            ->get_where($this->tableMaster, ['id_user' => $data['id_user']])
            ->row_array();
    } while ($cek);
}


        // set default role jika tidak disertakan
        if(empty($data['role'])) $data['role'] = 'user';

        // hash password sebelum insert
        if(isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        } else {
            echo json_encode(['status'=>false,'message'=>'Password wajib diisi']);
            return;
        }

        if (!$this->db->insert($this->tableMaster, $data)) {
            echo json_encode([
                'status' => false,
                'message'=> 'Gagal register user',
                'db_error'=> $this->db->error()
            ]);
            return;
        }

        echo json_encode([
            'status'=> true,
            'message'=> 'User berhasil didaftarkan',
            'id_user'=> $data['id_user']
        ]);
    }

    // Get semua user
    public function get() {
        $data = $this->db->get($this->tableMaster)->result_array();
        echo json_encode([
            'status'=>true,
            'message'=>'Data user berhasil diambil',
            'data'=> $data
        ]);
    }

    // Update data user
    public function update($id_user = null) {
        if (!$id_user) {
            echo json_encode(['status'=>false,'message'=>'id_user wajib disertakan di URL']);
            return;
        }

        $data = $this->getJsonInput();

        // hash password jika diubah
        if(isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        $this->db->where('id_user', $id_user);
        if (!$this->db->update($this->tableMaster, $data)) {
            echo json_encode(['status'=>false,'message'=>'Gagal update user','db_error'=>$this->db->error()]);
            return;
        }

        echo json_encode([
            'status'=>true,
            'message'=>'Data user berhasil diupdate',
            'id_user'=>$id_user
        ]);
    }

    // Hapus user
    public function delete($id_user = null) {
        if (!$id_user) {
            echo json_encode(['status'=>false,'message'=>'id_user wajib disertakan di URL']);
            return;
        }

        $this->db->where('id_user', $id_user);
        if (!$this->db->delete($this->tableMaster)) {
            echo json_encode(['status'=>false,'message'=>'Gagal menghapus user','db_error'=>$this->db->error()]);
            return;
        }

        echo json_encode([
            'status'=>true,
            'message'=>'User berhasil dihapus',
            'id_user'=>$id_user
        ]);
    }
}
