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

class Kasirq extends CI_Controller {

    public function __construct() {
        parent::__construct();
        
        $this->load->model(['barang_model','transaksi_model','m_kantor','m_kontak','m_metode','m_member']);
        $this->load->helper('rupiah');
        $this->load->helper(array('form', 'url','tanggal'));
        if($this->session->userdata('status') != "loginbro"  and empty($this->session->userdata('email')) ){
          $this->session->set_flashdata('msg','<div class="alert alert-danger alert-dismissible">
            <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
            <strong> Admin Bukan Admin </strong>Ulangi Kembali
            </div> ');

          redirect(base_url("")); 
          
        }
    }

    public function index() {
        date_default_timezone_set('Asia/Jakarta');
        $tgl = date('Ymd');

        $username = $this->session->userdata("username");  
        $this->db->where('username',$username);
        $query = $this->db->get('tb_admin');
        $row = $query->row();
        $data['id_admin']= $row->id;
        $data['nama_admin']= $row->nama_admin;
        $data['id_kantor']= $row->id_kantor;
        $id_admin = $row->id;
        $id_kantor = $row->id_kantor;

        //cek setoran
        $this->db->where('id_admin',$id_admin);
          $this->db->where('keterangan','logout-kasir');
        $this->db->where("date(tb_kasir.date)='$tgl' ");
        $query2 = $this->db->get('tb_kasir');
        $rowkasir = $query2->row();

        //cek cek awal
        $this->db->where('id_admin',$id_admin);
          $this->db->where('keterangan','login-kasir');
        $this->db->where("date(tb_kasir.date)='$tgl' ");
        $query22 = $this->db->get('tb_kasir');
        $rowkasir2 = $query22->row();

        if( $rowkasir->nominal != 0 or $rowkasir->nominal != '' ){
            redirect('home');
            $this->session->set_flashdata('msg','error-setor');

        }else if( $rowkasir2->nominal == 0 or $rowkasir2->nominal == '' ){
            redirect('home');
            $this->session->set_flashdata('msg','error-awal');

        }else{
            $data['title'] = 'Kasir';
            $username = $this->session->userdata("username");  
            $this->db->where('username',$username);
            $query = $this->db->get('tb_admin');
            $row = $query->row();
            $data['id_admin']= $row->id;
            $data['nama_admin']= $row->nama_admin;
            $data['id_kantor']= $row->id_kantor;
            $id_admin = $row->id;
            $id_kantor = $row->id_kantor;
            $data['metode'] = $this->m_metode->metode();
            $data['kontak'] = $this->m_kontak->kontak();
            $data['kantor'] = $this->m_kantor->kantor();
            $data['member'] = $this->m_member->member(); 
            $this->load->view('master/kasirq/index', $data);
        }
    }
    public function simpan_item() {
        $data = $this->input->post();
         
        $item_data = array(
            'id' => '',
            'id_barang' => $data['id_barang'],
            'harga_beli' => $data['harga_beli'],
            'harga_jual' => $data['harga'],
            'jumlah' => $data['jumlah'],
            'harga_total' => $data['total'],
            // 'satuan' => $data['satuan'],
            // 'id_kantor' => $data['id_kantor'],
            // 'id_admin' => $data['id_admin'],
            // 'id_transaksi' => $data['id_transaksi'],
            // 'created_at' => date('Y-m-d H:i:s')
        );

        $this->db->insert('tb_jual_kasir', $item_data);
        
        if ($this->db->affected_rows() > 0) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menyimpan item']);
        }
    }
    // Cari barang untuk autocomplete
    public function cari_barang() {
        $keyword = $this->input->get('term');
        $data = $this->transaksi_model->cari_barang($keyword);
        
        $response = array();
        foreach($data as $barang) {
            $response[] = array(
                'id' => $barang->id,
                'value' => $barang->nama_barang,
                'barcode' => $barang->barcode_ecer,
                'harga' => $barang->harga_jual_ecer,
                'harga_beli' => $barang->harga_beli,
                'isi_dos' => $barang->isi,
                'harga_jual_dos' => $barang->harga_jual_dos,
                'min_grosir_lv1' => $barang->min_grosir_lv1,
                'min_grosir_lv2' => $barang->min_grosir_lv2,
                'min_grosir_lv3' => $barang->min_grosir_lv3,
                'min_grosir_lv4' => $barang->min_grosir_lv4,
                'harga_grosir_lv1' => $barang->harga_grosir_lv1,
                'harga_grosir_lv2' => $barang->harga_grosir_lv2,
                'harga_grosir_lv3' => $barang->harga_grosir_lv3,
                'harga_grosir_lv4' => $barang->harga_grosir_lv4,
                'stok' => $barang->stok_aplikasi ?? 0,
            );
        }
        
        echo json_encode($response);
    }
    // public function get_barang_by_barcode() {
    //     $barcode = $this->input->post('barcode');
    //     $item = $this->db->select('*, COALESCE(min_grosir_lv1, 0) as min_grosir_lv1, COALESCE(min_grosir_lv2, 0) as min_grosir_lv2, COALESCE(min_grosir_lv3, 0) as min_grosir_lv3, COALESCE(min_grosir_lv4, 0) as min_grosir_lv4')
    //                      ->get_where('barang', ['barcode' => $barcode])
    //                      ->row_array();
    //     echo json_encode(['status' => !empty($item), 'data' => $item]);
    // }
    // Get barang by barcode
     
