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

class Supplier extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        cek_session_login();
        $this->perPage = 10;
        $this->iduser  = $this->session->idu;
        $this->title   = info()['title'];
    }

    /* ======================= LIST SUPPLIER ======================= */

    public function data()
    {
        $data['title'] = 'Data supplier | ' . $this->title;

        $conditions['returnType'] = 'count';
        $totalRec = $this->model_data->get_supplier($conditions);

        // Pagination
        $config['target']     = '#dataSupplier';
        $config['base_url']   = base_url('supplier/ajaxSupplier');
        $config['total_rows'] = $totalRec;
        $config['per_page']   = $this->perPage;
        $config['link_func']  = 'search_Supplier';
        $this->ajax_pagination->initialize($config);

        // First page data
        $conditions = array('limit' => $this->perPage);
        $data['result'] = $this->model_data->get_supplier($conditions);

        $this->template->load('main/themes', 'supplier/data_supplier', $data);
    }

    public function ajaxSupplier()
    {
        cek_nput_post('GET'); // sesuai pola proyek

        $page = $this->input->post('page');
        $offset = $page ? $page : 0;

        $limits = $this->input->post('limits');
        $limit  = !empty($limits) ? (int)$limits : $this->perPage;

        $sortBy = $this->input->post('sortBy');
        if (!empty($sortBy)) {
            $conditions['search']['sortBy'] = $sortBy;
        }

        $keywords = $this->input->post('keywords');
        if (!empty($keywords)) {
            $conditions['search']['keywords'] = $keywords;
        }

        // Count
        $conditions['returnType'] = 'count';
        $totalRec = $this->model_data->get_supplier($conditions);

        // Pagination
        $config['target']     = '#dataSupplier';
        $config['base_url']   = base_url('supplier/ajaxSupplier');
        $config['total_rows'] = $totalRec;
        $config['per_page']   = $limit;
        $config['link_func']  = 'search_Supplier';
        $this->ajax_pagination->initialize($config);

        // Data
        $conditions['start'] = $offset;
        $conditions['limit'] = $limit;
        unset($conditions['returnType']);

        $data['result'] = $this->model_data->get_supplier($conditions);

        // Render row list
        $conditions['offset'] = $offset;
        $this->load->view('supplier/cari-supplier', $data, false);
    }

    /* ======================= CRUD HELPER ======================= */

    public function get_data()
    {
        cek_nput_post('GET');

        $id = $this->db->escape_str($this->input->post('id'));
        $search = $this->model_app->view_where('supplier', array('id_supplier' => decrypt($id)));
        if ($search->num_rows() > 0) {
            $row = $search->row();
            $data = array(
                'id'     => $id,
                'nama'   => $row->nama_perusahaan,
                'pemilik'=> $row->pemilik,
                'jabatan'=> $row->jabatan,
                'telp'   => $row->telp,
                'email'  => $row->email,
                'jenis'  => $row->jenis_usaha,
                'rekening' => $row->nomor_rekening,
                'alamat' => $row->alamat,
                'tgl'    => $row->tgl_terdaftar
            );
        } else {
            $data = [];
        }

        $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }

    /* ======================= DETAIL SUPPLIER (HALAMAN) ======================= */

    public function detail($id = "")
    {
        $data['title'] = 'Detail pembelian supplier | ' . $this->title;

        if (empty($id)) {
            $this->output->set_content_type('application/json')
                ->set_output(json_encode(['status' => false, 'msg' => 'error']));
            return;
        }

        $dec_id = decrypt_url($id); // ID asli
        $search = $this->model_app->view_where('supplier', array('id_supplier' => $dec_id));

        if ($search->num_rows() == 0) {
            $this->output->set_content_type('application/json')
                ->set_output(json_encode(['status' => false, 'msg' => 'Data tidak ditemukan']));
            return;
        }

        $row = $search->row();
        // Kirim ke view agar bisa dipakai dan difilter via AJAX
        $data['supplier_id']   = (int)$dec_id;
        $data['supplier_nama'] = $row->nama_perusahaan;

        // (opsional) pratinjau awal; biarkan view memuat via AJAX agar konsisten pagination/keyword
        $this->template->load('main/themes', 'supplier/detail_supplier', $data);
    }

    /* ======================= DETAIL SUPPLIER (AJAX LIST) ======================= */

    public function ajaxDetailSupplier()
    {
        cek_nput_post('GET'); // sesuai pola proyek

        // --- FILTER WAJIB: ambil supplier_id dari POST ---
        $supplier_id = (int)$this->input->post('supplier_id');
        if ($supplier_id <= 0) {
            // tanpa supplier_id kita hentikan supaya tidak bocor semua data
            $this->load->view('supplier/detail-supplier', ['result' => [], 'error' => 'ID supplier tidak valid'], false);
            return;
        }
        // --------------------------------------------------

        $page   = $this->input->post('page');
        $offset = $page ? (int)$page : 0;

        $limits = $this->input->post('limits');
        $limit  = !empty($limits) ? (int)$limits : $this->perPage;

        $sortBy = $this->input->post('sortBy');
        if (!empty($sortBy)) {
            $conditions['search']['sortBy'] = $sortBy;
        }

        $keywords = $this->input->post('keywords');
        if (!empty($keywords)) {
            $conditions['search']['keywords'] = $keywords;
        }

        // >>> PASANG WHERE untuk supplier yang dipilih <<<
        $conditions['where'] = ['pembelian_detail.id_supplier' => $supplier_id];

        // Count
        $conditions['returnType'] = 'count';
        $totalRec = $this->model_data->getSupplier($conditions);

        // Pagination
        $config['target']     = '#dataSupplier';
        $config['base_url']   = base_url('supplier/ajaxDetailSupplier');
        $config['total_rows'] = $totalRec;
        $config['per_page']   = $limit;
        $config['link_func']  = 'search_Supplier';
        $this->ajax_pagination->initialize($config);

        // Data
        $conditions['start'] = $offset;
        $conditions['limit'] = $limit;
        unset($conditions['returnType']);

        $data['result'] = $this->model_data->getSupplier($conditions);

        // kirim offset (jika dipakai di partial)
        $conditions['offset'] = $offset;

        $this->load->view('supplier/detail-supplier', $data, false);
    }

    /* ======================= SIMPAN / HAPUS ======================= */

    public function simpan()
    {
        cek_nput_post('GET');
        simpan_demo("Simpan");

        $id   = $this->db->escape_str($this->input->post('id'));
        $type = $this->db->escape_str($this->input->post('type'));

        $data_post = array(
            'nama_perusahaan' => $this->db->escape_str($this->input->post('nama_perusahaan')),
            'pemilik'         => $this->db->escape_str($this->input->post('atas_nama')),
            'jabatan'         => $this->db->escape_str($this->input->post('jabatan')),
            'telp'            => $this->db->escape_str($this->input->post('no_hp')),
            'email'           => $this->db->escape_str($this->input->post('email')),
            'jenis_usaha'     => $this->db->escape_str($this->input->post('jenis_usaha')),
            'nomor_rekening'  => $this->db->escape_str($this->input->post('no_rekening')),
            'alamat'          => $this->db->escape_str($this->input->post('alamat'))
        );

        if ($id == 0 && $type == 'add') {
            $res = $this->model_app->input('supplier', $data_post);
            $data = ($res['status'] == 'ok')
                ? array('status' => 200, 'msg' => 'Data berhasil disimpan', 'id' => $res['id'], 'nama_perusahaan' => $data_post['nama_perusahaan'])
                : array('status' => 400, 'msg' => 'Data gagal disimpan');
        } elseif ($id > 0 && $type == 'edit') {
            $res = $this->model_app->update('supplier', $data_post, array('id_supplier' => $id));
            $data = ($res['status'] == 'ok')
                ? array('status' => 200, 'msg' => 'Data berhasil update', 'id' => $id, 'nama_perusahaan' => $data_post['nama_perusahaan'])
                : array('status' => 400, 'msg' => 'Data gagal diupdate');
        } else {
            $data = array('status' => 400, 'msg' => 'Bad request');
        }

        $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }

    public function hapus()
    {
        cek_nput_post('GET');
        simpan_demo('Hapus');

        $id   = $this->db->escape_str($this->input->post('id'));
        $type = $this->db->escape_str($this->input->post('type'));

        if ($id > 0 && $type == 'hapus') {
            $where = array('id_supplier' => $id);

            $cek = $this->model_app->view_where('pembelian_detail', $where);
            if ($cek->num_rows() > 0) {
                $data = array('status' => 400, 'msg' => 'Data tidak bisa dihapus');
            } else {
                $cek2 = $this->model_app->view_where('supplier', $where);
                if ($cek2->num_rows() > 0) {
                    $res = $this->model_app->hapus('supplier', $where);
                    $data = ($res['status'] == 'ok')
                        ? array('status' => 200, 'msg' => 'Data berhasil dihapus')
                        : array('status' => 400, 'msg' => 'Data gagal dihapus');
                } else {
                    $data = array('status' => 400, 'msg' => 'Jenis tidak bisa dihapus');
                }
            }
        } else {
            $data = array('status' => 400, 'msg' => 'Bad request');
        }

        $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }
}
