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

class Rollback extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_tabel();
        cek_session_login(0);

        $this->load->model("model_penjualan", "model");
        $this->load->model("Model_jurnal", "model_jurnal"); // <-- DITAMBAH: dipakai di beberapa sync_*
        $this->perPage = 10;
        $this->title  = info()['title'];
        $this->iduser = $this->session->idu;
        $this->akses  = $this->session->type_akses;
        $this->load->library('dummy');
    }

    public function resetdata(){
        cek_menu_akses();
        $data['title'] = 'Reset Data | ' . $this->title;
        $this->template->load('main/themes', 'rollback', $data);
    }

    public function cek_data_kategori(){
        $conditions['where'] = array('pub' => 'Y','kunci' => 0);
        $counter = $this->model_app->counter('jenis_cetakan', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_bahan(){
        $conditions['where'] = array('pub'=>1,'kunci'=>0);
        $counter = $this->model_app->counter('bahan', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_satuan(){
        $conditions['where'] = array('pub'=>0);
        $counter = $this->model_app->counter('satuan', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_produk(){
        $conditions['where'] = array('pub'=>1,'kunci'=>0);
        $counter = $this->model_app->counter('produk', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_jenis(){
        $conditions['where'] = array('kunci'=>0,'pub'=>'Y');
        $counter = $this->model_app->counter('jenis_pengeluaran', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_konsumen(){
        $conditions['where'] = array('kunci'=>0);
        $counter = $this->model_app->counter('konsumen', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_supplier(){
        $conditions['where'] = array('kunci'=>0,'publish'=>'Y');
        $counter = $this->model_app->counter('supplier', $conditions);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_penjualan(){
        $counter = $this->model_app->counter('invoice', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_jurnal(){
        $counter = $this->model_app->counter('jurnal', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_pembelian(){
        $counter = $this->model_app->counter('pembelian', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_pengeluaran(){
        $counter = $this->model_app->counter('kas_keluar', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_kasbon(){
        $counter = $this->model_app->counter('kasbon', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_stokmasuk(){
        $counter = $this->model_app->counter('stok_masuk', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_stokkeluar(){
        // FIX: sebelumnya salah hitung stok_masuk
        $counter = $this->model_app->counter('stok_keluar', []);
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function cek_data_mutasikas(){
        $counter = $this->count_mutasi_antar_kas();
        echo json_encode(['status'=>200,'counter'=>$counter]);
    }

    public function install_dummy(){
        database_demo('di Install');
        $name = $this->input->post('name', true);

        $counter = 0;
        $tipe = '';
        $title = 'Install sample';

        if ($name == 'kategori') {
            $tipe = 'install_kategori';
            $this->db->truncate('jenis_cetakan');
            $jenis_cetakan = $this->dummy->kategori();
            $counter = count($jenis_cetakan);
            $this->db->insert_batch('jenis_cetakan', $jenis_cetakan);
        } elseif ($name == 'bahan') {
            $tipe = 'install_bahan';
            $this->db->truncate('bahan');
            $bahan = $this->dummy->bahan();
            $counter = count($bahan);
            $this->db->insert_batch('bahan', $bahan);
        } elseif ($name == 'satuan') {
            $tipe = 'install_satuan';
            $this->db->truncate('satuan');
            $satuan = $this->dummy->satuan();
            $counter = count($satuan);
            $this->db->insert_batch('satuan', $satuan);
        } elseif ($name == 'produk') {
            $tipe = 'install_produk';
            $this->db->truncate('produk');
            $produk = $this->dummy->produk();
            $counter = count($produk);
            $this->db->insert_batch('produk', $produk);
        } elseif ($name == 'supplier') {
            $tipe = 'install_supplier';
            $this->db->truncate('supplier');
            $supplier = $this->dummy->supplier();
            $counter = count($supplier);
            $this->db->insert_batch('supplier', $supplier);
        } elseif ($name == 'jenis') {
            $tipe = 'install_jenis';
            $this->db->truncate('jenis_pengeluaran');
            $pengeluaran = $this->dummy->pengeluaran();
            $counter = count($pengeluaran);
            $this->db->insert_batch('jenis_pengeluaran', $pengeluaran);
        } elseif ($name == 'konsumen') {
            $tipe = 'install_konsumen';
            $this->db->truncate('konsumen');
            $konsumen = $this->dummy->konsumen();
            $counter = count($konsumen);
            $this->db->insert_batch('konsumen', $konsumen);
        } elseif ($name == 'pengeluaran') {
            $tipe = 'install_pengeluaran';
            $title = 'Tidak ada sample';
            $counter = 0;
        } elseif ($name == 'mutasikas') {
            $tipe = 'install_mutasikas';
            $title = 'Tidak ada sample';
            $counter = 0;
        } elseif ($name == 'jurnal') {
            $tipe = 'install_jurnal';
            $title = 'Syn Jurnal';
            $this->sync_journal_lunas();
            $this->sync_journal_belumlunas();
            $this->sync_kas_keluar();
            $this->sync_pembelian();
            $counter = $this->model_app->counter('jurnal', []);
        }

        echo json_encode(['status'=>200,'counter'=>$counter,'tipe'=>$tipe,'name'=>$name,'msg'=>'ok','title'=>$title]);
    }

    private function get_mutasi_antar_kas_refs()
    {
        if (!$this->db->table_exists('kas_masuk')) {
            return [];
        }

        $rows = $this->db
            ->select('id_generate')
            ->from('kas_masuk')
            ->where('id_bayar', 0)
            ->where('id_parent >', 0)
            ->where('pengeluaran >', 0)
            ->like('catatan', 'Mutasi:', 'after')
            ->where('id_generate IS NOT NULL', null, false)
            ->where('id_generate !=', '')
            ->group_by('id_generate')
            ->get()
            ->result_array();

        return array_values(array_filter(array_column($rows, 'id_generate')));
    }

    private function count_mutasi_antar_kas()
    {
        return count($this->get_mutasi_antar_kas_refs());
    }

    private function reset_mutasi_antar_kas()
    {
        $refs = $this->get_mutasi_antar_kas_refs();
        if (empty($refs)) {
            return 0;
        }

        $this->db->trans_begin();

        if ($this->db->table_exists('jurnal') && $this->db->table_exists('jurnal_detail')) {
            $jurnalRows = $this->db
                ->select('id_jurnal')
                ->from('jurnal')
                ->where_in('no_trans', $refs)
                ->like('keterangan', 'Mutasi:', 'after')
                ->get()
                ->result_array();

            $jurnalIds = array_values(array_filter(array_map('intval', array_column($jurnalRows, 'id_jurnal'))));
            if (!empty($jurnalIds)) {
                $this->db->where_in('id_jurnal', $jurnalIds)->delete('jurnal_detail');
                $this->db->where_in('id_jurnal', $jurnalIds)->delete('jurnal');
            }
        }

        if ($this->db->table_exists('jurnal_transaksi')) {
            $this->db
                ->like('keterangan', 'Mutasi:', 'after')
                ->delete('jurnal_transaksi');
        }

        $this->db
            ->where_in('id_generate', $refs)
            ->where('id_bayar', 0)
            ->like('catatan', 'Mutasi:', 'after')
            ->delete('kas_masuk');

        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            return 0;
        }

        $this->db->trans_commit();
        return count($refs);
    }

    private function sync_pembelian()
    {
        $this->load->model('Journal_model','journal');
        $this->load->model('Model_kas','kas');
        $this->load->model('model_pembelian','beli');

        $data = $this->model_app->views('pembelian')->result();
        if (!empty($data)) {
            foreach ($data as $row) {
                $catatan = "PEMBELIAN NO#" . $row->no_transaksi;
                $respon = [
                    "no_trans"   => $row->no_transaksi,
                    "tgl"        => $row->tgl_pembelian,
                    "keterangan" => $catatan,
                    "bukti"      => '',
                    "id_user"    => $this->iduser
                ];
                $this->db->insert('jurnal', $respon);
                $jurnal_id = $this->db->insert_id();

                $input_jurnal = [
                    'id_jurnal'      => $jurnal_id,
                    'id_akun'        => $row->id_akun,
                    'tipe_kas'       => $this->model_jurnal->getIdAkunKasById($row->id_akun),
                    'id_perkiraan'   => 2,
                    'nilai'          => $row->total_bayar,
                    'catatan_jurnal' => $row->keterangan
                ];
                $this->db->insert('jurnal_detail', $input_jurnal);

                $akun_detail = $this->model_jurnal->pembelian_detail($row->id_pembelian)->result();
                foreach ($akun_detail as $rows) {
                    $jumlah = $rows->jumlah * $rows->harga;
                    $input_jurnal_kredit = [
                        'id_jurnal'      => $jurnal_id,
                        'id_akun'        => $rows->id_akun,
                        'tipe_kas'       => $this->model_jurnal->getIdAkunKasById($rows->id_akun),
                        'id_perkiraan'   => 1,
                        'nilai'          => $jumlah,
                        'catatan_jurnal' => $rows->keterangan,
                    ];
                    $this->db->insert('jurnal_detail', $input_jurnal_kredit);
                }
            }
        }
    }

    private function sync_journal_lunas()
    {
        $this->load->model('Journal_model','journal');
        $where = ['lunas'=>1];
        $data = $this->model_app->view_where('invoice', $where)->result();

        if (!empty($data)) {
            $no = 0;
            foreach ($data as $row) {
                $no++;
                $_data = $this->model_jurnal->cek_bayar_belum_lunas($row->id_invoice)->row();
                $no_trans = date("ymd", strtotime($row->tgl_trx)) . sprintf("%04s", $no);
                $get_id_transaksi = get_id_transaksi($row->id_invoice)['nomor_order'];
                $nama = cekKonsumen($row->id_konsumen)['nama'];
                $catatan = "ORDER NO#" . $get_id_transaksi . ' - ' . $nama;

                $respon = [
                    "no_trans"   => $no_trans,
                    "tgl"        => $row->tgl_trx,
                    "keterangan" => $catatan,
                    "bukti"      => $_data->lampiran,
                    "id_user"    => $row->id_user
                ];
                $this->db->insert('jurnal', $respon);
                $jurnal_id = $this->db->insert_id();

                if ($_data->id_bayar == 1) {
                    $input_jurnal = [
                        'id_jurnal'    => $jurnal_id,
                        'id_akun'      => 1,
                        'tipe_kas'     => 1,
                        'id_perkiraan' => 1,
                        'nilai'        => $_data->total,
                        'catatan_jurnal'=> ""
                    ];
                } else {
                    $input_jurnal = [
                        'id_jurnal'    => $jurnal_id,
                        'id_akun'      => $_data->id_sub_bayar,
                        'tipe_kas'     => 1,
                        'id_perkiraan' => 1,
                        'nilai'        => $_data->total,
                        'catatan_jurnal'=> ""
                    ];
                }
                $this->db->insert('jurnal_detail', $input_jurnal);

                $akun_detail = $this->model_jurnal->akun_detail($row->id_invoice)->result();
                foreach ($akun_detail as $rows) {
                    $input_jurnal_kredit = [
                        'id_jurnal'    => $jurnal_id,
                        'id_akun'      => $rows->id_akun,
                        'tipe_kas'     => 0,
                        'id_perkiraan' => 2,
                        'nilai'        => $rows->total,
                        'catatan_jurnal'=> $rows->id_invoice,
                    ];
                    $this->db->insert('jurnal_detail', $input_jurnal_kredit);
                }
            }
        }
    }

    private function sync_journal_belumlunas()
    {
        $this->load->model('Journal_model','journal');
        $where = ['pos'=>'Y','status'=>'simpan','lunas'=>0];
        $data = $this->model_app->view_where('invoice', $where)->result();

        if (!empty($data)) {
            $no = 0;
            foreach ($data as $row) {
                $no++;
                $_data            = $this->model_jurnal->cek_bayar_belum_lunas($row->id_invoice)->row();
                $total            = $this->model_jurnal->sum_detail($row->id_invoice);
                $no_trans         = date("ymd", strtotime($row->tgl_trx)) . sprintf("%04s", $no);
                $get_id_transaksi = get_id_transaksi($row->id_invoice)['nomor_order'];
                $nama             = cekKonsumen($row->id_konsumen)['nama'];
                $cek_lunas        = $this->cek_lunas($row->id_invoice);
                $cek_count        = $this->model_jurnal->cek_count($row->id_invoice);
                $status           = $row->status;

                $total_order = $this->model_jurnal->sum_order($row->id_invoice);
                $sisa        = $total_order - $_data->total;
                $jml_bayar   = $_data->total;

                if ($jml_bayar > 0 && $cek_lunas == false && $cek_count == 1 && $status=='simpan'){
                    $catatan = "ORDER NO#" . $get_id_transaksi . ' - ' . $nama;
                    $dataIns = [
                        "no_trans"   => $no_trans,
                        "tgl"        => $row->tgl_trx,
                        "keterangan" => $catatan,
                        "bukti"      => $_data->lampiran,
                        "id_user"    => $row->id_user
                    ];

                    $this->db->insert('jurnal', $dataIns);
                    $jurnal_id = $this->db->insert_id();

                    $input_jurnal = array(
                        array(
                            'id_jurnal'    => $jurnal_id,
                            'id_akun'      => $this->model_jurnal->get_akun(8),
                            'tipe_kas'     => 1,
                            'id_perkiraan' => 1,
                            'nilai'        => $_data->total,
                        ),
                        array(
                            'id_jurnal'    => $jurnal_id,
                            'id_akun'      => $this->model_jurnal->get_akun(6),
                            'tipe_kas'     => 1,
                            'id_perkiraan' => 1,
                            'nilai'        => $sisa,
                        ),
                        array(
                            'id_jurnal'    => $jurnal_id,
                            'id_akun'      => $this->model_jurnal->get_akun(4),
                            'tipe_kas'     => 1,
                            'id_perkiraan' => 2,
                            'nilai'        => $total_order,
                        )
                    );
                    $this->db->insert_batch('jurnal_detail', $input_jurnal);
                }

                if ($jml_bayar == 0 && $cek_lunas == false && $status=='simpan'){
                    $catatan = "PIUTANG NO#" . $get_id_transaksi . ' - ' . $nama;
                    $dataIns = [
                        "no_trans"   => $no_trans,
                        "tgl"        => $row->tgl_trx,
                        "keterangan" => $catatan,
                        "bukti"      => '',
                        "id_user"    => $row->id_user
                    ];
                    $this->db->insert('jurnal', $dataIns);
                    $jurnal_id = $this->db->insert_id();

                    $input_jurnal_debet = [
                        'id_jurnal'    => $jurnal_id,
                        'id_akun'      => $this->model_jurnal->get_akun(6),
                        'tipe_kas'     => 1,
                        'id_perkiraan' => 1,
                        'nilai'        => $total_order,
                    ];
                    $this->db->insert('jurnal_detail', $input_jurnal_debet);

                    $akun_detail = $this->model_jurnal->akun_detail($row->id_invoice)->result();
                    foreach ($akun_detail as $r) {
                        $input_jurnal_kredit = [
                            'id_jurnal'    => $jurnal_id,
                            'id_akun'      => $r->id_akun,
                            'tipe_kas'     => 0,
                            'id_perkiraan' => 2,
                            'nilai'        => $r->total
                        ];
                        $this->db->insert('jurnal_detail', $input_jurnal_kredit);
                    }
                }
            }
        }
    }

    private function cek_lunas($no_order)
    {
        $_diskon = "ROUND(SUM((`invoice_detail`.`jumlah`) * (`invoice_detail`.`harga` * `invoice_detail`.`diskon`/100))) AS diskon";
        $cek_diskon      = $this->model_app->cek_total("invoice_detail", $_diskon, ["id_invoice" => $no_order])->diskon;
        $sum_detail      = $this->model->cek_total_detail($no_order);
        $cek_total_bayar = $this->model->cek_total_bayar($no_order);
        $diskon          = $this->model->cek_total_diskon_invoice($no_order);

        $sisa = $sum_detail - $cek_total_bayar - $cek_diskon - $diskon;
        return ($sisa == 0);
    }

    private function sync_kas_keluar()
    {
        $this->load->model('Journal_model','journal');
        $data = $this->model_app->views('kas_keluar')->result();
        if (!empty($data)) {
            foreach ($data as $row) {
                $respon = [
                    "no_trans"   => $row->no_transaksi,
                    "tgl"        => $row->tanggal,
                    "keterangan" => $row->keterangan,
                    "bukti"      => '',
                    "id_user"    => $row->id_user
                ];
                $this->db->insert('jurnal', $respon);
                $jurnal_id = $this->db->insert_id();

                $input_jurnal = [
                    'id_jurnal'      => $jurnal_id,
                    'id_akun'        => $row->id_akun,
                    'tipe_kas'       => $this->model_jurnal->getIdAkunKasById($row->id_akun),
                    'id_perkiraan'   => 2,
                    'nilai'          => $row->jumlah,
                    'catatan_jurnal' => $row->keterangan
                ];
                $this->db->insert('jurnal_detail', $input_jurnal);

                $akun_detail = $this->model_jurnal->kas_detail($row->id)->result();
                foreach ($akun_detail as $rows) {
                    $input_jurnal_kredit = [
                        'id_jurnal'      => $jurnal_id,
                        'id_akun'        => $rows->id_akun,
                        'tipe_kas'       => $this->model_jurnal->getIdAkunKasById($rows->id_akun),
                        'id_perkiraan'   => 1,
                        'nilai'          => $rows->jumlah,
                        'catatan_jurnal' => $rows->keterangan,
                    ];
                    $this->db->insert('jurnal_detail', $input_jurnal_kredit);
                }
            }
        }
    }

    public function reset_dummy(){
        database_demo('di Reset');
        $name = $this->input->post('name', true);

        $counter = 0;
        $title   = 'Install sample';
        $tipe    = '';

        if ($name == 'kategori') {
            $tipe = 'install_kategori';
            $this->db->truncate('jenis_cetakan');
            $jenis_cetakan = $this->dummy->reset_kategori();
            $this->db->insert_batch('jenis_cetakan', $jenis_cetakan);
        } elseif ($name == 'bahan') {
            $tipe = 'install_bahan';
            $this->db->truncate('bahan');
            $this->db->truncate('satu_harga');
            $this->db->truncate('harga_member');
            $this->db->truncate('harga_range_member');
            $this->db->truncate('harga_satuan');
            $this->db->truncate('range_harga');
            $bahan = $this->dummy->reset_bahan();
            $this->db->insert_batch('bahan', $bahan);
        } elseif ($name == 'satuan') {
            $tipe = 'install_satuan';
            $this->db->truncate('satuan');
        } elseif ($name == 'produk') {
            $tipe = 'install_produk';
            $this->db->truncate('produk');
            $produk = $this->dummy->reset_produk();
            $this->db->insert_batch('produk', $produk);
        } elseif ($name == 'supplier') {
            $tipe = 'install_supplier';
            $this->db->truncate('supplier');
            $supplier = $this->dummy->reset_supplier();
            $this->db->insert_batch('supplier', $supplier);
        } elseif ($name == 'jenis') {
            $tipe = 'install_jenis';
            $this->db->truncate('jenis_pengeluaran');
            $pengeluaran = $this->dummy->reset_pengeluaran();
            $this->db->insert_batch('jenis_pengeluaran', $pengeluaran);
        } elseif ($name == 'konsumen') {
            $tipe = 'install_konsumen';
            $this->db->truncate('konsumen');
            $konsumen = $this->dummy->reset_konsumen();
            $this->db->insert_batch('konsumen', $konsumen);
        } elseif ($name == 'penjualan') {
            $tipe = 'install_penjualan';
            $this->db->truncate('invoice');
            $this->db->truncate('invoice_detail');
            $this->db->truncate('bayar_invoice_detail');
            $this->db->update('tb_users', ['last_invoice'=>0,'last_idp'=>0], ['aktif'=>'Y']);
            $title = 'Tidak ada sample';
        } elseif ($name == 'jurnal') {
            $tipe = 'install_jurnal';
            $this->db->query("SET FOREIGN_KEY_CHECKS=0;");
            $this->db->truncate('jurnal');
            $this->db->truncate('jurnal_detail');
            $this->db->query("SET FOREIGN_KEY_CHECKS=1;");
            $title = 'Syn Jurnal';
        } elseif ($name == 'pembelian') {
            // =========================
            // FIX PENTING: hormati foreign key
            // =========================
            $tipe = 'install_pembelian';
            $this->db->trans_begin();
            $this->db->query("SET FOREIGN_KEY_CHECKS=0;");

            // kosongkan tabel anak terlebih dahulu
            if ($this->db->table_exists('bayar_pembelian'))    $this->db->truncate('bayar_pembelian');
            if ($this->db->table_exists('pembelian_detail'))   $this->db->truncate('pembelian_detail');
            if ($this->db->table_exists('pembelian'))          $this->db->truncate('pembelian');

            $this->db->query("SET FOREIGN_KEY_CHECKS=1;");
            $this->session->unset_userdata("cartbeli");

            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                echo json_encode(['status'=>500,'counter'=>0,'tipe'=>$tipe,'name'=>$name,'msg'=>'Gagal reset data pembelian','title'=>'Tidak ada sample']);
                return;
            } else {
                $this->db->trans_commit();
            }

            $title = 'Tidak ada sample';
        } elseif ($name == 'pengeluaran') {
            $tipe = 'install_pengeluaran';
            $this->db->truncate('kas_keluar');
            $this->db->truncate('kas_keluar_detail');
            $title = 'Tidak ada sample';
        } elseif ($name == 'stokmasuk') {
            $tipe = 'install_stokmasuk';
            $this->db->truncate('stok_masuk');
            $this->db->truncate('laporan_stok');
            $this->db->truncate('laporan_penerimaan');
            $this->db->truncate('cc_project');
            $this->db->truncate('cc_terjual');
            $title = 'Tidak ada sample';
        } elseif ($name == 'stokkeluar') {
            $tipe = 'install_stokkeluar';
            $this->db->truncate('stok_keluar');
            $this->db->truncate('laporan_stok');
            $this->db->truncate('laporan_penerimaan');
            $this->db->truncate('cc_project');
            $this->db->truncate('cc_terjual');
            $title = 'Tidak ada sample';
        } elseif ($name == 'mutasikas') {
            $tipe = 'install_mutasikas';
            $this->reset_mutasi_antar_kas();
            $title = 'Tidak ada sample';
        } elseif ($name == 'kasbon') {
            $tipe = 'install_kasbon';
            $this->db->truncate('kasbon');
            $title = 'Tidak ada sample';
        }

        echo json_encode(['status'=>200,'counter'=>$counter,'tipe'=>$tipe,'name'=>$name,'msg'=>'Data '.$name.' berhasil di reset','title'=>$title]);
    }

    function reset_ulang()
    {
        cek_nput_post('GET');
        database_demo_admin('di Reset');

        $this->db->trans_off();
        $this->db->trans_begin();

        $this->db->truncate('jenis_cetakan');
        $reset_kategori = $this->dummy->reset_kategori();
        $this->db->insert_batch('jenis_cetakan', $reset_kategori);

        $this->db->truncate('bahan');
        $bahan = $this->dummy->reset_bahan();
        $this->db->insert_batch('bahan', $bahan);

        $this->db->truncate('satuan');

        $this->db->truncate('produk');
        $produk = $this->dummy->reset_produk();
        $this->db->insert_batch('produk', $produk);

        $this->db->truncate('supplier');
        $supplier = $this->dummy->reset_supplier();
        $this->db->insert_batch('supplier', $supplier);

        $this->db->truncate('jenis_pengeluaran');
        $jenis_pengeluaran = $this->dummy->reset_pengeluaran();
        $this->db->insert_batch('jenis_pengeluaran', $jenis_pengeluaran);

        $this->db->truncate('konsumen');
        $konsumen = $this->dummy->reset_konsumen();
        $this->db->insert_batch('konsumen', $konsumen);

        $this->db->truncate('rekening_bank');
        $rekening_bank = $this->dummy->reset_rekening();
        $this->db->insert_batch('rekening_bank', $rekening_bank);

        $this->db->truncate('harga');
        $this->db->truncate('invoice');
        $this->db->truncate('invoice_detail');
        $this->db->truncate('bayar_invoice_detail');
        $this->db->truncate('pengeluaran');
        $this->db->truncate('pengeluaran_detail');
        $this->db->truncate('surat_jalan');
        $this->db->truncate('user_agent');
        $this->db->truncate('jurnal');
        $this->db->truncate('history_stok');
        $this->db->truncate('kasbon');
        $this->db->truncate('laporan_stok');

        $this->session->unset_userdata('cart');
        $this->session->unset_userdata('cartp');
        $this->db->update('tb_users', ['last_invoice'=>0,'last_idp'=>0], ['aktif'=>'Y']);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $data = array('status'=>200,'msg'=>'Database gagal di reset');
        } else {
            $this->db->trans_commit();
            $data = array('status'=>200,'msg'=>'Database berhasil di reset');
        }
        echo json_encode($data);
    }

    public function backup_table_db(){
        database_demo_admin('di Backup');
        $this->load->dbutil();
        $prefs = array(
            'tables'     => array('bahan'),
            'ignore'     => array(),
            'format'     => 'txt',
            'filename'   => 'mybackup.sql',
            'add_drop'   => TRUE,
            'add_insert' => TRUE,
            'newline'    => "\n"
        );
        echo json_encode(['status'=>200,'counter'=>2,'msg'=>'ok']);
    }

    public function menu_admin(){
        cek_nput_post('GET');
        database_demo_admin('di Rollback');
        $this->db->trans_off();
        $this->db->trans_begin();

        $this->db->truncate('menuadmin');
        $menuadmin = $this->dummy->menuadmin();
        $this->db->insert_batch('menuadmin', $menuadmin);

        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE){
            $this->db->trans_rollback();
            $data = array('status'=>400,'msg'=>'Menu gagal di rollback');
        }else{
            $this->db->trans_commit();
            $data = array('status'=>200,'msg'=>'Menu berhasil di rollback');
        }
        echo json_encode($data);
    }
}
