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

/**
 * @property CI_DB $db
 * @property CI_Input $input
 * @property CI_Output $output
 */
class Atv extends CI_Controller {

    private $tableMaster = 'atv';
    private $tableFoto = 'foto_atv';

    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;
    }

    private function insertFotoList($kode_produk, $fotoList) {
        foreach ($fotoList as $i => $fotoBase64) {
            if (!$fotoBase64) continue;
            $this->db->insert($this->tableFoto, [
                'kode_produk' => $kode_produk,
                'foto' => $fotoBase64,
                'urutan' => $i + 1
            ]);
        }
    }
public function insert() {
    $data = $this->getJsonInput();
    $fotoList = $data['foto_atv_list'] ?? [];
    unset($data['foto_atv_list']);

    $kode_produk = $data['kode_produk'] ?? null;

    // AUTO GENERATE kode_produk (PREFIX + 5 DIGIT ANGKA)
    if (!$kode_produk) {
        $prefix = 'ATV-';

        do {
            $kode_produk = $prefix . str_pad(mt_rand(0, 99999), 5, '0', STR_PAD_LEFT);
            $cek = $this->db->get_where($this->tableMaster, [
                'kode_produk' => $kode_produk
            ])->row_array();
        } while ($cek);

        $data['kode_produk'] = $kode_produk;
    }

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

    $this->insertFotoList($kode_produk, $fotoList);

    echo json_encode([
        'status' => true,
        'message' => 'Data ATV berhasil disimpan',
        'kode_produk' => $kode_produk,
        'jumlah_foto' => count($fotoList)
    ]);

}


    public function get() {
        $masterData = $this->db->get($this->tableMaster)->result_array();
        $result = [];

        foreach ($masterData as $atv) {
            $fotoList = $this->db->where('kode_produk', $atv['kode_produk'])
                                 ->order_by('urutan','ASC')
                                 ->get($this->tableFoto)
                                 ->result_array();
            $atv['foto_atv_list'] = array_column($fotoList, 'foto');
            $result[] = $atv;
        }

        echo json_encode(['status'=>true,'message'=>'Data ATV berhasil diambil','data'=>$result]);
    }

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

        $data = $this->getJsonInput();
        $fotoList = $data['foto_atv_list'] ?? [];
        unset($data['foto_atv_list']);

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

        $this->db->where('kode_produk', $kode_produk)->delete($this->tableFoto);
        $this->insertFotoList($kode_produk, $fotoList);

        echo json_encode([
            'status' => true,
            'message' => 'Data ATV berhasil diupdate',
            'kode_produk' => $kode_produk,
            'jumlah_foto' => count($fotoList)
        ]);
    }

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

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

        echo json_encode([
            'status' => true,
            'message' => 'Data ATV dan foto terkait berhasil dihapus',
            'kode_produk' => $kode_produk
        ]);
    }
}