    public function get_barang_by_barcode() {
        $barcode = $this->input->post('barcode');
        $barang = $this->Transaksi_model->get_barang_by_barcode($barcode);
        
        if($barang) {
            $response = array(
                'status' => true,
                'data' => array(
                    'id' => $barang->id,
                    'nama' => $barang->nama_barang,
                    'barcode' => $barang->barcode_ecer,
                    'harga_beli' => $barang->harga_beli_ecer,
                    'harga_beli_dos' => $barang->harga_beli_dos,
                    'isi_dos' => $barang->isi,
                    'harga' => $barang->harga_jual_ecer,
                    'harga_jual_dos' => $barang->harga_jual_dos,
                    'min_grosir_lv1' => $barang->min_grosir_lv1,
                    'min_grosir_lv2' => $barang->min_grosir_lv2,
                    'min_grosir_lv3' => $barang->min_grosir_lv3,
                    'min_grosir_lv4' => $barang->min_grosir_lv4,
                    'harga_grosir_lv1' => $barang->harga_grosir_lv1,
                    'harga_grosir_lv2' => $barang->harga_grosir_lv2,
                    'harga_grosir_lv3' => $barang->harga_grosir_lv3,
                    'harga_grosir_lv4' => $barang->harga_grosir_lv4,
                     
                )
            );
        } else {
            $response = array(
                'status' => false,
                'message' => 'Barang tidak ditemukan'
            );
        }
        
        echo json_encode($response);
    }
     // Proses transaksi
    public function proses_transaksi() {
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('sub_total', 'Sub Total', 'required');
        $this->form_validation->set_rules('total', 'Total', 'required');
        $this->form_validation->set_rules('bayar', 'Bayar', 'required');
        $this->form_validation->set_rules('kembali', 'Kembali', 'required');
        $this->form_validation->set_rules('metode_bayar', 'Metode Bayar', 'required');
        
        if($this->form_validation->run() == FALSE) {
            $response = array(
                'status' => false,
                'message' => validation_errors()
            );
        } else {
            // Generate ID Transaksi
            // $id_transaksi = $this->Transaksi_model->generate_id_transaksi();
            $id_transaksi = $this->input->post('id_transaksi');
            
            // Data Transaksi
            $data_transaksi = array(
                'id_transaksi' => $id_transaksi,
                'id_kantor' => $this->input->post('id_kantor'),
                'id_admin' => $this->input->post('id_admin'),
                'id_member' => $this->input->post('id_member'),
                'sub_total' => str_replace('.', '', $this->input->post('sub_total')),
                'total' => str_replace('.', '', $this->input->post('total')),
                'bayar' => str_replace('.', '', $this->input->post('bayar')),
                'kembali' => str_replace('.', '', $this->input->post('kembali')),
                'status' => 'LUNAS',
                'metode_bayar' => $this->input->post('metode_bayar'),
                'ket_metode' => $this->input->post('ket_metode')
            );
            
            // Data Detail Transaksi
            $detail_transaksi = array();
            $history_transaksi = array();
            foreach($this->input->post('id_barang') as $key => $id_barang) {
                //data barang
                $this->db->where('id',$id_barang);
                $query2  = $this->db->get('tb_barang');
                $row2    = $query2->row();
                $harga_beli_dos  = $row2->harga_beli_dos;
                $harga_beli_ecer  = $row2->harga_beli_ecer;
                $harga_jual_dos  = $row2->harga_jual_dos;
                $isi  = $row2->isi;
                 

                #cari stok
                $id_kantor = $this->input->post('id_kantor');
                $this->db->where('id_barang',$id_barang);
                $this->db->where('id_kantor',$id_kantor);
                $query1  = $this->db->get('tb_stok');
                $row1    = $query1->row();
                $stok_awal  = $row1->stok_aplikasi;
                $satuan = $this->input->post('satuan')[$key];
                if($satuan == 'dos'){
                    $isi_dos = $this->input->post('isi_dos')[$key];
                    $jum = $this->input->post('jumlah')[$key];
                    $jum_new =  $jum * $isi_dos ;
                    $harga_beli = $harga_beli_dos/$isi;
                    $harga_jual = $harga_jual_dos/$isi;
                    
                }else {
                    $jum_new = $this->input->post('jumlah')[$key];
                    $harga_beli = $harga_beli_ecer;
                    $harga_jual = str_replace('.', '', $this->input->post('harga_jual')[$key]);
                }
                

                $stok_akhir  = $stok_awal - $jum_new ;
                
                $id_admin= $this->input->post('id_admin');

                     //update stok gudang
                 $data5=array(

                    'stok_aplikasi'=> $stok_akhir

                  );
                   $this->db->where('id_barang',$id_barang);
                   $this->db->where('id_kantor',$id_kantor);
                   $this->db->update('tb_stok',$data5);



                //input data history
                

               

                //point
                // $new_point = $cek_point - $potongan;
                // $dataxx=array(

                //   'point'=> $new_point

                // );
                // $this->db->where('id_member',$id_member);
                // $this->db->update('tb_member',$dataxx);
                

                //entry ke detail transaksi
                $detail_transaksi[] = array(
                    'id_transaksi' => $id_transaksi,
                    'id_barang' => $id_barang,
                    'id_kantor' => $this->input->post('id_kantor'),
                    'id_admin' => $this->input->post('id_admin'),
                    'stok_awal' => $stok_awal,
                    'stok_akhir' => $stok_akhir,
                    'satuan' => $this->input->post('satuan')[$key],
                    'isi_dos' => $this->input->post('isi_dos')[$key],
                    // 'harga_beli' => str_replace('.', '', $this->input->post('harga_beli')[$key]),
                    'harga_beli' => $harga_beli,
                    'harga_jual' => $harga_jual,
                    'jumlah' => $jum_new,
                    'harga_total' => str_replace('.', '', $this->input->post('harga_total')[$key])
                );

                $history_transaksi[]=array(
                    'id_history' =>'',
                    'id_barang'     =>  $id_barang, 
                    'id_kantor' => $this->input->post('id_kantor'),
                    'id_admin' => $this->input->post('id_admin'),
                    'jumlah'      =>  $this->input->post('jumlah')[$key],
                    
                    'keterangan'=>  'terjual',
                    'id_transaksi'=>  $id_transaksi, 

                  );
            }
            
            // Simpan transaksi
            $simpan = $this->Transaksi_model->simpan_transaksi($data_transaksi, $detail_transaksi, $history_transaksi);
            
            if($simpan) {
                $response = array(
                    'status' => true,
                    'message' => 'Transaksi berhasil disimpan',
                    'id_transaksi' => $id_transaksi
                );
            } else {
                $response = array(
                    'status' => false,
                    'message' => 'Gagal menyimpan transaksi'
                );
            }
        }
        
        echo json_encode($response);
    }

