<?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 all_stock_cal(Request $request){
       
       $this->validate($request, [
            'depo' => 'required',
            'type' => 'required',
            'inv_id' => 'required',
            'item_id' => 'required',
            'qty' => 'required',
            'add' => 'required',
            'batch' => 'required',
            'usr' => 'required',
        ]);
            
            $depo =$request->input('depo');
            $type = $request->input('type');
            $inv_id =$request->input('inv_id'); 
            $item_id = $request->input('item_id');
            $qty =$request->input('qty');
            $add =$request->input('add');
            $batch = $request->input('batch');
            $usr = $request->input('usr');
    
    $cal = new Invoice();
       $cal_stock = $cal->cal_batch($depo,$type,$inv_id,$item_id,$qty,$add,$batch,$usr);


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

    }

    function get_data(Request $request){
        
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $user_id = $user_data[0]->user_id;
        
        $thridate = date('Y-m-d', strtotime('-3 months'));
        
        $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' AND (`mes_qto`.`po_cdate` > '$thridate' OR (`mes_qto`.`po_payment`<1 AND `mes_qto`.`po_final_tot`>0))
         ORDER BY `mes_qto`.`po_id` DESC");
        
        for($i=0; $i<count($results); $i++){
            $link = "https://manchieedecoco.com/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;
            $rounded_number = sprintf("%.2f", $bal);
            
            $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'=>$rounded_number,'Authorization'=>$auth,'inv_status'=>$status,'auth_sts'=>$results[$i]->po_auth,
            'return_value'=>$results[$i]->return_amnt);
        }
        if(empty($inv)){
            $inv = "No Invoices";
        }
        
        $data = response()->json($inv);
            return $data;
    }

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

       $id = $request->input('uniq');
       
        $results = app('db')->select("SELECT `mes_qto`.`po_id`,`mes_qto`.`qto_code`,`mes_qto`.`po_tot_qty`,`mes_qto`.`po_final_tot`,`mes_qto`.`po_tot_price`,`mes_qto`.`return_amnt`,
        `mes_qto`.`po_discount`,`mes_qto`.`po_vat`,
        `mes_qto`.`po_cdate`,`mes_customer`.`cust_company` , `mes_customer`.`cust_addres`,`mes_customer`.`cust_id`,
        `mes_user`.`user_fname`,`mes_user`.`user_lname`,`mes_user`.`user_mobnum` FROM `mes_qto` LEFT JOIN `mes_customer`
        ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` LEFT JOIN `mes_user` ON `mes_user`.`user_id` = `mes_qto`.`po_ref_id`
        LEFT JOIN `mes_country` ON `mes_country`.`cnty_id` = `mes_customer`.`cust_country` where `mes_qto`.`uniq_id` ='$id'  LIMIT 1"); 
        
        $dt = new User;
                    //$out = $dt->outstand($results[0]->cust_id);
                    $out = $dt->outstand_det($results[0]->cust_id);
        
        $inv_id = $results[0]->po_id;
        
        $resultitem = app('db')->select("SELECT `qto_items`.`po_itm_id` as row_id,`qto_items`.`po_itm_item_id` as item_id,
        `qto_items`.`po_itm_batch` as batch_id,`qto_items`.`po_itm_qty` as qty,`qto_items`.`free_item` as free, 
        `item`.`itm_name` as product,`batch`.`batch` as batch,`qto_items`.`po_itm_unitprice` as price FROM `qto_items` 
        LEFT JOIN `mes_item` ON `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 `qto_items`.`po_itm_currancy` = `mes_currancy`.`curr_id` 
        LEFT JOIN `mes_unit` ON `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 `batch` ON `batch`.`batch_id` = `qto_items`.`po_itm_batch`
        LEFT JOIN `mes_category` ON `mes_category`.`cat_id` = `mes_item`.`item_cat` WHERE `qto_items`.`po_itm_po_id` = '$inv_id' ORDER BY `qto_items`.`po_itm_id` DESC");
        
        if(count($results)<1){
            $data = response()->json("Incorrect ID");
        }else{
            $result[0] = $results;
            $result[1] = $resultitem;
            $result[2] = $out;
            $data = response()->json($result);
        }
        
        
            return $data;
    }

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

        $data = response()->json($last_id);
            return $data;
    }
    
    function get_gen_detail(){
       
      $resultitem = app('db')->select("SELECT * FROM `general`");

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

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

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

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

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

        $results = app('db')->select("SELECT * from `mes_customer` JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
        where `cust_status` ='1' AND `cust_salseperson` ='$id' AND `cust_city` !='0' AND `cust_auth`='1'");
      // $results = app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.* from `mes_customer` JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
     // JOIN `mes_qto` ON `mes_qto`.`po_sup_id`=`mes_customer`.`cust_id` where `cust_status` ='1' AND `cust_city` !='0' 
    //  AND `cust_auth`='1' AND (`mes_qto`.`po_ref_id`='$id' OR `cust_salseperson` ='$id') GROUP BY `mes_customer`.`cust_id`");

       // $results .=app('db')->select("SELECT `mes_customer`.* from `mes_qto` JOIN `mes_customer` ON `mes_customer`.`cust_id`=`mes_qto`.`po_sup_id` WHERE `mes_qto`.`po_ref_id`='$id'");

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

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

       $id = $request->input('refid');
       
       // $results = app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.* from `mes_customer` JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
     // JOIN `mes_qto` ON `mes_qto`.`po_sup_id`=`mes_customer`.`cust_id` where `cust_status` ='1' AND `cust_city` !='0' 
     // AND `cust_auth`='1' AND (`mes_qto`.`po_ref_id`='$id' OR `cust_salseperson` ='$id') GROUP BY `mes_customer`.`cust_id`");
     
     $customer = [];

      $results = app('db')->select("SELECT `cust_id`, `cust_uniqid`, `cust_idtext`,`cust_company`, `cust_addres`, 
        `cust_distc`, `cust_prov`, `cust_city`,`cust_discount`, 
        `cust_creditper`, `credit_limit`, `cust_salseperson`, `cust_status`, 
        `cust_auth`,`cust_credit`, `cust_pay_excess`, `cust_return_excess`, `cust_route`
        from `mes_customer` where `cust_status` ='1' AND `cust_salseperson` ='$id' ORDER BY `cust_company` ASC");
        
        for($i=0; $i<count($results); $i++){
            $outs = new Invoice();
                $outt = $outs->outstand($results[$i]->cust_id);
            $customer[] = array(
                'cust_id'=>$results[$i]->cust_id, 
                'cust_uniqid'=>$results[$i]->cust_uniqid, 
                'cust_idtext'=>$results[$i]->cust_idtext,
                'cust_company'=>$results[$i]->cust_company, 
                'cust_addres'=>$results[$i]->cust_addres, 
                'cust_distc'=>$results[$i]->cust_distc, 
                'cust_prov'=>$results[$i]->cust_prov, 
                'cust_city'=>$results[$i]->cust_city,
                'cust_discount'=>$results[$i]->cust_discount, 
                'cust_creditper'=>$results[$i]->cust_creditper, 
                'credit_limit'=>$results[$i]->credit_limit, 
                'cust_salseperson'=>$results[$i]->cust_salseperson, 
                'cust_status'=>$results[$i]->cust_status, 
                'cust_auth'=>$results[$i]->cust_auth,
                'cust_credit'=>$results[$i]->cust_credit, 
                'cust_pay_excess'=>$results[$i]->cust_pay_excess, 
                'cust_return_excess'=>$results[$i]->cust_return_excess, 
                'cust_outstand'=>$outt, 
                'cust_route'=>$results[$i]->cust_route);
            
        }
        
         $result = app('db')->select("SELECT `mes_customer`.`cust_id`,`mes_customer`.* from `mes_customer` 
       JOIN `customer_route` ON `customer_route`.`cus_id`=`mes_customer`.`cust_id` 
       JOIN `mes_qto` ON `mes_qto`.`po_sup_id`=`mes_customer`.`cust_id` where `cust_status` ='1' 
       AND `cust_city` !='0' AND `cust_salseperson`!='$id' AND `mes_qto`.`po_ref_id`='$id' GROUP BY `mes_customer`.`cust_id` ");
       
       for($i=0; $i<count($result); $i++){
           
           if (in_array($result[$i]->cust_id, $customer)){
               
           }else{
               $outs = new Invoice();
                $outt = $outs->outstand($result[$i]->cust_id);
               
            $customer[] = array(
                'cust_id'=>$result[$i]->cust_id, 
                'cust_uniqid'=>$result[$i]->cust_uniqid, 
                'cust_idtext1'=>$result[$i]->cust_idtext,
                'cust_company'=>$result[$i]->cust_company, 
                'cust_addres'=>$result[$i]->cust_addres, 
                'cust_distc'=>$result[$i]->cust_distc, 
                'cust_prov'=>$result[$i]->cust_prov, 
                'cust_city'=>$result[$i]->cust_city,
                'cust_discount'=>$result[$i]->cust_discount, 
                'cust_creditper'=>$result[$i]->cust_creditper, 
                'credit_limit'=>$result[$i]->credit_limit, 
                'cust_salseperson'=>$result[$i]->cust_salseperson, 
                'cust_status'=>$result[$i]->cust_status, 
                'cust_auth'=>$result[$i]->cust_auth,
                'cust_credit'=>$result[$i]->cust_credit, 
                'cust_pay_excess'=>$result[$i]->cust_pay_excess, 
                'cust_return_excess'=>$result[$i]->cust_return_excess, 
                'cust_outstand'=>$outt, 
                'cust_route'=>$result[$i]->cust_route);
           }
            
        }
        
        
        $data = response()->json($customer);
            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;
        
        $us_temp = app('db')->select("SELECT COUNT(`po_itm_id`) as tempcount FROM `temp_qto_items` WHERE `po_user`='$id'");
        $tempitem = $us_temp[0]->tempcount;

            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 ORDER BY `mes_item`.`item_brand`,`mes_item`.`item_id` ASC");
                    
                    foreach ($resultitem as $row) {

                        $detail = app('db')->select("SELECT `product`, MAX(`buying_price`) as buying, MAX(`selling_price`) as selling, MAX(`retail_price`) as retail FROM `batch_depo` WHERE `avl_qty` >0 AND `product` = '$row->dpstock_itemid'");
                        if($detail[0]->selling<1){$ssel = "0.00";}else{ $ssel = $detail[0]->selling;}
                        if($detail[0]->retail<1){$rrtl = "0.00";}else{$rrtl = $detail[0]->retail;}
                        if($row->item_freeitm<1){$itmf = "0";}else{$itmf = $row->item_freeitm;}
                        if($row->item_freqty<1){$frq = "0";}else{$frq = $row->item_freqty;}
                        
                        if($rrtl=="0.00"){
                            $detail_new = app('db')->select("SELECT `product`, `buying_price`, `selling_price`,`retail_price` FROM `batch_depo` WHERE `product` = '$row->dpstock_itemid' ORDER BY `exp_date` DESC");
                            if(count($detail_new)>0){ $rrtl = $detail_new[0]->retail_price;}
                             
                         }
                         
                         if($ssel=="0.00"){
                            $detail_new = app('db')->select("SELECT `product`, `buying_price`, `selling_price`,`retail_price` FROM `batch_depo` WHERE `product` = '$row->dpstock_itemid' ORDER BY `exp_date` DESC");
                            if(count($detail_new)>0){$ssel = $detail_new[0]->selling_price; }
                         }
                        
                        $resultitemm[] = array('item_id'=>($row->dpstock_itemid),'dpstock_dpoid'=>($row->dpstock_dpoid),'dpstock_qty'=>($row->dpstock_qty),
                            'itm_name'=>($row->itm_name),'item_selling_price'=>($ssel),'item_retail_price'=>($rrtl),'item_freeitm'=>($itmf),'item_freqty'=>($frq),'temp'=>($tempitem));
                    }
                
           
            }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 ORDER BY `mes_item`.`item_brand`,`mes_item`.`item_id` ASC");

                foreach ($resultitem as $row) {

                    $detail = app('db')->select("SELECT `product`, MAX(`buying_price`) as buying, MAX(`selling_price`) as selling, MAX(`retail_price`) as retail FROM `batch` WHERE `avl_qty` >0 AND `product` = '$row->dpstock_itemid'");
                        if($detail[0]->selling<1){$ssel = "0.00";}else{ $ssel = $detail[0]->selling;}
                        if($detail[0]->retail<1){$rrtl = "0.00";}else{$rrtl = $detail[0]->retail;}
                         if($row->item_freeitm<1){$itmf = "0";}else{$itmf = $row->item_freeitm;}
                        if($row->item_freqty<1){$frq = "0";}else{$frq = $row->item_freqty;}
                        
                        if($rrtl=="0.00"){
                            $detail_new = app('db')->select("SELECT `product`, `buying_price`, `selling_price`,`retail_price` FROM `batch` WHERE `product` = '$row->dpstock_itemid' ORDER BY `exp_date` DESC");
                            if(count($detail_new)>0){ $rrtl = $detail_new[0]->retail_price;}
                             
                         }
                         
                         if($ssel=="0.00"){
                            $detail_new = app('db')->select("SELECT `product`, `buying_price`, `selling_price`,`retail_price` FROM `batch` WHERE `product` = '$row->dpstock_itemid' ORDER BY `exp_date` DESC");
                            if(count($detail_new)>0){$ssel = $detail_new[0]->selling_price; }
                         }
                        
                    $resultitemm[] = array('item_id'=>($row->dpstock_itemid),'dpstock_dpoid'=>($row->dpstock_dpoid),'dpstock_qty'=>($row->dpstock_qty),
                        'itm_name'=>($row->itm_name),'item_selling_price'=>($ssel),'item_retail_price'=>($rrtl),'item_freeitm'=>($itmf),'item_freqty'=>($frq),'temp'=>($tempitem));
                }
            }


        
    
        $data = response()->json($resultitemm);
            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, [
            'batch_id' => 'required',
            'batch_price' => 'required'
        ]);

        $item = $request->input('batch_id');
        $batch_price = $request->input('batch_price');
        
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $u_name = $user_data[0]->user_name;
        $u_id = $user_data[0]->user_id;
                
            $stk = new Invoice();
                $detail = $stk->chk_itm_price($item,$batch_price,$u_id);    

            $data = response()->json($detail);
            return $data;
    }
    
    function check_allitem_price(Request $request){
        $this->validate($request, [
            'batch_id' => 'required',
            'batch_price' => 'required'
        ]);

    $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $user_id = $user_data[0]->user_id;

        $batch = $request->input('batch_id');
       $str_arr = preg_split ("/\,/", $batch); 
            $price = $request->input('batch_price');
            $prc_arr = preg_split ("/\,/", $price);
        
        $detail = "approved"; 
        for($i=0; $i<count($str_arr); $i++){
            $stk = new Invoice();
                $detail = $stk->chk_itm_price($str_arr[$i],$prc_arr[$i],$user_id); 
                if($detail=="Not Approved"){
                    $detail = "Not Approved";
                    break;
                }
            
        }
                

            $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',
            'free' => 'required',
            'unit_price' => 'required'
        ]);
       
        $item = $request->input('itemid');
        $refid = $request->input('refid');
        $dispc = $request->input('dispc');
       
        $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;
            $usr = $seluser[0]->user_id;
          //  Session::set('uname',$usr);
          //  $_SESSION["uname"] = $usr;
          
          $custom_price = $request->input('unit_price');
          
          

         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";
                          
                        }else */
                        
                        if($request->input('free') > $max_free){
                                    $aprvl = "1"; $det = "Need approval. Free quantity Exceeded";
                       }
                       else{
                            $data[0] = ""; $aprvl = "0"; $det = "";
                        }
    
//no need below                              
                                    $aprvl = "0";    
                        
        $qty = $request->input('qty');
        //$price = "100";
        $freeitm = $request->input('free');
        $custom_price = $request->input('unit_price');
    
    $cal = new Invoice();
                if($depo!="0"){
                    $select_batch = app('db')->select("SELECT * FROM `batch_depo` WHERE `product`='$item' AND `avl_qty`>0 AND `depo`='$depo' ORDER BY `exp_date` ASC;");
                }else{
                    $select_batch = app('db')->select("SELECT * FROM `batch` WHERE `product`='$item' AND `avl_qty`>0 ORDER BY `exp_date` ASC;");
                }
                
                $item_qty = $qty+$freeitm;
                  $inv_qty = $qty+$freeitm;
                  
                    foreach ($select_batch as $row) {
                        $price = $row->selling_price;
                        $batch_id = $row->batch_id;
                        
                        $item_qty = $item_qty - $row->avl_qty;
                        
                        
                                if(($item_qty>0)){
                                    $b_qty = $row->avl_qty;
                                    if($custom_price>0){
                                        $price = $custom_price;
                                        if($custom_price < $row->selling_price){$aprvl = "1"; $det = "Need approval. Price Discount Exceeded";}
                                    }else{
                                        $price = $row->selling_price; 
                                    }
                                    
    //no need below                              
                                    $aprvl = "0"; $price = $custom_price;
                                    
                                    $resultinsert = app('db')->insert("INSERT INTO `temp_qto_items` (`temp_id`, `po_itm_item_id`, `po_itm_qty`, `po_itm_dis`,`po_itm_unitprice`, `po_itm_unit`,`po_itm_batch`, `po_aprvl`, `free_item`,
                                    `depo_id`, `po_user`) VALUES ('0', '$item', '$b_qty', '$dispc','$price', '002','$batch_id','$aprvl', '0', '$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;
                                
                                    $cal_stock = $cal->cal_batch($depo,"temp",$ins_id,$item,$b_qty,"min",$row->batch_id,$usr);
                                    
                                    if($resultinsert){
                                            $data[0] = "Added to Invoice";
                                        }else{
                                            $data[0] = "Not added";
                                        }
                                    
                                }else if(($item_qty<0)){
                                    
                                    $b_qty = $row->avl_qty + $item_qty;
                                    if($custom_price>0){
                                        $price = $custom_price;
                                        if($custom_price < $row->selling_price){$aprvl = "1"; $det = "Need approval. Price Discount Exceeded";}
                                    }else{
                                        $price = $row->selling_price;
                                    }
                                    $cal_free = ($b_qty-$freeitm);
                                    
                                    if($cal_free>0){
                                        $b_qty = $b_qty-$freeitm;
                                    }else{
                                        $freeitm = $b_qty;
                                        $b_qty = 0;  
                                        
                                                //update previouse line
                                                $gt_ins_idd =   app('db')->select("SELECT `po_itm_id`,`po_itm_qty` from `temp_qto_items` where `po_user` ='$usr' ORDER BY `po_itm_id` DESC LIMIT 1");
                                                $ins_idd = $gt_ins_idd[0]->po_itm_id;
                                                  $pre_bal = $gt_ins_idd[0]->po_itm_qty + $cal_free;  $thisfree = abs($cal_free);
                                                $updt = app('db')->update("UPDATE `temp_qto_items` SET `po_itm_qty`='$pre_bal',`free_item`='$thisfree' WHERE `po_user` = '$usr' and `po_itm_id`= '$ins_idd'"); 
                                       
                                    }
      //no need below                              
                                    $aprvl = "0"; $price = $custom_price;
                                    $resultinsert = app('db')->insert("INSERT INTO `temp_qto_items` (`temp_id`, `po_itm_item_id`, `po_itm_qty`,`po_itm_dis`, `po_itm_unitprice`, `po_itm_unit`,`po_itm_batch`, `po_aprvl`, `free_item`,
                                    `depo_id`, `po_user`) VALUES ('0', '$item', '$b_qty', '$dispc', '$price', '002','$batch_id','$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;
                                
                                    $cal_stock = $cal->cal_batch($depo,"temp",$ins_id,$item,($b_qty+$freeitm),"min",$row->batch_id,$usr);
                                    if($resultinsert){
                                            $data[0] = "Added to Invoice";
                                        }else{
                                            $data[0] = "Not added";
                                        }
                                    
                                    break;
                                }else if(($item_qty==0)){
                                    if($custom_price>0){
                                        $price = $custom_price;
                                        if($custom_price < $row->selling_price){$aprvl = "1"; $det = "Need approval. Price Discount Exceeded";}
                                    }else{
                                        $price = $row->selling_price;
                                    }
                                    
                                    $aprvl = "0"; $price = $custom_price;
                                    //update previouse line
                                             //   $gt_ins_idd =   app('db')->select("SELECT `po_itm_id`,`po_itm_qty` from `temp_qto_items` where `po_user` ='$usr' ORDER BY `po_itm_id` DESC LIMIT 1");
                                             //   $ins_idd = $gt_ins_idd[0]->po_itm_id;
                                             //     $pre_bal = $gt_ins_idd[0]->po_itm_qty - $freeitm;
                                            //       $pre_bal = $gt_ins_idd[0]->po_itm_qty - $request->input('free');
                                             //   $updt = app('db')->update("UPDATE `temp_qto_items` SET `po_itm_qty`='$pre_bal',`free_item`='$freeitm' WHERE `po_user` = '$usr' and `po_itm_id`= '$ins_idd'"); 
                                    $lst_qty = $row->avl_qty - $freeitm;
                                    
                                        $resultinsert = app('db')->insert("INSERT INTO `temp_qto_items` (`temp_id`, `po_itm_item_id`, `po_itm_qty`,`po_itm_dis`, `po_itm_unitprice`, `po_itm_unit`,`po_itm_batch`, `po_aprvl`, `free_item`,
                                    `depo_id`, `po_user`) VALUES ('0', '$item', '$lst_qty', '$dispc','$price', '002','$batch_id','$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;
                                
                                    $cal_stock = $cal->cal_batch($depo,"temp",$ins_id,$item,$row->avl_qty,"min",$row->batch_id,$usr);
                                    if($resultinsert){
                                            $data[0] = "Added to Invoice";
                                        }else{
                                            $data[0] = "Not added";
                                        }
                                    
                                    break;
                                    
                                }

                    }

               
         
        $data[1] =$det;
        
        $data['resultitem'] = app('db')->select("SELECT `temp_qto_items`.`po_itm_id` as row_id,`temp_qto_items`.`po_itm_item_id` as item_id,
        `temp_qto_items`.`po_itm_batch` as batch_id,`temp_qto_items`.`po_itm_qty` as qty,`temp_qto_items`.`free_item` as free, 
        `item`.`itm_name` as product,`batch`.`batch` as batch,`temp_qto_items`.`po_itm_unitprice` as price 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`
        LEFT JOIN `batch` ON `batch`.`batch_id` = `temp_qto_items`.`po_itm_batch`
        WHERE `temp_qto_items`.`po_user` = '$usr' and `temp_qto_items`.`po_itm_item_id` = '$item' ORDER BY `temp_qto_items`.`temp_id` ASC");

    
    
         }else{
            $data[0] = "No Stock";
            $det = $data['resultitem'] = "";
         }
            $dataa = response()->json($data);
            return $dataa;
        

    }
    
    function get_temp_inv_data(Request $request){
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $uname = $user_data[0]->user_id;
        $resultitem = app('db')->select("SELECT `temp_qto_items`.`po_itm_id` as row_id,`temp_qto_items`.`po_itm_item_id` as item_id,
        `temp_qto_items`.`po_itm_batch` as batch_id,`temp_qto_items`.`po_itm_qty` as qty,`temp_qto_items`.`free_item` as free, 
        `item`.`itm_name` as product,`batch`.`batch` as batch,`temp_qto_items`.`po_itm_unitprice` as price 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 `batch` ON `batch`.`batch_id` = `temp_qto_items`.`po_itm_batch`
        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'
        ]);

        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $u_name = $user_data[0]->user_name;
        $u_id = $user_data[0]->user_id;
             $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');
             $vat = $request->input('vat');
             if($request->input('remark')){
                  $remark = $request->input('remark');
             }else{
                  $remark = "";
             }
            
         
            $temp_item =   app('db')->select("SELECT `po_itm_id` from `temp_qto_items` where `po_user` ='$u_id'");     
            $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` ='$u_id'");     
           $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(40 < $dis){
                                $discnt = $dis;
                                    $auth = 0;  $authd = "Need Approval for Customer Discount";
                            }else 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 = "";}
                            }else{
                                $discnt = $get_dis[0]->cust_discount;
                                $auth = 1;$authd = "";
                            } 

       
        $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;
        
       $cur_dt =  date('d-m-y h:i:s');
    
    // no need
    $auth = 1;
        
        $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`,`po_time`,`po_vat`) VALUES 
        ('$uniq_id','$cust','$out', '$refid', '$totprice', '$ndis', '$fintot', '$cal_tot', '$count', 
        '$other', '0001', '0.00','$finl' ,'$u_id', '$remark','$date', '$auth','$cal_totfree','$udepo','$cur_dt','$vat')");    

            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`='$u_id'");
            $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` = '$u_id'"); 
                
                $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_batch`, `po_itm_po_id`,`service_des`, `po_itm_qty`, `free_item`,
                       `po_itm_unit`, `po_itm_dis`,`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_batch','$row->po_itm_po_id','$row->service_des','$row->po_itm_qty','$row->free_item','$row->po_itm_unit','$row->po_itm_dis','$row->po_itm_unitprice',
                       '$row->po_itm_currancy','$row->po_itm_description','$row->po_aprvl','$u_id')");    
                            
                            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'");
                                
                            }
                            $cal = new Invoice();
                            
                        //$cal_stock = $cal->cal_batch_only($udepo,"temprem","0",$row->po_itm_item_id,$row->po_itm_qty,"plus",$row->po_itm_batch,$u_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';}
                    
                    if($ndis>0){
                        $disvl = ($cal_tot_val/100)*$ndis;
                        $cal_tot_val = $cal_tot_val - $disvl;
                    }
                        $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";}
                   
    //no need
    $aprl = 1;
                    
                    $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){
        $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $user_id = $user_data[0]->user_id;
        
        $this->validate($request, [
                'temp_line_id'  => 'required',
                'ref_id'  => 'required'
                
        ]);
        $temp_pro_id = $request->input('temp_line_id');
        $ref = $request->input('ref_id');
        $invoice = new Invoice();
                        $depo = $invoice->get_sales_depo($ref);
        
        $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){
            $gt_batch = $resultitem[0]->po_itm_item_id;
                $all_data = app('db')->select("SELECT * FROM `temp_qto_items` WHERE `po_itm_item_id` = '$gt_batch' and `po_user`=$user_id");
              $allqty = 0;  
                foreach ($all_data as $row) {
                    $allqty = $row->po_itm_qty+ $row->free_item;
                    $line_num = $row->po_itm_id;
                        
                        $updt = app('db')->delete("DELETE FROM `temp_qto_items` WHERE `po_itm_item_id` = '$gt_batch' and `po_user`=$user_id and `po_itm_id`='$line_num'");
                        if($updt){
                                $data = "Removed";
                                $cal = new Invoice();
                                $cal_stock = $cal->cal_batch($row->depo_id,"temprem","0",$gt_batch,$allqty,"plus",$row->po_itm_batch,$user_id);
                                
                        }else{
                                $data = "error";
                        }
                }
              
        
        }else{
            $data = "Incorrect Id";
        }
        
        $dataa = response()->json($data);
            return $dataa;
    }
    
    function rem_allinv_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');
        $invoice = new Invoice();
                        $depo = $invoice->get_sales_depo($ref);
        
        $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){
            $gt_batch = $resultitem[0]->po_itm_item_id;
                $all_data = app('db')->select("SELECT * FROM `temp_qto_items` WHERE `po_itm_item_id` = '$gt_batch' and `po_user`=$ref");
              $allqty = 0;  
                foreach ($all_data as $row) {
                    $allqty = $row->po_itm_qty+ $row->free_item;
                    $line_num = $row->po_itm_id;
                        
                        $updt = app('db')->delete("DELETE FROM `temp_qto_items` WHERE `po_itm_id`='$line_num'");
                        if($updt){
                                $data = "Removed";
                                $cal = new Invoice();
                                $cal_stock = $cal->cal_batch($row->depo_id,"temprem","0",$gt_batch,$allqty,"plus",$row->po_itm_batch,0);
                                
                        }else{
                                $temp_pro_id = $data = "error";
                        }
                }
              
        
        }else{
            $data = "Incorrect Id";
             $temp_pro_id = $data = "error";
        }
        
        $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://manchieedecoco.com/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;
        
    }
    
    function posdata(Request $request){
        $this->validate($request, [
            'invid' => 'required'
        ]);
        
        $unq_id = $request->input('invid');
        
        
        $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`.`uniq_id`='$unq_id'");
        
   
        
        $data = response()->json($results);
            return $data;
        
    }
    
    
    
    
}
