<?php

namespace App\Http\Controllers\API;
use App\Models\Quotation;
use App\Models\QuotationList;
use App\Models\Repaire;
use App\Models\STORE\Product;
use App\Models\ListRepaireItem;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class QuotationController extends Controller
{
    //
    public function index()
    {
        if(check_roles('bill_access')){
            // start permissions
            $key = \Request::get('s');  
            if($key==''){ 
                $quotations = Quotation::where('quotations.work_status','success')
                ->leftJoin('customers', 'customers.id', '=', 'quotations.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'quotations.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('quotations.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
             } else {
                $quotations = Quotation::where('quotations.work_status','success')->where('quotations.quonum_id','LIKE',"%{$key}%")->orWhere('quotations.customer_name','LIKE',"%{$key}%")
                ->leftJoin('customers', 'customers.id', '=', 'quotations.customer_id')
                ->leftJoin('customer_offices', 'customer_offices.id', '=', 'quotations.office_id')
                ->orderBy('created_at', 'desc')
                ->paginate(10, array('quotations.*', 'customers.name','customers.last_name','customers.sex','customers.address','customers.tel', 'customer_offices.office_name','customer_offices.office_tel'))
                ->toArray();
             }
            

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

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

            $quo = Quotation::where('quonum_id',$id)->get();
            $quolist = QuotationList::where('work_status','success')->where('quonum_id',$id)->get();
            $allProduct = Product::get();
            $db_product = [];
            foreach($quolist 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_quos' => $quo,
                'quolist'=> $quolist,
                'success' => true,
            ];
            return response()->json($response);

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

        Quotation::where('work_status','create')->delete();

        /// start permissions
        $quotation = Quotation::all()->sortByDesc('created_at')->take(1)->toArray();
        $number = 1;
        foreach($quotation as $quo)
        {
            $number = $quo['quonum_id'];
        }

        if($number!=''){

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

        try {
        $quota = new Quotation();
            $quota->status = 'pending';
            $quota->signed = 'false';
            $quota->quonum_id = 'SQT'.$number;
            $quota->work_status = 'create';
            $quota->save();


            $quonum_id = $quota->quonum_id;
            $success = true;
            $message = 'customer register successfully';

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

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

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

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

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

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

            $quotation = Quotation::all()->sortByDesc('created_at')->take(1)->toArray();
            $number = 1;
            foreach($quotation as $quo)
            {
                $number = $quo['quonum_id'];
            }

            if($number!=''){

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

            try {
            $quota = new Quotation();
                $quota->status = 'pending';
                $quota->signed = 'false';
                $quota->quonum_id = 'SQT'.$number;

                $quota->office_id = $request->office_id;
                $quota->customer_id = $request->customer_id;
                $quota->customer_detail = $request->customer_detail;
                $quota->customer_name = $request->customer_name;
                $quota->customer_tel = $request->customer_tel;
                $quota->customer_address = $request->customer_address;
                $quota->user_id = $request->user_id;
            // $bills->signed = $sg;
                $quota->customer_type = $request->customer_type;
                $quota->all_credit = $request->totalAmount;
                $quota->all_count = $request->totalCount;
                $quota->tax = $st;
                $quota->discut = $request->discut;
            // $bills->status = $ChStatus;


                $quota->save();
                $quonum_id = $quota->quonum_id;

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

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

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

                foreach($litem as $li)
                {
                    // add to list bill
                    $quolist = new QuotationList();
                    $quolist->quonum_id = $quonum_id;
                    $quolist->name = $li['name'];
                    $quolist->detail = $li['detail'];
                    $quolist->product_id = $li['product_id'];
                    $quolist->count = $li['count'];
                    $quolist->credit = $li['credit'];
                    $quolist->save();
                }

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

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

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

    public function update($id, Request $request)
    {
        if(check_roles('bill_edit')){
                // start permissions

                try {

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

                $quo = Quotation::where('quonum_id',$id)
                ->update([
                    '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,
                    '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,
                    'ListBilldata'=> $request->ListBilldata,
                    'status' => $ChStatus,
                    'work_status'=> 'success'
                ]);

                $quot = QuotationList::where('work_status','success')->where('quonum_id',$id)->get();
                $billslist = false;
                $listbills_old = array();
                $listbills_new = array();

                if($quo){
                    foreach($request->list_bill as $lb){
                        // add new list bill to array
                        array_push($listbills_new,$lb['id']);

                        if(count($quot)>0){                                
                            foreach($quot as $b){
                                if($b['quonum_id']==$id && $b['quonum_id']!='' && $b['bill_list_id']==$lb['id'] && $b['bill_list_id']!=''){
                                        $blistup = QuotationList::where('quonum_id',$id)->where('bill_list_id',$lb['id']);
                                        $blistup->update([
                                            'count' => (int)$lb['count'],
                                            'credit' => (int)$lb['price'],
                                            'work_status'=> 'success'
                                        ]);

                                       
                                } 
                                // add old list bill to array
                                array_push($listbills_old,$b['bill_list_id']);
                            }
                           // print_r($listbills_old);
                            //  ມີການເພີ່ມລາຍການ ໃໝ່ໃນໃບບິນ ໃຫ້ເພີ່ມເຂົ້າ
                            if(!in_array($lb['id'] , $listbills_old)){  
                  
                                $quotlist = new QuotationList();
                                $quotlist->quonum_id = $id;
                                $quotlist->name = $lb['product_name'];
                                //$quotlist->detail = null;
                                $quotlist->quo_type = $lb['bill_type']; 
                                $quotlist->product_id = $lb['product_id'];
                                $quotlist->bill_list_id = $lb['id'];
                                $quotlist->barcode = $lb['barcode'];
                                $quotlist->count = $lb['count'];
                                $quotlist->credit = $lb['price'];
                                $quotlist->work_status = 'success';
                                $quotlist->save();
                                
                                // ຈົບ

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

                           
                            
                        }
                        else{

                          $quotlist = new QuotationList();
                                $quotlist->quonum_id = $id;
                                $quotlist->name = $lb['product_name'];
                                $quotlist->detail = null;
                                $quotlist->quo_type = $lb['bill_type']; 
                                $quotlist->product_id = $lb['product_id'];
                                $quotlist->bill_list_id = $lb['id'];
                                $quotlist->barcode = $lb['barcode'];
                                $quotlist->count = $lb['count'];
                                $quotlist->credit = $lb['price'];
                                $quotlist->work_status = 'success';
                                $quotlist->save();
                      
                        }
                        
                        /// update list item

                        $quo_up = QuotationList::where('quonum_id',$id)->where('work_status','success')->get();
                        foreach($quo_up as $ql){
                            if($lb['id']==$ql['bill_list_id']){
                                QuotationList::where('quonum_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'
                            ]);
                        }
                        }
                        
                    }
                    // 

                    $quot = QuotationList::where('work_status','success')->where('quonum_id',$id)->get();
                    foreach($quot as $b){
                        if(!in_array($b['bill_list_id'] , $listbills_new)){ 
                            $blistup = QuotationList::where('work_status','success')->where('quonum_id',$id)->where('bill_list_id',$b['bill_list_id']);
                            $blistup->update([ 'work_status'=> 'reject' ]);
                         }

                    }


                }
  

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

        // return response()->json('ຂໍ້ມູນໄດ້ຖຶກບັນທຶກ ສຳເລັດແລ້ວ!');
                $success = true;
                $message = 'ການບັນທຶກຂໍ້ມູນ ສຳເລັດ!';
            } catch (\Illuminate\Database\QueryException $ex) {
                $success = false;
                $message = $ex->getMessage();
                // ບັນທຶກ ການເຄື່ອນໄຫວ save logs
                save_logs('ອັບເດດ ໃບສະເໜີລາຄາໃໝ່ error: '.$message,'error');
            }

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

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

    public function delete($id)
    {

        if(check_roles('bill_remove')){
            // start permission

             //  ກວດຊອບ ລາຍການໃບບິນ ທີ່ຖຶກລຶບອກ
             $checkDellistbill = QuotationList::where('work_status','success')->where('quonum_id',$id)->where('barcode','!=','')->get();
             foreach($checkDellistbill as $b){

                                
                                //  reject

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

                               // updat trn list

                
             }

        // Quotation::where('quonum_id',$id)->delete();
        // QuotationList::where('quonum_id',$id)->delete();



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

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

        $success = true;
        $message = 'ຂໍ້ມູນໄດ້ຖຶກລຶບ ສຳເລັດແລ້ວ!';

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

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

        return response()->json($response);

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

    }
}
