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

class Kodebarang extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
    }
    
    public function index()
    {
        $data = ["active_menu" => "kode_barang"];
        $this->load->view('partials/header', $data);
        $this->load->view('kode_barang/layout');
        $this->load->view('partials/footer');
    }

    // =========================
    // GET DATA (DATATABLE)
    // =========================
    public function get_data()
    {
        $data = $this->db->order_by('id', 'DESC')->get('kode_barang')->result();

        $result = [];
        $no = 1;

        foreach ($data as $row) {
            $result[] = [
                $no++,
                $row->kode_barang,
                $row->nama,
                (int)$row->limit_stock,
                strtoupper($row->tracking_type ?? 'UNIT'),
                strtolower($row->need_serial_number ?? 'false') === 'true' ? 'Ya' : 'Tidak',
                $row->unit ?? 'PCS',
                '
                <button class="btn btn-sm btn-secondary btn-editkode" data-id="'.$row->id.'">Edit</button>
                <button class="btn btn-sm btn-danger btn-delete" data-id="'.$row->id.'">Delete</button>
                '
            ];
        }

        echo json_encode(["data"=>$result]);
    }

    // =========================
    // DETAIL
    // =========================
    public function detail($id)
    {
        echo json_encode(
            $this->db->get_where('kode_barang',['id'=>$id])->row()
        );
    }

    // =========================
    // SAVE
    // =========================
    public function save()
    {
        $nama = trim($this->input->post('nama'));
        $kode = trim($this->input->post('kode'));
        $limit_stock = (int)$this->input->post('limit_stock');
        $tracking_type = strtoupper(trim($this->input->post('tracking_type')));
        $need_serial_number = strtolower(trim($this->input->post('need_serial_number')));
        $unit = trim($this->input->post('unit'));

        if(!$nama || !$kode){
            echo json_encode(['status'=>false,'message'=>'Kode dan nama wajib diisi']);
            return;
        }

        if(!in_array($tracking_type, ['UNIT','QTY'])){
            echo json_encode(['status'=>false,'message'=>'Tracking type tidak valid']);
            return;
        }

        if(!in_array($need_serial_number, ['true','false'])){
            echo json_encode(['status'=>false,'message'=>'Need serial number tidak valid']);
            return;
        }

        if(!in_array($unit, ['PCS','Meter','Lembar'])){
            echo json_encode(['status'=>false,'message'=>'Unit tidak valid']);
            return;
        }

        $exists = $this->db->get_where('kode_barang', ['kode_barang' => $kode])->num_rows();
        if($exists > 0){
            echo json_encode(['status'=>false,'message'=>'Kode barang sudah digunakan']);
            return;
        }

        $this->db->insert('kode_barang', [
            'kode_barang' => $kode,
            'nama' => $nama,
            'created_at' => date('Y-m-d H:i:s'),
            'limit_stock' => $limit_stock,
            'tracking_type' => $tracking_type,
            'need_serial_number' => $need_serial_number,
            'unit' => $unit
        ]);

        log_activity(
            'kode_barang',
            'create',
            'Menambahkan kode barang: ' . $kode . ' - ' . $nama,
            'success'
        );

        echo json_encode(['status'=>true,'message'=>'Kode barang berhasil ditambahkan']);
    }

    // =========================
    // UPDATE
    // =========================
    public function update()
    {
        $id   = (int)$this->input->post('id');
        $kode = trim($this->input->post('kode'));
        $nama = trim($this->input->post('nama'));
        $limit_stock = (int)$this->input->post('limit_stock');
        $tracking_type = strtoupper(trim($this->input->post('tracking_type')));
        $need_serial_number = strtolower(trim($this->input->post('need_serial_number')));
        $unit = trim($this->input->post('unit'));

        if(!$id || !$nama || !$kode){
            echo json_encode(['status'=>false,'message'=>'ID, kode dan nama wajib diisi']);
            return;
        }

        if(!in_array($tracking_type, ['UNIT','QTY'])){
            echo json_encode(['status'=>false,'message'=>'Tracking type tidak valid']);
            return;
        }

        if(!in_array($need_serial_number, ['true','false'])){
            echo json_encode(['status'=>false,'message'=>'Need serial number tidak valid']);
            return;
        }

        if(!in_array($unit, ['PCS','Meter','Lembar'])){
            echo json_encode(['status'=>false,'message'=>'Unit tidak valid']);
            return;
        }

        $exists = $this->db
            ->where('kode_barang', $kode)
            ->where('id !=', $id)
            ->get('kode_barang')
            ->num_rows();

        if($exists > 0){
            echo json_encode(['status'=>false,'message'=>'Kode barang sudah digunakan']);
            return;
        }

        $this->db->where('id',$id)->update('kode_barang', [
            'kode_barang' => $kode,
            'nama' => $nama,
            'limit_stock' => $limit_stock,
            'tracking_type' => $tracking_type,
            'need_serial_number' => $need_serial_number,
            'unit' => $unit
        ]);

        log_activity(
            'kode_barang',
            'update',
            'Update kode barang ID: ' . $id . ' (' . $kode . ' - ' . $nama . ')',
            'success'
        );

        echo json_encode(['status'=>true,'message'=>'Kode barang berhasil diupdate']);
    }

    // =========================
    // DELETE
    // =========================
    public function delete($id)
    {
        $row = $this->db->get_where('kode_barang', ['id'=>$id])->row();

        if(!$row){
            echo json_encode([
                'status'=>false,
                'message'=>'Data kode barang tidak ditemukan'
            ]);
            return;
        }

        // cek relasi ke items (mengacu ke kode_id)
        $cek = $this->db->get_where('items',['kode_id'=>$id])->num_rows();

        if($cek > 0){
            echo json_encode([
                'status'=>false,
                'message'=>'Kode barang tidak bisa dihapus karena masih dipakai item'
            ]);
            return;
        }

        $this->db->delete('kode_barang',['id'=>$id]);

        log_activity(
            'kode_barang',
            'delete',
            'Hapus kode barang ID: ' . $id . ' (' . $row->kode_barang . ' - ' . $row->nama . ')',
            'success'
        );

        echo json_encode(['status'=>true,'message'=>'Kode barang berhasil dihapus']);
    }

    
    public function list()
    {
        echo json_encode(
            $this->db->get('kode_barang')->result()
        );
    }
}