<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Invoice;
use App\User;
use App\Product;
use App\Numbertowordconvertsconver;
use Session;

class InvController extends Controller
{

    public function __construct()
    {
       $this->middleware('auth');
    }

    function get_data(Request $request){
        
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $user_id = $user_data[0]->user_id;
        
        $results = app('db')->select("SELECT `mes_qto`.*, `mes_customer`.*, `mes_currancy`.*, `mes_country`.* FROM `mes_qto` LEFT JOIN `mes_customer` 
        ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` LEFT JOIN `mes_currancy` ON `mes_currancy`.`curr_id` = `mes_qto`.`po_currancy` 
        LEFT JOIN `mes_country` ON `mes_country`.`cnty_id` = `mes_customer`.`cust_country` where `po_ref_id`='$user_id' ORDER BY `mes_qto`.`po_id` DESC");
        
        for($i=0; $i<count($results); $i++){
            $link = "https://demo.webip.lk/nance/inv_view_pdf?id=".$results[$i]->uniq_id;
                $invvid = $results[$i]->po_id;
            if($results[$i]->po_payment!=1){$sts = "Not Paid"; $col = "";}else{$sts = "Paid"; $col = "green";}
            if($results[$i]->po_auth!=1){$auth = "Pending Authorize";}else{$auth = "Authorized";}
            if($results[$i]->po_status!=1){$status = "cancelled";}else{$status = "active";}
            $paym = app('db')->select("SELECT SUM(pay_amount) as paym from `mes_payment` where `pay_invid` =$invvid AND `pay_authrize` ='1'");
            if($paym[0]->paym){$paymnt=$paym[0]->paym;}else{$paymnt="0";}
            $bal = ($results[$i]->po_final_tot - $paymnt)-$results[$i]->return_amnt;
            
            $paym_pen = app('db')->select("SELECT SUM(pay_amount) as paym from `mes_payment` where `pay_invid` =$invvid AND `pay_authrize` ='0' AND `pay_stetus`='1' ");
            if($paym_pen[0]->paym){$paypend=$paym_pen[0]->paym; $col="yellow"; $sts="Pending";}else{$paypend="0";}
            
            $inv[] = array('inv_id'=>($results[$i]->qto_code.$results[$i]->po_id),'uniq'=>$results[$i]->uniq_id,'inv_tot'=>$results[$i]->po_tot_price,
            'inv_dis'=>$results[$i]->po_discount,'final_total'=>$results[$i]->po_final_tot,'inv_qty'=>$results[$i]->po_tot_qty,
            'free_qty'=>$results[$i]->po_tot_freqty,'item_count'=>$results[$i]->po_tot_items,'customer'=>$results[$i]->cust_company,'cutomer_adrs'=>$results[$i]->cust_addres,
            'cutomer_adrs'=>$results[$i]->cust_addres,'pdflink'=>$link,'created_on'=>$results[$i]->po_cdate,'payment_status'=>$sts,'payment_color'=>$col,'paid_amount'=>$paymnt
            ,'balance_to_pay'=>$bal,'Authorization'=>$auth,'inv_status'=>$status,
            'return_value'=>$results[$i]->return_amnt);
        }
        if(empty($inv)){
            $inv = "No Invoices";
        }
        
        $data = response()->json($inv);
            return $data;
    }

    function get_sin_data(Request $request, $id){
       
        $results = app('db')->select("SELECT `mes_qto`.*, `mes_customer`.*, `mes_currancy`.*, `mes_country`.* FROM `mes_qto` LEFT JOIN `mes_customer`
        ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` LEFT JOIN `mes_currancy` ON `mes_currancy`.`curr_id` = `mes_qto`.`po_currancy` 
        LEFT JOIN `mes_country` ON `mes_country`.`cnty_id` = `mes_customer`.`cust_country` where `mes_qto`.`po_id` ='$id'  LIMIT 1");
        if(count($results)<1){
            $data = response()->json("Incorrect ID");
        }else{
            $data = response()->json($results);
        }
        
        
            return $data;
    }

    function get_last_id(){
       
       $invoice = new Invoice();
       $last_id = $invoice->getqtnlast_id();

        $data = response()->json($last_id);
            return $data;
    }

    function ref_list(){
       
       $invoice = new Invoice();
       $list = $invoice->sales_ref_list();

        $data = response()->json($list);
            return $data;
    }

    function get_cust_byid(Request $request){
       
       $this->validate($request, [
            'refid' => 'required'
        ]);

       $id = $request->input('refid');

        $results = app('db')->select("SELECT * from `mes_customer` where `cust_status` ='1' AND `cust_salseperson` ='$id' AND `cust_city` !='0'");
      //  $results = app('db')->select("SELECT * from `mes_customer` where `cust_status` ='1' AND `cust_salseperson` ='$id'");


        $data = response()->json($results);
            return $data;

    }
    
    function get_sin_cust(Request $request){
        $this->validate($request, [
            'cust_id' => 'required'
        ]);

        $cust = $request->input('cust_id');
                $resultitem = app('db')->select("SELECT * FROM `mes_customer` where `cust_id` = '$cust'");
        
            if(count($resultitem)<1){
                $data = response()->json("Incorrect ID");
                
            }else if($resultitem[0]->cust_prov != 0){
                $data = response()->json($resultitem);
            }else{
                $data = response()->json("Please add city");
            }    


           // $data = response()->json($resultitem);
            return $data;
    }

    function get_prod_byref(Request $request){
       

       $id = $request->input('refid');
       
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $depo = $user_data[0]->user_depoid;

            if($depo!=0){
                $invoice = new Invoice();
                $depo = $invoice->get_sales_depo($id);
         
            $resultitem = app('db')->select("SELECT * FROM `mes_depot_stock` LEFT JOIN `mes_item` ON `mes_item`.`item_id` = `mes_depot_stock`.`dpstock_itemid` 
            LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` 
            where `mes_depot_stock`.`dpstock_dpoid` = '$depo' and `mes_item`.`item_status` =1 and `mes_category`.`cat_id` !=14 ORDER BY `mes_item`.`item_id`");

           
            }else{

               // $resultitem = app('db')->select("SELECT `stc_id`,`item_catcount`,`item_freqty`,`itm_code`,`itm_id`,`item_code`,`stc_code`,`stc_itemid`,`stc_qty`,`item_code`,`item_selling_price`,`itm_name`,`item_freeitm` FROM `mes_stock` LEFT JOIN `mes_item` ON `mes_item`.`item_id` = `mes_stock`.`stc_itemid` LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` where `mes_stock`.`stc_qty` > 0");
                    $resultitem = app('db')->select("SELECT `mes_stock`.`stc_id` as dpstock_id,`mes_stock`.`stc_itemid` as dpstock_itemid,`mes_stock`.`stc_grnid` as dpstock_dpoid ,`mes_stock`.`stc_qty` as dpstock_qty,`mes_item`.*,`item`.*,`mes_stock`.*,`mes_category`.*
                    FROM `mes_stock` LEFT JOIN `mes_item` ON `mes_item`.`item_id` = `mes_stock`.`stc_itemid` LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` 
                    LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` where `mes_item`.`item_status` =1 and `mes_category`.`cat_id` !=14 ORDER BY `mes_item`.`item_id`");

            }

        $data = response()->json($resultitem);
            return $data;

    }

    function chk_depo_stock(Request $request){

        $this->validate($request, [
            'refid' => 'required',
            'itemid' => 'required',
            'qty' => 'required'
        ]);

        $refid = $request->input('refid');
        $invoice = new Invoice();
                $depo = $invoice->get_sales_depo($refid);

        if($depo!="0"){
            $stk = new Invoice();
                $gt_stk = $stk->get_depo_item_stock($depo,$request->input('itemid'),$request->input('qty'));
        } else{
            $stk = new Invoice();
                $gt_stk = $stk->get_main_item_stock($depo,$request->input('itemid'),$request->input('qty'));
        }       

            $data = response()->json($depo);
            return $gt_stk;

    }

    function get_sin_item(Request $request){
        $this->validate($request, [
            'item_id' => 'required'
        ]);

        $item = $request->input('item_id');
                $resultitem = app('db')->select("SELECT * FROM `mes_item` LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` where `mes_item`.`item_id` = '$item'");


            $data = response()->json($resultitem);
            return $data;
    }

    function check_item_price(Request $request){
        $this->validate($request, [
            'item_id' => 'required',
            'item_price' => 'required'
        ]);

        $item = $request->input('item_id');
                
            $stk = new Invoice();
                $detail = $stk->chk_itm_price($item,$request->input('item_price'));    

            $data = response()->json($detail);
            return $data;
    }

    function check_free_count(Request $request){
        $this->validate($request, [
            'item_id' => 'required',
            'qty' => 'required',
            'free' => 'required'
        ]);

        $free = new Invoice();
                $max_free = $free->gt_free_item($request->input('item_id'),$request->input('qty'));

           if($request->input('free') > $max_free){
                $data = "Need Approval";
           }else{
                $data = "ok";
           }  

           return $data;   

    }

    function add_invoice_product(Request $request){
        $this->validate($request, [
            'refid' => 'required',
            'itemid' => 'required',
            'qty' => 'required',
            'price' => 'required',
            'free' => 'required'
        ]);
        $item = $request->input('itemid');
        $refid = $request->input('refid');
        $invoice = new Invoice();
                $depo = $invoice->get_sales_depo($refid);
            $totqty = $request->input('qty') + $request->input('free');    

            if($depo!="0"){
                $stk = new Invoice();
                    $gt_stk = $stk->get_depo_item_stock($depo,$request->input('itemid'),$totqty);
            } else{
                $stk = new Invoice();
                    $gt_stk = $stk->get_main_item_stock($depo,$request->input('itemid'),$totqty);
            }

            $free = new Invoice();
                            $max_free = $free->gt_free_item($request->input('itemid'),$request->input('qty'));

            $resultitem = app('db')->select("SELECT * FROM `mes_item` LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` where `mes_item`.`item_id` = '$item'");   
            $seluser =   app('db')->select("SELECT * from `mes_user` where `user_id` ='$refid'");     
            $usr = $seluser[0]->user_name;
          //  Session::set('uname',$usr);
          //  $_SESSION["uname"] = $usr;

         if($gt_stk!="No Stock"){     
                $prc = new Invoice();
                    $gt_prc = $prc->chk_itm_price($request->input('itemid'),$request->input('price'));

                        if(($gt_prc!="not approved") && ($request->input('price') < $resultitem[0]->item_selling_price)){
                            $aprvl = "1"; $det = "Need approval. Item Price is low";
                          
                        }elseif($request->input('free') > $max_free){
                                    $aprvl = "1"; $det = "Need approval. Free quantity Exceeded";
                               
                       }else{
                            $data[0] = "No Stock"; $aprvl = "0"; $det = "";
                        }
        $qty = $request->input('qty');
        $price = $request->input('price');
        $freeitm = $request->input('free');
    
                $resultinsert = app('db')->insert("INSERT INTO `temp_qto_items` (`temp_id`, `po_itm_item_id`, `po_itm_qty`, `po_itm_unitprice`, `po_itm_unit`, `po_aprvl`, `free_item`,
                `depo_id`, `po_user`) VALUES ('0', '$item', '$qty', '$price', '002','$aprvl', '$freeitm', '$depo', '$usr') ");
                $gt_ins_id =   app('db')->select("SELECT `po_itm_id` from `temp_qto_items` where `po_user` ='$usr' ORDER BY `po_itm_id` DESC LIMIT 1");
                $ins_id = $gt_ins_id[0]->po_itm_id;
                
                $resultinsert = app('db')->insert("INSERT INTO `temp_qto_items_test` (`temp_id`, `po_itm_item_id`, `po_itm_qty`, `po_itm_unitprice`, `po_itm_unit`, `po_aprvl`, `free_item`,
                `depo_id`, `po_user`) VALUES ('0', '$item', '$qty', '$price', '002','$aprvl', '$freeitm', '$depo', '$usr') ");


                $cal = new Invoice();
                   $cal_stock = $cal->cal_stock($depo,"temp",$ins_id,$item,$totqty,"min","0"); 

                if($resultinsert){
                    $data[0] = "Added to Invoice";
                }else{
                    $data[0] = "Not added";
                }

         }else{
            $data[0] = "No Stock";
            $det = "";
         }
        $data[1] =$det;
    return $data;

    }
    
    function get_temp_inv_data(Request $request){
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $uname = $user_data[0]->user_name;
        $resultitem = app('db')->select("SELECT * FROM `temp_qto_items` 
        LEFT JOIN `mes_item` ON `temp_qto_items`.`po_itm_item_id` = `mes_item`.`item_id` 
        LEFT JOIN `item` ON `item`.`itm_id` = `mes_item`.`item_name` 
        LEFT JOIN `mes_currancy` ON `temp_qto_items`.`po_itm_currancy` = `mes_currancy`.`curr_id` 
        LEFT JOIN `mes_unit` ON `temp_qto_items`.`po_itm_unit` = `mes_unit`.`unit_id` 
        LEFT JOIN `mes_model` ON `mes_model`.`model_id` = `mes_item`.`item_model`
        LEFT JOIN `mes_brand` ON `mes_brand`.`brand_id` = `mes_item`.`item_brand` 
        LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` WHERE `temp_qto_items`.`po_user` = '$uname' ORDER BY `temp_qto_items`.`temp_id` DESC");

    
            $dataa = response()->json($resultitem);
            return $dataa;

    }

    function create_new_invoice(Request $request){
        $this->validate($request, [
                'cus_id'  => 'required',
                'ref_id'  => 'required',
                'tot_price'  => 'required', 
                'discount'  => 'required',
                'final'  => 'required',
                'tot_qty'  => 'required',
                'other'  => 'required',
                'username'  => 'required'
        ]);

        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $u_name = $user_data[0]->user_name;
             $username = $user_data[0]->user_name;
             $udepo = $user_data[0]->user_depoid;
             $cust = $request->input('cus_id');
             $dis = $request->input('discount');
             $final = $request->input('final');
         
            $temp_item =   app('db')->select("SELECT `po_itm_id` from `temp_qto_items` where `po_user` ='$username'");     
            $count = count($temp_item);
        if($count<1){
            $dataa[0] = "Incorrect Data"; 
            return $dataa;
        }    
            $temp_totitem =   app('db')->select("SELECT SUM(`po_itm_qty`) as tot,SUM(`free_item`) as tot_free from `temp_qto_items` where `po_user` ='$username'");     
           $cal_tot = $temp_totitem[0]->tot;
           $cal_totfree = $temp_totitem[0]->tot_free;

        $get_dis =   app('db')->select("SELECT `cust_discount` from `mes_customer` where `cust_id` ='$cust'");  
        
                            if($get_dis[0]->cust_discount != 0.00){
                                    if($get_dis[0]->cust_discount < $dis){ 
                                        $discnt = $dis; $auth = 0; $authd = "Need Approval for Customer Discount";
                                    }else{
                                        $discnt = $get_dis[0]->cust_discount; $auth = 1; $authd = "No Authorization needed";}
                            }else if(0 < $dis){
                                $discnt = $dis;
                                    $auth = 0;  $authd = "Need Approval for Customer Discount";
                            }else{
                                $discnt = $get_dis[0]->cust_discount;
                                $auth = 1;$authd = "No Authorization needed";
                            } 

       
        $num_val = new Numbertowordconvertsconver; 
        $last_val = $num_val->convert_number($final);
            
            $tempNum = explode('.', $final);
            $num1 =  $num_val->convert_number($tempNum[0]);
            $num2 = $num_val->convert_number($tempNum[1]);
            
            if($tempNum[1]!=00){
               $finl= $num1." and ". $num2." cents only";
                
            }else{$finl= $num1." and ". $num2." only";}
            $date = date('Y-m-d');   
            $refid = $request->input('ref_id');
            $totprice = $request->input('tot_price');
            $cust_dis = $get_dis[0]->cust_discount;
            if($cust_dis!=$dis){
                $ndis = $dis;
            }else{
                $ndis = $cust_dis;
            }
            
            $fintot = $request->input('final');
            $tot_qty = $request->input('tot_qty');
            $other = $request->input('other');

        $unc = new Invoice();
        $uniq_id = $unc->unique_code(8);
        
        $outs = new Invoice();
        $outt = $outs->outstand($cust);
        $out = $outt+$fintot;
        
        $resultinsert = app('db')->insert("INSERT INTO `mes_qto` (`uniq_id`,`po_sup_id`,`po_sup_outstand`, `po_ref_id`, `po_tot_price`, `po_discount`, `po_final_tot`, 
        `po_tot_qty`, `po_tot_items`, `po_other`, 
        `po_currancy`, `po_delevery`,`po_fwording`, `po_cuser`, `po_remark`, `po_cdate`, `po_auth`,`po_tot_freqty`,`depo`) VALUES 
        ('$uniq_id','$cust','$out', '$refid', '$totprice', '$ndis', '$fintot', '$cal_tot', '$count', 
        '$other', '0001', '0.00','$finl' ,'$username', '','$date', '$auth','$cal_totfree','$udepo')");    

            if($resultinsert){
                $dataa[0][0] = "Invoice Created";
                $dataa[0][1] = $uniq_id;
                
                $gt_id =   app('db')->select("SELECT `po_id` from `mes_qto` where `uniq_id` ='$uniq_id' and `po_cuser`='$username'");
            $insert_id = $gt_id[0]->po_id;
            
                $updt = app('db')->update("UPDATE `temp_qto_items` SET `po_itm_po_id`='$insert_id',`temp_id`='$insert_id' WHERE `po_user` = '$username'"); 
                $temp_item =   app('db')->select("SELECT * from `temp_qto_items` where `po_itm_po_id` ='$insert_id'");
            
            
                $tot_free = $cal_tot_val = 0;    
                    foreach ($temp_item as $row) {
                       $itminsert = app('db')->insert("INSERT INTO `qto_items`( `po_itm_item_id`, `depo_id`, `po_itm_po_id`,`service_des`, `po_itm_qty`, `free_item`,
                       `po_itm_unit`, `po_itm_unitprice`, `po_itm_currancy`, `po_itm_description`, `po_aprvl`, `po_user`) VALUES 
                       ('$row->po_itm_item_id','$row->depo_id','$row->po_itm_po_id','$row->service_des','$row->po_itm_qty','$row->free_item','$row->po_itm_unit','$row->po_itm_unitprice',
                       '$row->po_itm_currancy','$row->po_itm_description','$row->po_aprvl','$username')");    
                            
                            if($itminsert){
                                $tot_free = $tot_free + $row->free_item;
                                $updt_id = $row->po_itm_id;
                                $cal_tot_val = $cal_tot_val+ ($row->po_itm_unitprice*$row->po_itm_qty);
                              $updt_inv = app('db')->update("UPDATE `mes_inventry` SET `invt_type_id`='$insert_id',`invt_type`='INV' WHERE `invt_type_id` = '$updt_id' and `invt_type` = 'temp'"); 
                            $updt = app('db')->delete("DELETE FROM `temp_qto_items` WHERE `po_itm_id` = '$updt_id' and `po_itm_po_id` ='$insert_id'");
                                
                            }
                            
                    }
                    $cnt =   app('db')->select("SELECT `po_itm_po_id` from `qto_items` where `po_itm_po_id` ='$insert_id' and `po_aprvl` ='1'");
                    $count2 = count($cnt);
                    if(($count2 > 0)||($auth!=1)){$aprl = '0';}else{$aprl = '1';}
                        $tempNum = explode('.', $cal_tot_val);
                        $num1 =  $num_val->convert_number($tempNum[0]);
                        if(isset($tempNum[1])){
                            $num2 = $num_val->convert_number($tempNum[1]);
                        }else{
                            $num2 = "zero";
                        }
                        
                        if($num2!="zero"){
                           $finl= $num1." and ". $num2." cents only";
                            
                        }else{$finl= $num1." and ". $num2." only";}
                    
                    $updt = app('db')->update("UPDATE `mes_qto` SET `po_tot_freqty`='$tot_free',`po_final_tot`='$cal_tot_val',`po_fwording`='$finl'
                           ,`po_auth`='$aprl' WHERE `po_id` = '$insert_id'");
                    
                    $rtn = app('db')->select("SELECT * FROM `inv_return` LEFT JOIN `mes_qto` ON `mes_qto`.`po_id` = `inv_return`.`ret_invnum` 
                    WHERE `mes_qto`.`po_sup_id` = '$cust' and `inv_return`.`ret_to_inv` = '0' ORDER BY `inv_return`.`ret_id` ASC");

                   /*     if(isset($rtn[0]->ret_amount)){
                            $ret_amnt = $rtn[0]->ret_amount;
                            $ret_id = $rtn[0]->ret_id;
                           $updt = app('db')->update("UPDATE `mes_qto` SET `po_tot_freqty`='$tot_free',`return_amnt`='$ret_amnt'
                           ,`po_auth`='$aprl' WHERE `po_id` = '$insert_id'");
                           
                           $updt1 = app('db')->update("UPDATE `inv_return` SET `ret_to_inv`='1' WHERE `ret_id` = '$ret_id'");
                        }else{
                            $updt = app('db')->update("UPDATE `mes_qto` SET `po_tot_freqty`='$tot_free'
                           ,`po_auth`='$aprl' WHERE `po_id` = '$insert_id'");
                        } */
            
            }else{
                $dataa[0] = "Incorrect Data"; 
            }
            
            
            if($aprl!=1){
                $item_dt = new Product(); 
              // $sm = $item_dt->dosms($insert_id,"Requesting Authorization for");
            }
            
            $dataa[1] = $authd;
            
            $data = response()->json($dataa);
            return $data;

    }
    
    function rem_inv_item(Request $request){
        $this->validate($request, [
                'temp_line_id'  => 'required',
                'ref_id'  => 'required'
                
        ]);
        $temp_pro_id = $request->input('temp_line_id');
        $ref = $request->input('ref_id');
        $resultitem = app('db')->select("SELECT * FROM `temp_qto_items` WHERE `temp_qto_items`.`po_itm_id` = '$temp_pro_id'");
        $count = count($resultitem);
        if($count>0){
            $allqty = $resultitem[0]->po_itm_qty+$resultitem[0]->free_item;
        $invoice = new Invoice();
                $depo = $invoice->get_sales_depo($ref);
        
                $updt = app('db')->delete("DELETE FROM `temp_qto_items` WHERE `po_itm_id` = '$temp_pro_id'");
                if($updt){
                        $data = "Removed";
                        $cal = new Invoice();
                        $cal_stock = $cal->cal_stock($depo,"temprem","0",$resultitem[0]->po_itm_item_id,$allqty,"plus","0");
                        
                }else{
                        $data = "error";
                }
        }else{
            $data = "Incorrect Id";
        }
        
        
        $dataa = response()->json($temp_pro_id);
            return $dataa;
    }
    
    function request_sms(Request $request){
        $this->validate($request, [
            'invoice_id' => 'required'
        ]);
        
        $inv = $request->input('invoice_id');
        $item_dt = new Product(); 
       // $sm = $item_dt->dosms($inv,"Requesting Authorization for");
       
        $data = response()->json("Requested for Authorization");
         return $data;
        
    }
    
    function invoice_search(Request $request){
        
        $this->validate($request, [
            'detail' => 'required'
        ]);
        $detail = $request->input('detail');
        
        if(($detail!="")){
            
            $results = app('db')->select("SELECT `mes_qto`.*, `mes_customer`.*, `mes_currancy`.*, `mes_country`.* FROM `mes_qto` LEFT JOIN `mes_customer` 
                ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` LEFT JOIN `mes_currancy` ON `mes_currancy`.`curr_id` = `mes_qto`.`po_currancy` 
                LEFT JOIN `mes_country` ON `mes_country`.`cnty_id` = `mes_customer`.`cust_country` 
                where `mes_qto`.`po_id` LIKE '%$detail%' or `mes_customer`.`cust_company` LIKE '%$detail%' ORDER BY `mes_qto`.`po_id` DESC");
                for($i=0; $i<count($results); $i++){
                    $link = "https://demo.webip.lk/nance/inv_view_pdf?id=".$results[$i]->uniq_id;
                    
                    if($results[$i]->po_payment!=1){$sts = "Not Paid";}else{$sts = "Paid";}
                    if($results[$i]->po_auth!=1){$auth = "Pending Authorize";}else{$auth = "Authorized";}
                    if($results[$i]->po_status!=1){$status = "cancelled";}else{$status = "active";}
                    $inv[] = array('inv_id'=>($results[$i]->qto_code.$results[$i]->po_id),'uniq'=>$results[$i]->uniq_id,'inv_tot'=>$results[$i]->po_tot_price,
                    'inv_dis'=>$results[$i]->po_discount,'final_total'=>$results[$i]->po_final_tot,'inv_qty'=>$results[$i]->po_tot_qty,
                    'free_qty'=>$results[$i]->po_tot_freqty,'item_count'=>$results[$i]->po_tot_items,'customer'=>$results[$i]->cust_company,'cutomer_adrs'=>$results[$i]->cust_addres,
                    'cutomer_adrs'=>$results[$i]->cust_addres,'pdflink'=>$link,'created_on'=>$results[$i]->po_cdate,'payment_status'=>$sts,'Authorization'=>$auth,'inv_status'=>$status);
                }
                if(empty($inv)){
                    $inv = "No Invoices";
                }
            
        }else{
            $inv = "Please enter details to search";
        }
        
        $data = response()->json($inv);
            return $data;
        
    }
    
    
}