    // public function cari_barang(){
    //     $term = $this->input->get('term');
    //     $data = $this->Barang_model->get_by_barcode_or_name($term);
    //     $res = array_map(function($b){
    //         return [
    //             'label' => $b->nama_barang,
    //             'value' => $b->nama_barang,
    //             'barcode' => $b->barcode_ecer,
    //             'harga' => $b->harga_jual_ecer
    //         ];
    //     }, $data);
    //     echo json_encode($res);
    // }
    // public function get_barang_by_barcode(){
    //     $bc = $this->input->post('barcode');
    //     $b = $this->Barang_model->get_by_barcode($bc);
    //     if($b){
    //         echo json_encode(['status'=>true,'data'=>$b]);
    //     } else {
    //         echo json_encode(['status'=>false,'message'=>'Barang tidak ditemukan']);
    //     }
    // }

    // public function proses_transaksi(){
    //     // Contoh dalam fungsi proses_transaksi
        
    //     $id_transaksi = $this->input->post('id_transaksi');
    //     $sub = (int)$this->input->post('sub_total');
    //     $total = (int)$this->input->post('total');
    //     $bayar = (int)$this->input->post('bayar');
    //     $kembali = (int)$this->input->post('kembali');
    //     $metode = $this->input->post('metode_bayar');
    //     $ket = $this->input->post('ket_metode');

