<?php

namespace App\Http\Controllers\API;
use App\Models\Bills;
use App\Models\BillsList;
use App\Models\Repaire;
use App\Models\STORE\Store;
use App\Models\ListRepaireItem;
use App\Models\ACC\AccTRN;
use App\Models\Order;
use App\Models\STORE\Product;
use App\Models\STORE\Barcode;
use App\Models\STORE\Unit;
use App\Models\Service;
use App\Models\Quotation;
use App\Models\QuotationList;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BillsController extends Controller
{
    //
    public function index()
    {
        if(check_roles('bill_access')){

        $key = \Request::get('s');
        $filter = \Request::get('filter');

        if($key==''){
            if($filter=='pay'){

                $bills = Bills::where('bills.work_status','success')->where('bills.status','payed')
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();

            } elseif($filter=='unpay'){

                $bills = Bills::where('bills.work_status','success')->where('bills.status','pending')
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();

            } else {
                    $bills = Bills::where('bills.work_status','success')
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
            }
            
        } else {
            if($filter=='pay'){
                $bills = Bills::where('bills.work_status','success')->where('bills.status','payed')->where('bills.billnum_id','LIKE',"%{$key}%")->orWhere('bills.customer_name','LIKE',"%{$key}%")
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
            } elseif($filter=='unpay'){
                $bills = Bills::where('bills.work_status','success')->where('bills.status','pending')->where('bills.billnum_id','LIKE',"%{$key}%")->orWhere('bills.customer_name','LIKE',"%{$key}%")
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
            } else {
                $bills = Bills::where('bills.work_status','success')->where('bills.billnum_id','LIKE',"%{$key}%")->orWhere('bills.customer_name','LIKE',"%{$key}%")
                ->leftJoin('customers', 'customers.id', '=', 'bills.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'bills.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('bills.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
            }
            
        }

        
        return array_reverse($bills);

        } else {
           $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }
    }

    public function edit($id)
    {
        if(check_roles('bill_edit')){

            $bill = Bills::where('work_status','success')->where('billnum_id',$id)
            ->join('users','users.id','=','bills.user_id')
            ->select('bills.*','users.name','users.last_name','users.sex')
            ->get();
            $billslist = BillsList::where('work_status','success')->where('billnum_id',$id)->get();
            $allProduct = Product::get();
            $db_product = [];
            foreach($billslist as $bl){
                foreach($allProduct as $pro){
                if($bl['product_id']==$pro['product_id']){
                    array_push($db_product, (object)[
                        'product_id' => $pro['product_id'],
                        'in_store' => $pro['in_store'],
                        'in_store_pack' => $pro['in_store_pack'],
                        'product_unit_type' => $pro['product_unit_type']
                    ]);
                }
                }
            }



            $response = [
                'db_product' => $db_product,
                'data_bills' => $bill,
                'billslist' => $billslist,
                'success' => true,
            ];
            return response()->json($response);

        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }
    }
    public function addbills(Request $request)
    {
        if(check_roles('bill_add')){
            try {
                Bills::where('work_status','create')->delete();

                // start permission
                $billg = Bills::all()->sortByDesc('created_at')->take(1)->toArray();
                $number = 1;
                foreach($billg as $bill)
                {
                    $number = $bill['billnum_id'];
                }

                if($number!=''){

                    $number = str_replace("SIT","",$number);
                    $number = (int)$number+1;
                    $length = 5;
                    $number = substr(str_repeat(0, $length).$number, - $length);
                }

                
                $bills = new Bills();
                    $bills->status = 'pending';
                    $bills->signed = 'false';
                    $bills->billnum_id = 'SIT'.$number;
                    $bills->tax = '0';
                    $bills->work_status = 'create';
                    $bills->save();
                    $bill_id = $bills->id;
                    $billnum_id = $bills->billnum_id;
                    $dateCreat = $bills->created_at;
                    $success = true;
                    $message = 'add bill success!';

                 // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ສ້າງໃບບິນໃໝ່ ເລກທີ່: '.$billnum_id,'success');

            } catch (\Illuminate\Database\QueryException $ex) {
                $billnum_id = false;
                $success = false;
                $dateCreat = '';
                $message = $ex->getMessage();
                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ສ້າງໃບບິນໃໝ່ error: '.$message,'error');
            }



            $response = [
                'number' => $number,
                'billnum_id' => $billnum_id,
                'success' => $success,
                'dateCreate' => $dateCreat,
                'message' => $message,
            ];
            return response()->json($response);

        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }
    }

    public function addbillRe(Request $request)
    {
        if(check_roles('bill_add')){
        // start permission

        try {

        $CheckBill = Bills::where('billnum_id',$request->billID)->count();
        if($request->billUpdate=='true' && $CheckBill == '1'){
            /// ------------- upadte ----------------
            $billID = $request->billID;
            $bill_que = Bills::where('billnum_id',$billID)->get();

            if($bill_que[0]->status=='payed'){
                $message = 'ໃບບິນເລກທີ: '.$billID.' ໄດ້ຊຳລ່ະແລ້ວ, ບໍ່ອານຸຍາດໃຫ້ແກ້ໄຂ ລາຍການໃບບິນໄດ້!';
                $response = [
                    'success' => false,
                    'message' => $message,
                ];
                return response()->json($response);
             } else {

                // ລຶບຂໍ້ມູນເກົ່າ
                BillsList::where('billnum_id',$billID)->delete();
                AccTRN::where('bill_id',$billID)->delete();
                /// update repaire
                $repaire = Repaire::where('renum_id',$request->renum_id)
                ->update([
                    'all_price' => $request->totalAmount,
                 ]);
                $bill = Bills::where('billnum_id',$billID)
                    ->update([
                        'all_credit' => $request->totalAmount,
                        'all_count' => $request->totalCount,
                        'signed'=> $request->signed,
                        'ListBilldata' => json_encode($request->ListBilldata),
                        'office_id' => $request->office_id,
                        'customer_id' => $request->customer_id,
                        'customer_name' => $request->customer_name,
                        'customer_tel' => $request->customer_tel,
                        'customer_address' => $request->customer_address,

                    ]);
                /// ອັບເດດ ລາຍການໃບບິນຄືນ
                /// update repaire
                //$repaire = Repaire::where('renum_id',$request->renum_id) ->update([ 'billnum_id' => $billID ]);

                /// add item repaire to list bill
                $litem = ListRepaireItem::where('renum_id',$request->renum_id)->get();

                foreach($request->list_bill as $list){
                    $billslist = new BillsList();
                        $billslist->billnum_id = $billID;
                        $billslist->name = $list['product_name'];
                        $billslist->detail = null;
                        $billslist->bill_type = $list['bill_type'];
                        $billslist->product_id = $list['product_id'];
                        $billslist->bill_list_id = $list['id'];
                        $billslist->barcode = $list['barcode'];
                        $billslist->count = $list['count'];
                        $billslist->credit = $list['price'];
                        $billslist->work_status = 'success';
                        $billslist->save();
                        //$billslist_id = $billslist->id;

                        /// add to TRN ---------------------------------------------------------------------------------
                        if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                        $trn_type ='cincome';

                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }
                        if($trn_type=='income'){ $tnum = 'INC'; }
                        elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                        elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                        elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ

                        // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                        $accs = new AccTRN([
                            'trn_id' => $tnum.$number,
                            'bill_list_id' => $list['id'],
                            'barcode' => $list['barcode'],
                            'bill_id' => $billID,
                            'trn_type' => $trn_type,
                            'acc_trn_detail' => $list['product_name'],
                            'amount' => $list['price'],
                            'count' => $list['count'],
                            'sum' => (int)$list['price'] * (int)$list['count'],
                            'rate' => '1',
                            'dr' => $dr,
                            'cr' => $cr,
                            'user_id' => $request->user_id,
                            'work_status'=> 'success'
                        ]);
                        $accs->save();
                        //// end add TRN -----------------------------------------------------------------

                       
                    // ຈົບ ບັນທຶກລາຍຈ່າຍຕົ້ນທຶນຊື້ --------------------------------------------------------------------

              

                    /// ຈົບທຸລະກຳ --------------------------------------------

                }



                }
                //return $bill_que[0]->status;
                //Bills::where('billnum_id',$id)->delete();
                //BillsList::where('billnum_id',$billID)->delete();
                //AccTRN::where('bill_id',$billID)->delete();
                $billnum_id = $billID;
                }
                else
                { /// -------------------- add normal ------------------

                if($request->status){ $ChStatus = 'payed'; } else{ $ChStatus = 'pending'; }
                if($request->signed) { $sg = 'true'; } else { $sg = 'false'; }
                if($request->tax) { $st = 10; } else { $st = 0; }

                $billg = Bills::all()->sortByDesc('created_at')->take(1)->toArray();
                $number = 1;
                foreach($billg as $bill)
                {
                    $number = $bill['billnum_id'];
                }

                if($number!=''){

                    $number = str_replace("SIT","",$number);
                    $number = (int)$number+1;
                // $number = 98765;
                    $length = 5;
                    $number = substr(str_repeat(0, $length).$number, - $length);
                }

                $bills = new Bills();
                    $bills->status = 'pending';
                    $bills->signed = 'false';
                    $bills->billnum_id = 'SIT'.$number;

                    $bills->office_id = $request->office_id;
                    $bills->customer_id = $request->customer_id;
                    $bills->customer_detail = $request->customer_detail;
                    $bills->customer_name = $request->customer_name;
                    $bills->customer_tel = $request->customer_tel;
                    $bills->customer_address = $request->customer_address;
                    $bills->user_id = $request->user_id;
                    $bills->signed = $request->signed;
                    $bills->customer_type = $request->customer_type;
                    $bills->all_credit = $request->totalAmount;
                    $bills->all_count = $request->totalCount;
                    $bills->tax = $st;
                    $bills->discut = $request->discount;                    //ok
                    $bills->ListBilldata = json_encode($request->ListBilldata);
                    $bills->work_status = 'success';
                // $bills->status = $ChStatus;

                    $bills->save();
                    $bill_id = $bills->id;
                    $billnum_id = $bills->billnum_id;

                    // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                    save_logs('ສ້າງໃບບິນໃໝ່ ຈາກລາຍການສ້ອມແປງ ບິນເລກທີ່: '.$billnum_id,'success');

                /// update repaire
                Repaire::where('renum_id',$request->renum_id) ->update([ 'billnum_id' => $billnum_id ]);

                foreach($request->list_bill as $list){
                    $billslist = new BillsList();
                        $billslist->billnum_id = $billnum_id;
                        $billslist->name = $list['product_name'];
                        $billslist->detail = null;
                        $billslist->bill_type = $list['bill_type'];
                        $billslist->product_id = $list['product_id'];
                        $billslist->bill_list_id = $list['id'];
                        $billslist->barcode = $list['barcode'];
                        $billslist->count = $list['count'];
                        $billslist->credit = $list['price'];
                        $billslist->work_status = 'success';
                        $billslist->save();
                        //$billslist_id = $billslist->id;

                        /// add to TRN ---------------------------------------------------------------------------------
                        // if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }

                        // $trn_type ='cincome';

                        // $repaire = AccTRN::all()->sortByDesc('id')->take(1)->toArray();
                        // $number = 1;
                        // foreach($repaire as $re)
                        // { $number = $re['trn_id']; }
                        // if($number!=''){
                        //     $number1 = str_replace("INC","",$number);
                        //     $number2 = str_replace("EXP","",$number1);
                        //     $number3 = str_replace("CAP","",$number2);
                        //     $number4 = str_replace("CIN","",$number3);
                        //     $number = (int)$number4+1;
                        //     $length = 8;
                        //     $number = substr(str_repeat(0, $length).$number, - $length);
                        // }
                        // if($trn_type=='income'){ $tnum = 'INC'; }
                        // elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                        // elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                        // elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ

                        // // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                        // $accs = new AccTRN([
                        //     'trn_id' => $tnum.$number,
                        //     'bill_list_id' => $list['id'],
                        //     'barcode' => $list['barcode'],
                        //     'bill_id' => $billnum_id,
                        //     'trn_type' => $trn_type,
                        //     'acc_trn_detail' => $list['product_name'],
                        //     'amount' => $list['price'],
                        //     'count' => $list['count'],
                        //     'sum' => (int)$list['price'] * (int)$list['count'],
                        //     'rate' => '1',
                        //     'dr' => $dr,
                        //     'cr' => $cr,
                        //     'user_id' => $request->user_id,
                        //     'work_status'=> 'success'
                        // ]);
                        // $accs->save();

                        $trn_type ='cincome';

                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                        $number = $trn_org[0]['trn_id'];
                        
                        if($number){
                            $number1 = str_replace("INC","",$number);
                            $number2 = str_replace("EXP","",$number1);
                            $number3 = str_replace("CAP","",$number2);
                            $number4 = str_replace("CIN","",$number3);
                            $number5 = str_replace("EXC","",$number4);
                            $number = (int)$number5+1;
                            $length = 8;
                            $number = substr(str_repeat(0, $length).$number, - $length);
                           
                        } else {
                            $number_c = 1;
                            $number = substr(str_repeat(0, $length).$number_c, - $length);
                        }


                                    if($trn_type=='income'){ $tnum = 'INC'; }
                                    elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                                    elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                                    elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                                    if($list['bill_type'] == 'product'){
                                        $dr = '411'; $cr = '707';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                                    } elseif($list['bill_type'] == 'service') {
                                        $dr = '411'; $cr = '706';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '706'; } else { $dr = '551'; $cr = '706'; }
                                    }

                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $list['id'],
                                        'barcode' => $list['barcode'],
                                        'bill_id' => $billnum_id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => $list['product_name'],
                                        'amount' => $list['price'],
                                        'count' => $list['count'],
                                        'sum' => (int)$list['price'] * (int)$list['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();
                        //// end add TRN -----------------------------------------------------------------

                       
                    // ຈົບ ບັນທຶກລາຍຈ່າຍຕົ້ນທຶນຊື້ --------------------------------------------------------------------

              

                    /// ຈົບທຸລະກຳ --------------------------------------------

                }

                // old list bill
                /// add item repaire to list bill
                // $litem = ListRepaireItem::where('renum_id',$request->renum_id)->get();

                // foreach($litem as $li)
                // {
                //     // add to list bill bill_type
                //     $billslist = new BillsList();
                //     $billslist->billnum_id = $billnum_id;
                //     $billslist->name = $li['name'];
                //     $billslist->detail = $li['detail'];
                //     $billslist->bill_type = $li['bill_type'];
                //     $billslist->product_id = $li['product_id'];
                //     $billslist->count = $li['count'];
                //     $billslist->credit = $li['credit'];
                //     $billslist->save();


                //     /// add TRN -------------------------
                //     $repaire = AccTRN::all()->sortByDesc('id')->take(1)->toArray();
                //     $number = 1;
                //     $trn_type = 'cincome';
                //     foreach($repaire as $re)
                //     { $number = $re['trn_id']; }
                //     if($number!=''){
                //         $number1 = str_replace("INC","",$number);
                //         $number2 = str_replace("EXP","",$number1);
                //         $number3 = str_replace("CAP","",$number2);
                //         $number4 = str_replace("CIN","",$number3);
                //         $number = (int)$number4+1; $length = 8;
                //         $number = substr(str_repeat(0, $length).$number, - $length); }
                //     if($trn_type=='income'){ $tnum = 'INC'; }
                //     elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                //     elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                //     elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                //     if($li['bill_type'] == 'product'){
                //         $dr = '411'; $cr = '707';
                //         //if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                //     } elseif($li['bill_type'] == 'service') {
                //         $dr = '411'; $cr = '706';
                //         //if($request->CashType=='true') { $dr = '571'; $cr = '706'; } else { $dr = '551'; $cr = '706'; }
                //     }

                //     $accs = new AccTRN([
                //         'trn_id' => $tnum.$number,
                //         'bill_list_id' => $li['id'],
                //         'bill_id' => $billnum_id,
                //         'trn_type' => $trn_type,
                //         'acc_trn_detail' => $li['name'],
                //         'amount' => $li['credit'],
                //         'count' => $li['count'],
                //         'sum' => (int)$li['credit'] * (int)$li['count'],
                //         'rate' => '1',
                //         'dr' => $dr,
                //         'cr' => $cr,
                //         'user_id' => $request->user_id
                //     ]);
                //     $accs->save();
                //     /// end TRN -----------------------------
                // }



            }



                    $success = true;
                    $message = 'customer register successfully';
                } catch (\Illuminate\Database\QueryException $ex) {
                    $billnum_id = false;
                    $success = false;
                    $message = $ex->getMessage();

                    // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                    save_logs('ສ້າງໃບບິນໃໝ່ error: '.$message,'error');
                }

                $response = [
                    'number' => $number,
                    'billnum_id' => $billnum_id,
                    'success' => $success,
                    'message' => $message,
                ];
                return response()->json($response);

            /// end permissions
        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }

    }

    public function addbillpos(Request $request){

        if(check_roles('bill_add')){

        // start permission

        /// add bill on pos system

        $billg = Bills::all()->sortByDesc('created_at')->take(1)->toArray();
        $number = 1;
        foreach($billg as $bill)
        {
            $number = $bill['billnum_id'];
        }

        if($number!=''){

            $number = str_replace("SIT","",$number);
            $number = (int)$number+1;
           // $number = 98765;
            $length = 5;
            $number = substr(str_repeat(0, $length).$number, - $length);
        }

       // $listorder = $request->listorder;



       // return $listorder;

        try {
            /// add bill

            $bills = new Bills();

                $bills->status = 'pending';
                $bills->signed = 'false';
                $bills->billnum_id = 'SIT'.$number;
                $bills->user_id = $request->user_id;                    //ok
                $bills->customer_type = $request->customer_type;        //ok
                $bills->office_id = $request->office_id;                //ok
                $bills->customer_id = $request->customer_id;            //ok
                $bills->customer_name = $request->customer_name;        //ok
                $bills->customer_tel = $request->customer_tel;          //ok
                $bills->customer_address = $request->customer_address;  //ok
                $bills->signed = 'true';                                //ok
                $bills->all_credit = $request->totalAmount;             //ok
                $bills->all_count = $request->totalCount;               //ok
                $bills->tax = $request->tax_amount;                     //ok
                $bills->discut = $request->discount;                    //ok
                $bills->ListBilldata = json_encode($request->ListBilldata);
                $bills->work_status = 'success';
                $bills->status = 'payed';

                $bills->save();
                $bill_id = $bills->id;
                $billnum_id = $bills->billnum_id;

                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ສ້າງໃບບິນໃໝ່ ຈາກຂາຍໜ້າຮ້ານ POS ເລກທີ່: '.$billnum_id,'success');

                /// add to list bill

                foreach($request->list_bill as $list){
                    $billslist = new BillsList();
                        $billslist->billnum_id = $billnum_id;
                        $billslist->name = $list['product_name'];
                        $billslist->detail = null;
                        $billslist->bill_type = $list['bill_type'];
                        $billslist->product_id = $list['product_id'];
                        $billslist->bill_list_id = $list['id'];
                        $billslist->barcode = $list['barcode'];
                        $billslist->count = $list['count'];
                        $billslist->credit = $list['price'];
                        $billslist->work_status = 'success';
                        $billslist->save();
                        //$billslist_id = $billslist->id;

                        /// add to TRN ---------------------------------------------------------------------------------
                        if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                        $trn_type ='income';

                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                        $number = $trn_org[0]['trn_id'];
                        
                        if($number){
                            $number1 = str_replace("INC","",$number);
                            $number2 = str_replace("EXP","",$number1);
                            $number3 = str_replace("CAP","",$number2);
                            $number4 = str_replace("CIN","",$number3);
                            $number5 = str_replace("EXC","",$number4);
                            $number = (int)$number5+1;
                            $length = 8;
                            $number = substr(str_repeat(0, $length).$number, - $length);
                           
                        } else {
                            $number_c = 1;
                            $number = substr(str_repeat(0, $length).$number_c, - $length);
                        }

                        if($trn_type=='income'){ $tnum = 'INC'; }
                        elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                        elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                        elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ

                        // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                        $accs = new AccTRN([
                            'trn_id' => $tnum.$number,
                            'bill_list_id' => $list['id'],
                            'barcode' => $list['barcode'],
                            'bill_id' => $billnum_id,
                            'trn_type' => $trn_type,
                            'acc_trn_detail' => $list['product_name'],
                            'amount' => $list['price'],
                            'count' => $list['count'],
                            'sum' => (int)$list['price'] * (int)$list['count'],
                            'rate' => '1',
                            'dr' => $dr,
                            'cr' => $cr,
                            'user_id' => $request->user_id,
                            'work_status'=> 'success'
                        ]);
                        $accs->save();
                        //// end add TRN -----------------------------------------------------------------

                        /// ບັນທຶກລາຍຈ່າຍ ຕົ້ນທຶນ ---------------------------------------------------
                    if($list['product_id']!='' && $list['product_id']!='0'){
                        if($list['unit']=='unit'){
                            $product_que = Product::where('product_id',$list['product_id'])->get();
                            $price_buy = $product_que[0]->product_price_buy;

                        //  $trn_type=='expense';
                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                        $number = $trn_org[0]['trn_id'];
                        
                        if($number){
                            $number1 = str_replace("INC","",$number);
                            $number2 = str_replace("EXP","",$number1);
                            $number3 = str_replace("CAP","",$number2);
                            $number4 = str_replace("CIN","",$number3);
                            $number5 = str_replace("EXC","",$number4);
                            $number = (int)$number5+1;
                            $length = 8;
                            $number = substr(str_repeat(0, $length).$number, - $length);
                           
                        } else {
                            $number_c = 1;
                            $number = substr(str_repeat(0, $length).$number_c, - $length);
                        }

                            $trn_type ='expense';
                            $tnum = 'EXP';
                            $dr = '607';
                            $cr = '307';

                            // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                            $accs = new AccTRN([
                                'trn_id' => $tnum.$number,
                                'bill_list_id' => $list['id'],
                                'bill_id' => $billnum_id,
                                'trn_type' => $trn_type,
                                'acc_trn_detail' => 'ຄິດໄລ່ ລາຍຈ່າຍຕົ້ນທຶນ: '.$list['product_name'],
                                'amount' => $price_buy,
                                'count' => $list['count'],
                                'sum' => (int)$price_buy * (int)$list['count'],
                                'rate' => '1',
                                'dr' => $dr,
                                'cr' => $cr,
                                'user_id' => $request->user_id,
                                'work_status'=> 'success'
                            ]);
                            $accs->save();


                        } else if($list['unit']=='pack'){

                            $product_que = Product::where('product_id',$list['product_id'])->get();
                            $price_buy = (int)$product_que[0]->product_price_buy/(int)$product_que[0]->product_unit_type;

                        //  $trn_type=='expense';
                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                        $number = $trn_org[0]['trn_id'];
                        
                        if($number){
                            $number1 = str_replace("INC","",$number);
                            $number2 = str_replace("EXP","",$number1);
                            $number3 = str_replace("CAP","",$number2);
                            $number4 = str_replace("CIN","",$number3);
                            $number5 = str_replace("EXC","",$number4);
                            $number = (int)$number5+1;
                            $length = 8;
                            $number = substr(str_repeat(0, $length).$number, - $length);
                           
                        } else {
                            $number_c = 1;
                            $number = substr(str_repeat(0, $length).$number_c, - $length);
                        }

                            $trn_type ='expense';
                            $tnum = 'EXP';
                            $dr = '607';
                            $cr = '307';

                            // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                            $accs = new AccTRN([
                                'trn_id' => $tnum.$number,
                                'bill_list_id' => $list['id'],
                                'bill_id' => $billnum_id,
                                'trn_type' => $trn_type,
                                'acc_trn_detail' => 'ຄິດໄລ່ ລາຍຈ່າຍຕົ້ນທຶນ: '.$list['product_name'].'(ຂາຍຍ່ອຍ)',
                                'amount' => $price_buy,
                                'count' => $list['count'],
                                'sum' => (int)$price_buy * (int)$list['count'],
                                'rate' => '1',
                                'dr' => $dr,
                                'cr' => $cr,
                                'user_id' => $request->user_id,
                                'work_status'=> 'success'
                            ]);
                            $accs->save();
                        }
                    }
                    // ຈົບ ບັນທຶກລາຍຈ່າຍຕົ້ນທຶນຊື້ --------------------------------------------------------------------

                    /// ບັນທຶກ ການຕັດສະຕ໋ອກ
                    // if($list['product_id']!=''){

                    //     $product_que = Product::where('product_id',$list['product_id'])->get();
                    //     $product = Product::where('product_id',$list['product_id']);
                    //         $product->update([
                    //             'in_store' => (int)$product_que[0]->in_store - (int)$list['count']
                    //         ]);


                    // }

                    // ບັນທຶກ Order
                    $bill_que = Bills::where('billnum_id',$billnum_id)->get();
                    $order = new Order();
                    $order->billnum_id = $billnum_id;
                    $order->product_id = $list['product_id'];
                    $order->count = $list['count'];
                    $order->price = $list['price'];
                    $order->customer_id = $bill_que[0]->customer_id;
                    $order->user_id = $bill_que[0]->user_id;
                    $order->status = 'true';
                    $order->save();

                    /// ຈົບທຸລະກຳ --------------------------------------------

                }

                // ລົງບັນຊີ ສ່ວນຫຼຸດໃຫ້ລູກຄ້າ
                if($request->discount){
                    if($request->CashType=='true') { $dr = '619'; $cr = '571'; } else { $dr = '619'; $cr = '551'; }
                    $trn_type='expense'; /// ປະເພດລາຍຈ່າຍ
                    $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }
                        if($trn_type=='income'){ $tnum = 'INC'; }
                        elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                        elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                        elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ

                        // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                        $accs = new AccTRN([
                            'trn_id' => $tnum.$number,
                            'bill_list_id' => '',
                            'barcode' => '',
                            'bill_id' => $billnum_id,
                            'trn_type' => $trn_type,
                            'acc_trn_detail' => 'ລົງບັນຊີສ່ວນຫຼຸດໃຫ້ລູກຄ້າ ເລກທີ່ໃບບິນ: '.$billnum_id,
                            'amount' => $request->discount,
                            'count' => 1,
                            'sum' => (int)$request->discount,
                            'rate' => '1',
                            'dr' => $dr,
                            'cr' => $cr,
                            'user_id' => $request->user_id,
                            'work_status'=> 'success'
                        ]);
                        $accs->save();

                        save_logs('ລົງບັນຊີສ່ວນຫຼຸດໃຫ້ລູກຄ້າ ຈາກຂາຍໜ້າຮ້ານ POS ບິນເລກທີ່: '.$billnum_id,'success');
                }
                

                //// update

                foreach($request->ListBilldata[0]['db_product'] as $cinstore){
                    Product::where('product_id',$cinstore['product_id'])->update([ 'in_store' => $cinstore['in_store'], 'in_store_pack' => $cinstore['in_store_pack']]);
                  }


                $success = true;
                $message = 'add bills pos successfully';
            } catch (\Illuminate\Database\QueryException $ex) {
                $billnum_id = false;
                $success = false;
                $message = $ex->getMessage();

                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ສ້າງໃບບິນໃໝ່ error: '.$message,'error');
            }

            $response = [
                'Bills_id'=> $billnum_id,
                'success' => $success,
                'message' => $message,
            ];

            return response()->json($response);
        /// end permission
        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }

    }

    public function import_quotation_to_bill($id, Request $request){

       // return $request->customer_name;

        if(check_roles('bill_add')){
            try {


                $quo = Quotation::where('quonum_id',$id)->get();
                if($quo[0]['billnum_id']){
                    $billnum_id = $quo[0]['billnum_id'];
                    $dateCreat = $quo[0]['created_at'];
                }else{
                        Bills::where('work_status','create')->delete();
                        // start permission
                        $billg = Bills::all()->sortByDesc('created_at')->take(1)->toArray();
                        $number = 1;
                        foreach($billg as $bill)
                        {
                            $number = $bill['billnum_id'];
                        }
                        if($number!=''){
                            $number = str_replace("SIT","",$number);
                            $number = (int)$number+1;
                            $length = 5;
                            $number = substr(str_repeat(0, $length).$number, - $length);
                        }

                        $bills = new Bills();
                            $bills->status = 'pending';
                            $bills->signed = 'false';
                            $bills->billnum_id = 'SIT'.$number;
                            $bills->tax = '0';
                            $bills->work_status = 'create';
                            $bills->save();

                            $bill_id = $bills->id;
                            $billnum_id = $bills->billnum_id;
                            $dateCreat = $bills->created_at;

                            Quotation::where('quonum_id',$id)
                            ->update([
                                'billnum_id' => $billnum_id,
                            ]);

                            save_logs('ສ້າງໃບບິນໃໝ່ ເພື່ອນຳເຂົ້າຈາກ ໃບສະເໜີລາຄາ ເລກທີ່: '.$billnum_id,'success');
                }

                



                // update after create

                if($request->status){ $ChStatus = 'payed'; } else{ $ChStatus = 'pending'; }
                if($request->signed) { $sg = 'true'; } else { $sg = 'false'; }
                if($request->tax) { $st = 10; } else { $st = 0; }
                $trn_type = $request->trn_type;

                $bill = Bills::where('billnum_id',$billnum_id)
                    ->update([
                        'office_id' => $request->office_id,
                        'customer_id' => $request->customer_id,
                        // 'customer_detail' => $request->customer_detail,
                        'customer_name' => $request->customer_name,
                        'customer_tel' => $request->customer_tel,
                        'customer_address' => $request->customer_address,
                        'user_id' => $request->user_id,
                        'signed' => $sg,
                        'customer_type' => $request->customer_type,
                        'all_credit' => $request->totalAmount,
                        'all_count' => $request->totalCount,
                        'tax' => $request->tax_amount,
                        'discut' => $request->discount,
                        'status' => $ChStatus,
                        'ListBilldata'=> $request->ListBilldata,
                        'work_status'=> 'success'
                    ]);

                    //  print_r($request->ListBilldata[0]['db_product']);

                  foreach($request->ListBilldata[0]['db_product'] as $cinstore){
                    Product::where('product_id',$cinstore['product_id'])->update([ 'in_store' => $cinstore['in_store'], 'in_store_pack' => $cinstore['in_store_pack']]);
                  }

                    /// add bill list

                    $blist = BillsList::where('work_status','success')->where('billnum_id',$billnum_id)->get();
                    $billslist = false;
                    $listbills_old = array();
                    $listbills_new = array();
                    if($bill){
                        foreach($request->list_bill as $lb){
                            // add new list bill to array
                            array_push($listbills_new,$lb['id']);
                            if(count($blist)>0){
                                foreach($blist as $b){
                                    if($b['billnum_id']==$billnum_id && $b['billnum_id']!='' && $b['bill_list_id']==$lb['id'] && $b['bill_list_id']!=''){
                                            
                                                $blistup = BillsList::where('billnum_id',$billnum_id)->where('bill_list_id',$lb['id']);
                                                $blistup->update([
                                                    'count' => (int)$lb['count'],
                                                    'credit' => (int)$lb['price'],
                                                    'work_status'=> 'success'
                                                ]);
                                       
                                            // updat trn list

                                            $blistup = AccTRN::where('bill_id',$billnum_id)->where('bill_list_id',$lb['id']);
                                            $blistup->update([
                                                'count' => (int)$lb['count'],
                                                'amount' => (int)$lb['price'],
                                                'sum' => (int)$lb['price']*(int)$lb['count'],
                                                'work_status'=> 'success'
                                            ]);
                                    }
                                    // add old list bill to array
                                    array_push($listbills_old,$b['bill_list_id']);
                                }

                                //  ມີການເພີ່ມລາຍການ ໃໝ່ໃນໃບບິນ ໃຫ້ເພີ່ມເຂົ້າ
                                if(!in_array($lb['id'] , $listbills_old)){

                                    $billslist_upnew = new BillsList();
                                    $billslist_upnew->billnum_id = $billnum_id;
                                    $billslist_upnew->name = $lb['product_name'];
                                    $billslist_upnew->detail = null;
                                    $billslist_upnew->bill_type = $lb['bill_type'];
                                    $billslist_upnew->product_id = $lb['product_id'];
                                    $billslist_upnew->bill_list_id = $lb['id'];
                                    $billslist_upnew->barcode = $lb['barcode'];
                                    $billslist_upnew->count = $lb['count'];
                                    $billslist_upnew->credit = $lb['price'];
                                    $billslist_upnew->work_status = 'success';
                                    $billslist_upnew->save();

                                    //  ບັນທຶກລົງລາຍການ ເຄື່ອນໄຫວບັນຊີ

                                    $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }


                                    if($trn_type=='income'){ $tnum = 'INC'; }
                                    elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                                    elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                                    elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                                    if($lb['bill_type'] == 'product'){
                                        $dr = '411'; $cr = '707';
                                    } elseif($lb['bill_type'] == 'service') {
                                        $dr = '411'; $cr = '706';
                                    }

                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $lb['id'],
                                        'barcode' => $lb['barcode'],
                                        'bill_id' => $billnum_id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => $lb['product_name'],
                                        'amount' => $lb['price'],
                                        'count' => $lb['count'],
                                        'sum' => (int)$lb['price'] * (int)$lb['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();

                                    // ຈົບ

                                    save_logs('ອັບເດດໃບບິນ ເລກທີ່: '.$id.' ເພີ່ມລາຍການໃໝ່: '.$lb['product_name'],'success');
                                }



                            }
                            else{

                              $billslist = new BillsList();
                                    $billslist->billnum_id = $billnum_id;
                                    $billslist->name = $lb['product_name'];
                                    $billslist->detail = null;
                                    $billslist->bill_type = $lb['bill_type'];
                                    $billslist->product_id = $lb['product_id'];
                                    $billslist->bill_list_id = $lb['id'];
                                    $billslist->barcode = $lb['barcode'];
                                    $billslist->count = $lb['count'];
                                    $billslist->credit = $lb['price'];
                                    $billslist->work_status = 'success';
                                    $billslist->save();

                            }


                             /// update list item

                             $bill_list_up = BillsList::where('billnum_id',$billnum_id)->where('work_status','success')->get();
                             foreach($bill_list_up as $ql){
                                 if($lb['id']==$ql['bill_list_id']){
                                    BillsList::where('billnum_id',$billnum_id)->where('bill_list_id',$ql['bill_list_id'])->where('work_status','success')
                                     ->update([
                                     'name' => $lb['product_name'],
                                     'count' => $lb['count'],
                                     'credit' => $lb['price'],
                                     'work_status'=> 'success'
                                 ]);

                                 // update trn 
                                 AccTRN::where('bill_id',$billnum_id)->where('bill_list_id',$ql['bill_list_id'])->where('work_status','success')
                                        ->update([
                                        'acc_trn_detail' => $lb['product_name'],
                                        'count' => $lb['count'],
                                        'amount' => $lb['price'],
                                        'amount' => (int)$lb['price']*(int)$lb['count'],
                                        'work_status'=> 'success'
                                    ]);

                             }
                             }

                        }

                         //  ກວດຊອບ ລາຍການໃບບິນ ທີ່ຖຶກລຶບອກ
                         $checkDellistbill = BillsList::where('work_status','success')->where('billnum_id',$billnum_id)->get();
                         foreach($checkDellistbill as $b){
                             if(!in_array($b['bill_list_id'] , $listbills_new)){
                                        if($b['bill_type']=='product'){
                                                    $barcode_getunit = Barcode::where('barcode',$b['barcode'])->get();
                                                    $getunit = Unit::where('id',$barcode_getunit[0]['unit'])->get();
                                                    $product_getunittype = Product::where('product_id',$b['product_id'])->get();
                                                    $product_unit_type = $product_getunittype[0]['product_unit_type'];
                                                    $count = $b['count'];
                                                    if($getunit[0]['unit_to']==1){
                                                        // unit
                                                        $in_store = (int)$product_getunittype[0]['in_store']+(int)$count;
                                                        $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+((int)$count*(int)$product_unit_type);
                                                        Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                                    } else {
                                                        // pack
                                                        $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+(int)$count;
                                                        $in_store = floor((int)$in_store_pack/(int)$product_unit_type);
                                                        Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                                    }
                                        }

                                            $blistup = BillsList::where('work_status','success')->where('billnum_id',$billnum_id)->where('bill_list_id',$b['bill_list_id']);
                                            $blistup->update([ 'work_status'=> 'reject' ]);
                                            $blistup = AccTRN::where('work_status','success')->where('bill_id',$billnum_id)->where('bill_list_id',$b['bill_list_id']);
                                            $blistup->update([ 'work_status'=> 'reject' ]);
                                           save_logs('ຍົກເລີກລາຍການໃນໃບບິນ (reject) ເລກທີ່: '.$billnum_id.' ລາຍການ: '.$b['name'],'success');
                             }
                         }
                    }

                    //save_logs('ນຳເຂົ້າ ສ້າງໃບບິນໃໝ່ ເລກທີ່:'.$billnum_id,'success');

                    if($billslist){
                        //$trn_type = 'cincome';

                        if(!$request->status){
                            // check status save
                            AccTRN::where('bill_id',$billnum_id)->delete();
                            $litem = BillsList::where('billnum_id',$billnum_id)->get();
                                foreach($litem as $li)
                                {
                                    $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }

                                    if($trn_type=='income'){ $tnum = 'INC'; }
                                    elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                                    elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                                    elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                                    if($li['bill_type'] == 'product'){
                                        $dr = '411'; $cr = '707';
                                    } elseif($li['bill_type'] == 'service') {
                                        $dr = '411'; $cr = '706';
                                    }

                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $li['bill_list_id'],
                                        'barcode' => $li['barcode'],
                                        'bill_id' => $billnum_id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => $li['name'],
                                        'amount' => $li['credit'],
                                        'count' => $li['count'],
                                        'sum' => (int)$li['credit'] * (int)$li['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();
                                }
                        }
                    }
                    


                    $success = true;
                    $message = 'ນຳລາຍການ ໃບສະເໜີລາຄາ ເຂົ້າໃບບິນສຳເລັດ!';

                 // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ນຳເຂົ້າສ້າງ ໃບບິນໃໝ່ ເລກທີ່: '.$billnum_id,'success');

            } catch (\Illuminate\Database\QueryException $ex) {
                $billnum_id = false;
                $success = false;
                //$dateCreat = '';
                $message = $ex->getMessage();
                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ນຳເຂົ້າ ສ້າງໃບບິນໃໝ່ error: '.$message,'error');
            }



            $response = [
                //'number' => $number,
                'billnum_id' => $billnum_id,
                'success' => $success,
                //'dateCreate' => $dateCreat,
                'message' => $message,
            ];
            return response()->json($response);

        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }

    }

    public function update($id, Request $request)
    {
        if(check_roles('bill_edit')){
            // start permissions
        $bill_check = Bills::where('billnum_id',$id)->get();
        if($bill_check[0]->status=='pending'){

            if($request->status){ $ChStatus = 'payed'; } else{ $ChStatus = 'pending'; }
                if($request->signed) { $sg = 'true'; } else { $sg = 'false'; }
                if($request->tax) { $st = 10; } else { $st = 0; }
                $trn_type = $request->trn_type;
            
                

                //$bill = Bills::find($id);
                


               // else
                //{
                  $bill = Bills::where('billnum_id',$id)
                    ->update([
                        'office_id' => $request->office_id,
                        'customer_id' => $request->customer_id,
                        // 'customer_detail' => $request->customer_detail,
                        'customer_name' => $request->customer_name,
                        'customer_tel' => $request->customer_tel,
                        'customer_address' => $request->customer_address,
                        'user_id' => $request->user_id,
                        'signed' => $sg,
                        'customer_type' => $request->customer_type,
                        'all_credit' => $request->totalAmount,
                        'all_count' => $request->totalCount,
                        'tax' => $request->tax_amount,
                        'discut' => $request->discount,
                       // 'status' => $ChStatus,
                        'ListBilldata'=> $request->ListBilldata,
                        'work_status'=> 'success'
                    ]);

                    // ຕັດສິນຄ້າໃນ Store
                  //  print_r($request->ListBilldata[0]['db_product']);

                  foreach($request->ListBilldata[0]['db_product'] as $cinstore){
                    Product::where('product_id',$cinstore['product_id'])->update([ 'in_store' => $cinstore['in_store'], 'in_store_pack' => $cinstore['in_store_pack']]);
                  }

                    /// add bill list

                    $blist = BillsList::where('work_status','success')->where('billnum_id',$id)->get();
                    $billslist = false;
                    $listbills_old = array();
                    $listbills_new = array();
                    if($bill){
                        foreach($request->list_bill as $lb){
                            // add new list bill to array
                            array_push($listbills_new,$lb['id']);
                            if(count($blist)>0){
                                foreach($blist as $b){
                                    if($b['billnum_id']==$id && $b['billnum_id']!='' && $b['bill_list_id']==$lb['id'] && $b['bill_list_id']!=''){
                                            
                                                $blistup = BillsList::where('billnum_id',$id)->where('bill_list_id',$lb['id']);
                                                $blistup->update([
                                                    'count' => (int)$lb['count'],
                                                    'credit' => (int)$lb['price'],
                                                    'work_status'=> 'success'
                                                ]);
                                       
                                            // updat trn list

                                            $blistup = AccTRN::where('bill_id',$id)->where('bill_list_id',$lb['id']);
                                            $blistup->update([
                                                'count' => (int)$lb['count'],
                                                'amount' => (int)$lb['price'],
                                                'sum' => (int)$lb['price']*(int)$lb['count'],
                                                'work_status'=> 'success'
                                            ]);
                                    }
                                    // add old list bill to array
                                    array_push($listbills_old,$b['bill_list_id']);
                                }

                                //  ມີການເພີ່ມລາຍການ ໃໝ່ໃນໃບບິນ ໃຫ້ເພີ່ມເຂົ້າ
                                if(!in_array($lb['id'] , $listbills_old)){


                                    $billslist_upnew = new BillsList();
                                    $billslist_upnew->billnum_id = $id;
                                    $billslist_upnew->name = $lb['product_name'];
                                    $billslist_upnew->detail = null;
                                    $billslist_upnew->bill_type = $lb['bill_type'];
                                    $billslist_upnew->product_id = $lb['product_id'];
                                    $billslist_upnew->bill_list_id = $lb['id'];
                                    $billslist_upnew->barcode = $lb['barcode'];
                                    $billslist_upnew->count = $lb['count'];
                                    $billslist_upnew->credit = $lb['price'];
                                    $billslist_upnew->work_status = 'success';
                                    $billslist_upnew->save();

                                    //  ບັນທຶກລົງລາຍການ ເຄື່ອນໄຫວບັນຊີ

                                    $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }


                                    if($trn_type=='income'){ $tnum = 'INC'; }
                                    elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                                    elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                                    elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                                    if($lb['bill_type'] == 'product'){
                                        $dr = '411'; $cr = '707';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                                    } elseif($lb['bill_type'] == 'service') {
                                        $dr = '411'; $cr = '706';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '706'; } else { $dr = '551'; $cr = '706'; }
                                    }

                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $lb['id'],
                                        'barcode' => $lb['barcode'],
                                        'bill_id' => $id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => $lb['product_name'],
                                        'amount' => $lb['price'],
                                        'count' => $lb['count'],
                                        'sum' => (int)$lb['price'] * (int)$lb['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();

                                    // ຈົບ

                                    save_logs('ອັບເດດໃບບິນ ເລກທີ່: '.$id.' ເພີ່ມລາຍການໃໝ່: '.$lb['product_name'],'success');
                                }



                            }
                            else{

                              $billslist = new BillsList();
                                    $billslist->billnum_id = $id;
                                    $billslist->name = $lb['product_name'];
                                    $billslist->detail = null;
                                    $billslist->bill_type = $lb['bill_type'];
                                    $billslist->product_id = $lb['product_id'];
                                    $billslist->bill_list_id = $lb['id'];
                                    $billslist->barcode = $lb['barcode'];
                                    $billslist->count = $lb['count'];
                                    $billslist->credit = $lb['price'];
                                    $billslist->work_status = 'success';
                                    $billslist->save();

                            }


                             /// update list item

                             $bill_list_up = BillsList::where('billnum_id',$id)->where('work_status','success')->get();
                             foreach($bill_list_up as $ql){
                                 if($lb['id']==$ql['bill_list_id']){
                                    BillsList::where('billnum_id',$id)->where('bill_list_id',$ql['bill_list_id'])->where('work_status','success')
                                     ->update([
                                     'name' => $lb['product_name'],
                                     'count' => $lb['count'],
                                     'credit' => $lb['price'],
                                     'work_status'=> 'success'
                                 ]);
                            /// update trn detail and price
                                 AccTRN::where('bill_id',$id)->where('bill_list_id',$ql['bill_list_id'])->where('work_status','success')
                                        ->update([
                                        'acc_trn_detail' => $lb['product_name'],
                                        'count' => $lb['count'],
                                        'amount' => $lb['price'],
                                        'amount' => (int)$lb['price']*(int)$lb['count'],
                                        'work_status'=> 'success'
                                    ]);
                             }
                             }

                        }

                         //  ກວດຊອບ ລາຍການໃບບິນ ທີ່ຖຶກລຶບອກ
                         $checkDellistbill = BillsList::where('work_status','success')->where('billnum_id',$id)->get();
                         //return $checkDellistbill;
                         //return $listbills_new;
                         foreach($checkDellistbill as $b){
                             if(!in_array($b['bill_list_id'] , $listbills_new)){
                                     //echo $b['bill_list_id']."-";
                                     //echo $b['bill_type']."-";

                                            // ລາຍການທີ່ຖຶກລຶບ ໃຫ້ສົ່ງຄືນ Store
                                            // ຂໍ້ມູນທີ່ຕ້ອງການ barcode, product_id, count
                                            // barcode ໄປດຶງຂໍ້ມູນຈາກ table barcde ເພື່ອຊອກຫາວ່າສິນຄ້າເປັນ pack ຫຼື unit
                                            // product_id ໄປດຶງຂໍ້ມູນຈາກ table product ເພື່ອຊອກຫາຕົວຄູນ ຂອງປະເພດ pack unit
                                            // ຈາກນັ້ນ ທຳການຄຳນວນ ແລ້ວອັບເດດ table product
                                            // ຖ້າແມ່ນ Product ໃຫ້ກວດຊອບການຕັດສະຕ໋ອກ
                                        if($b['bill_type']=='product'){
                                                    $barcode_getunit = Barcode::where('barcode',$b['barcode'])->get();
                                                    $getunit = Unit::where('id',$barcode_getunit[0]['unit'])->get();
                                                    $product_getunittype = Product::where('product_id',$b['product_id'])->get();


                                                // echo $getunit[0]['unit_to']."-";
                                                    //echo $product_getunittype[0]['in_store_pack'];

                                                    // if($getunit[0]['unit_to']==1){ $unit = 'unit'; } else { $unit = 'pack'; }
                                                    $product_unit_type = $product_getunittype[0]['product_unit_type'];
                                                    $count = $b['count'];

                                                    if($getunit[0]['unit_to']==1){
                                                        // unit
                                                        $in_store = (int)$product_getunittype[0]['in_store']+(int)$count;
                                                        $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+((int)$count*(int)$product_unit_type);
                                                        Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                                    } else {
                                                        // pack
                                                        $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+(int)$count;
                                                        $in_store = floor((int)$in_store_pack/(int)$product_unit_type);
                                                        Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                                    }
                                        }

                                            //  reject

                                            $blistup = BillsList::where('work_status','success')->where('billnum_id',$id)->where('bill_list_id',$b['bill_list_id']);
                                            $blistup->update([ 'work_status'=> 'reject' ]);

                                           // updat trn list

                                           $blistup = AccTRN::where('work_status','success')->where('bill_id',$id)->where('bill_list_id',$b['bill_list_id']);
                                            $blistup->update([ 'work_status'=> 'reject' ]);
                                           // log
                                           save_logs('ຍົກເລີກລາຍການໃນໃບບິນ (reject) ເລກທີ່: '.$id.' ລາຍການ: '.$b['name'],'success');
                             }
                         }
                    }


                    // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                    save_logs('ອັບເດດໃບບິນ ເລກທີ່: '.$id,'success');

                    if($billslist){
                        //$trn_type = 'cincome';

                        if(!$request->status){

                            // check status save
                            AccTRN::where('bill_id',$id)->delete();
                            $litem = BillsList::where('billnum_id',$id)->get();
                                foreach($litem as $li)
                                {

                                    $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }

                                    if($trn_type=='income'){ $tnum = 'INC'; }
                                    elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                                    elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                                    elseif($trn_type=='cincome'){ $tnum = 'CIN'; }

                                    if($li['bill_type'] == 'product'){
                                        $dr = '411'; $cr = '707';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '707'; } else { $dr = '551'; $cr = '707'; }
                                    } elseif($li['bill_type'] == 'service') {
                                        $dr = '411'; $cr = '706';
                                        //if($request->CashType=='true') { $dr = '571'; $cr = '706'; } else { $dr = '551'; $cr = '706'; }
                                    }

                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $li['bill_list_id'],
                                        'barcode' => $li['barcode'],
                                        'bill_id' => $id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => $li['name'],
                                        'amount' => $li['credit'],
                                        'count' => $li['count'],
                                        'sum' => (int)$li['credit'] * (int)$li['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();
                                }
                        }
                    }

                    

                    /// ຖ້າມີການຊຳລະ ----------------------------------

                if($request->PayStatus){
                        
                        
                        $litem = BillsList::where('billnum_id',$id)->where('work_status','success')->get();
                        foreach($litem as $li)
                        {
                            $trn_type = 'income';
                            
                                if($request->CashType=='true') { $dr = '571'; $cr = '411'; } else { $dr = '551'; $cr = '411'; }


                                $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                                $number = $trn_org[0]['trn_id'];
                                
                                if($number){
                                    $number1 = str_replace("INC","",$number);
                                    $number2 = str_replace("EXP","",$number1);
                                    $number3 = str_replace("CAP","",$number2);
                                    $number4 = str_replace("CIN","",$number3);
                                    $number5 = str_replace("EXC","",$number4);
                                    $number = (int)$number5+1;
                                    $length = 8;
                                    $number = substr(str_repeat(0, $length).$number, - $length);
                                   
                                } else {
                                    $number_c = 1;
                                    $number = substr(str_repeat(0, $length).$number_c, - $length);
                                }
                            if($trn_type=='income'){ $tnum = 'INC'; }
                            elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                            elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                            elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ



                            // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                            $acc = new AccTRN([
                                'trn_id' => $tnum.$number,
                                'bill_list_id' => $li['bill_list_id'],
                                'barcode' => $li['barcode'],
                                'bill_id' => $id,
                                'trn_type' => 'income',
                                'acc_trn_detail' => $li['name'],
                                'amount' => $li['credit'],
                                'count' => $li['count'],
                                'sum' => (int)$li['credit'] * (int)$li['count'],
                                'rate' => '1',
                                'dr' => $dr,
                                'cr' => $cr,
                                'user_id' => $request->user_id,
                                'work_status'=> 'success'
                            ]);
                            $acc->save();

                            /// ບັນທຶກລາຍຈ່າຍ ຕົ້ນທຶນ ---------------------------------------------------
                        if($li['product_id']!='' && $li['product_id']!='0'){
                            if($li['bill_type'] == 'product'){
                                    $product_que = Product::where('product_id',$li['product_id'])->get();
                                    $price_buy = $product_que[0]->product_price_buy;

                                //  $trn_type=='expense';
                                $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                                $number = $trn_org[0]['trn_id'];
                                
                                if($number){
                                    $number1 = str_replace("INC","",$number);
                                    $number2 = str_replace("EXP","",$number1);
                                    $number3 = str_replace("CAP","",$number2);
                                    $number4 = str_replace("CIN","",$number3);
                                    $number5 = str_replace("EXC","",$number4);
                                    $number = (int)$number5+1;
                                    $length = 8;
                                    $number = substr(str_repeat(0, $length).$number, - $length);
                                   
                                } else {
                                    $number_c = 1;
                                    $number = substr(str_repeat(0, $length).$number_c, - $length);
                                }

                                    $trn_type ='expense';
                                    $tnum = 'EXP';
                                    $dr = '607';
                                    $cr = '307';
                           
                                    // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                                    $accs = new AccTRN([
                                        'trn_id' => $tnum.$number,
                                        'bill_list_id' => $li['bill_list_id'],
                                        'barcode' => $li['barcode'],
                                        'bill_id' => $id,
                                        'trn_type' => $trn_type,
                                        'acc_trn_detail' => 'ຄິດໄລ່ ລາຍຈ່າຍຕົ້ນທຶນ: '.$li['name'],
                                        'amount' => $price_buy,
                                        'count' => $li['count'],
                                        'sum' => (int)$price_buy * (int)$li['count'],
                                        'rate' => '1',
                                        'dr' => $dr,
                                        'cr' => $cr,
                                        'user_id' => $request->user_id,
                                        'work_status'=> 'success'
                                    ]);
                                    $accs->save();      
                                }
                                elseif($li['bill_type'] == 'service'){
                                    // ຄິດໄລ່ຕົ້ນທຶນ ບໍລິການ


                                    $service_que = Service::where('service_id',$li['product_id'])->get();
                                    $price_buy_ser = $service_que[0]->price_buy;

                                    
                                    
                                //  $trn_type=='expense';
                                $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                                $number = $trn_org[0]['trn_id'];
                                
                                if($number){
                                    $number1 = str_replace("INC","",$number);
                                    $number2 = str_replace("EXP","",$number1);
                                    $number3 = str_replace("CAP","",$number2);
                                    $number4 = str_replace("CIN","",$number3);
                                    $number5 = str_replace("EXC","",$number4);
                                    $number = (int)$number5+1;
                                    $length = 8;
                                    $number = substr(str_repeat(0, $length).$number, - $length);
                                   
                                } else {
                                    $number_c = 1;
                                    $number = substr(str_repeat(0, $length).$number_c, - $length);
                                }

                                    $trn_type ='expense';
                                    $tnum = 'EXP';
                                    $dr = '608';
                                    $cr = '308';

                                    if($price_buy_ser!=null || $price_buy_ser !=''){
                                       
                                        // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                                        $accs = new AccTRN([
                                            'trn_id' => $tnum.$number,
                                            'bill_list_id' => $li['bill_list_id'],
                                            'barcode' => $li['barcode'],
                                            'bill_id' => $id,
                                            'trn_type' => $trn_type,
                                            'acc_trn_detail' => 'ຄິດໄລ່ ລາຍຈ່າຍຕົ້ນທຶນ: '.$li['name'],
                                            'amount' => $price_buy_ser,
                                            'count' => $li['count'],
                                            'sum' => (int)$price_buy_ser * (int)$li['count'],
                                            'rate' => '1',
                                            'dr' => $dr,
                                            'cr' => $cr,
                                            'user_id' => $request->user_id,
                                            'work_status'=> 'success',
                                        ]);
                                        $accs->save();   
                                    }   
                              
                                   
                                }
                            }
                            // ຈົບ ບັນທຶກລາຍຈ່າຍຕົ້ນທຶນຊື້ --------------------------------------------------------------------



                            // ບັນທຶກ Order
                            $bill_que = Bills::where('billnum_id',$id)->get();
                            $order = new Order();
                            $order->billnum_id = $li['billnum_id'];
                            $order->product_id = $li['product_id'];
                            $order->count = $li['count'];
                            $order->price = $li['credit'];
                            $order->customer_id = $bill_que[0]->customer_id;
                            $order->user_id = $bill_que[0]->user_id;
                            $order->status = 'true';
                            $order->save();

                        }

                        /// save trn



                        /// update bill
                        Bills::where('billnum_id',$id)
                        ->update([
                            'status' => $ChStatus
                        ]);
                        $bill = Bills::where('billnum_id',$id)->get();
                        //return $bill[0]['all_credit'];
                        // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                        save_logs('ຊຳລະເງິນ ບິນເລກທີ່: '.$id.' ມູນຄ່າ: '.number_format((int)$bill[0]['all_credit'], 0, ',', '.').' ກີບ','success');
                    //}

                    // ລົງບັນຊີ ສ່ວນຫຼຸດໃຫ້ລູກຄ້າ
                    if($request->discount){
                        if($request->CashType=='true') { $dr = '619'; $cr = '571'; } else { $dr = '619'; $cr = '551'; }
                        $trn_type='expense'; /// ປະເພດລາຍຈ່າຍ
                        $trn_org = AccTRN::orderBy('id', 'desc')->take(1)->get();
                            $number = $trn_org[0]['trn_id'];
                            
                            if($number){
                                $number1 = str_replace("INC","",$number);
                                $number2 = str_replace("EXP","",$number1);
                                $number3 = str_replace("CAP","",$number2);
                                $number4 = str_replace("CIN","",$number3);
                                $number5 = str_replace("EXC","",$number4);
                                $number = (int)$number5+1;
                                $length = 8;
                                $number = substr(str_repeat(0, $length).$number, - $length);
                               
                            } else {
                                $number_c = 1;
                                $number = substr(str_repeat(0, $length).$number_c, - $length);
                            }
                            if($trn_type=='income'){ $tnum = 'INC'; }
                            elseif($trn_type=='expense'){ $tnum = 'EXP'; }
                            elseif($trn_type=='capital'){ $tnum = 'CAP'; }
                            elseif($trn_type=='cincome'){ $tnum = 'INC'; } ///ປ່ຽນໃຫ້ເປັນລາຍຮັບ

                            // ບັນທຶກຂໍ້ມູນ ການເຄື່ອນໄຫວວັນຊີ
                            $accs = new AccTRN([
                                'trn_id' => $tnum.$number,
                                'bill_list_id' => '',
                                'barcode' => '',
                                'bill_id' => $id,
                                'trn_type' => $trn_type,
                                'acc_trn_detail' => 'ລົງບັນຊີສ່ວນຫຼຸດໃຫ້ລູກຄ້າ ເລກທີ່ໃບບິນ: '.$id,
                                'amount' => $request->discount,
                                'count' => 1,
                                'sum' => (int)$request->discount,
                                'rate' => '1',
                                'dr' => $dr,
                                'cr' => $cr,
                                'user_id' => $request->user_id,
                                'work_status'=> 'success'
                            ]);
                            $accs->save();

                            save_logs('ລົງບັນຊີສ່ວນຫຼຸດໃຫ້ລູກຄ້າ ຈາກຂາຍໜ້າຮ້ານ POS ບິນເລກທີ່: '.$id,'success');
                    }
                }
                    /// update billl

    

                }

                $success = true;
                $message = 'ການບັນທຶກຂໍ້ມູນ ສຳເລັດ!';
                $response = [
                    'success' => $success,
                    'message' => $message,
                ];
                return response()->json($response);


        /// end permission
        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }


    }

    public function delete($id)
    {

        if(check_roles('bill_remove')){
                // start permission
                /// update restall product


                    //----------------------------------------------------------------

                    //  ກວດຊອບ ລາຍການໃບບິນ ທີ່ຖຶກລຶບອກ
                    $checkDellistbill = BillsList::where('work_status','success')->where('billnum_id',$id)->where('barcode','!=','')->get();
                    foreach($checkDellistbill as $b){
                        // if(!in_array($b['bill_list_id'] , $listbills_new)){
                              // echo $b['bill_list_id']."-";

                                       // ລາຍການທີ່ຖຶກລຶບ ໃຫ້ສົ່ງຄືນ Store
                                       // ຂໍ້ມູນທີ່ຕ້ອງການ barcode, product_id, count
                                       // barcode ໄປດຶງຂໍ້ມູນຈາກ table barcde ເພື່ອຊອກຫາວ່າສິນຄ້າເປັນ pack ຫຼື unit
                                       // product_id ໄປດຶງຂໍ້ມູນຈາກ table product ເພື່ອຊອກຫາຕົວຄູນ ຂອງປະເພດ pack unit
                                       // ຈາກນັ້ນ ທຳການຄຳນວນ ແລ້ວອັບເດດ table product

                                       $barcode_getunit = Barcode::where('barcode',$b['barcode'])->get();
                                       $getunit = Unit::where('id',$barcode_getunit[0]['unit'])->get();
                                       $product_getunittype = Product::where('product_id',$b['product_id'])->get();


                                       $product_unit_type = $product_getunittype[0]['product_unit_type'];
                                       $count = $b['count'];

                                       if($getunit[0]['unit_to']==1){
                                           // unit
                                           $in_store = (int)$product_getunittype[0]['in_store']+(int)$count;
                                           $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+((int)$count*(int)$product_unit_type);
                                           Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                       } else {
                                           // pack
                                           $in_store_pack = (int)$product_getunittype[0]['in_store_pack']+(int)$count;
                                           $in_store = floor((int)$in_store_pack/(int)$product_unit_type);
                                           Product::where('product_id',$b['product_id'])->update([ 'in_store'=> $in_store, 'in_store_pack'=> $in_store_pack ]);

                                       }

                                       //  reject

                                       $blistup = BillsList::where('work_status','success')->where('billnum_id',$id)->where('bill_list_id',$b['bill_list_id']);
                                       $blistup->update([ 'work_status'=> 'reject' ]);

                                      // updat trn list

                                      $blistup = AccTRN::where('work_status','success')->where('bill_id',$id)->where('bill_list_id',$b['bill_list_id']);
                                       $blistup->update([ 'work_status'=> 'reject' ]);
                                      // log
                                      //save_logs('ຍົກເລີກລາຍການໃນໃບບິນ (reject) ເລກທີ່: '.$id.' ລາຍການ: '.$b['name']);
                        // }
                    }



                                   $bills = Bills::where('billnum_id',$id);
                                   $bills->update([ 'work_status'=> 'reject' ]);

                                    $blistup = BillsList::where('billnum_id',$id);
                                    $blistup->update([ 'work_status'=> 'reject' ]);

                                   // updat trn list

                                    $acctrn = AccTRN::where('bill_id',$id);
                                    $acctrn->update([ 'work_status'=> 'reject' ]);
                                   // log
                                   save_logs('ຍົກເລີກໃບບິນ (reject) ເລກທີ່: '.$id,'success');
                //     }
                // }

                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
               // save_logs('ລຶບໃບບິນ ເລກທີ່: '.$id.' ອອກຈາກລະບົບ');


                $success = true;
                $message = 'Delete successfully';
                $response = [
                    'success' => $success,
                    'message' => $message,
                ];
                return response()->json($response);
                /// end permission

        } else {
            $response = ['message' => 'ທ່ານ ບໍ່ມີສິດເຂົ້າເຖິງຂໍ້ມູນ!', ];
            return response()->json($response);
        }
    }
}