    //     $barang = $this->input->post('id_barang');
    //     $harga = $this->input->post('harga_jual');
    //     $jumlah = $this->input->post('jumlah');
    //     $htot = $this->input->post('harga_total');

    //     $transaksi = [
    //         'id_transaksi' => $id_transaksi,
    //         'sub_total'=>$sub,
    //         'total'=>$total,
    //         'bayar'=>$bayar,
    //         'kembali'=>$kembali,
    //         'status'=>'success',
    //         'metode_bayar'=>$metode,
    //         'ket_metode'=>$ket
    //     ];$details = [];
    //     foreach($barang as $i=>$idb){
    //         $details[] = [
    //             'id_transaksi' => $id_transaksi,
    //             'id_barang'=>$idb,
    //             'harga_beli'=>0,
    //             'harga_jual'=>$harga[$i],
    //             'jumlah'=>$jumlah[$i],
    //             'harga_total'=>$htot[$i]
    //         ];
    //     }
    //     $id_trans = $this->Transaksi_model->simpan($transaksi, $details);
    //     echo json_encode(['status'=>true,'id_transaksi'=>$id_trans]);
    // }

    // public function generate_id_transaksi()
    // {
    //     $tanggal = date('Ymd'); // Format tanggal: 20250710
    //     $prefix = 'TRX' . $tanggal;

    //     // Ambil ID terakhir berdasarkan tanggal hari ini
    //     $this->db->select('id_transaksi');
    //     $this->db->like('id_transaksi', $prefix); // cari yang mulai dengan TRX20250710
    //     $this->db->order_by('id_transaksi', 'DESC');
    //     $this->db->limit(1);
    //     $last = $this->db->get('tb_transaksi')->row();

    //     if ($last) {
    //         // Ambil angka terakhir dan tambahkan
    //         $last_number = (int)substr($last->id_transaksi, -4);
    //         $next_number = str_pad($last_number + 1, 4, '0', STR_PAD_LEFT);
    //     } else {
    //         $next_number = '0001';
    //     }

    //     $new_id = $prefix . '-' . $next_number;

    //     echo json_encode([
    //         'status' => true,
    //         'id_transaksi' => $new_id
    //     ]);
    // }

    

     
}