<?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\Payment;

class ReturnController extends Controller
{
   
   
   function get_invoice(Request $request){
       $this->validate($request, [
            'cust_id' => 'required'
            
        ]);
       $cust = $request->input('cust_id');
        $inv = app('db')->select("SELECT * FROM `mes_qto` WHERE `po_status`=1 AND `po_sup_id`='$cust' AND `po_auth`='1'");
        /*
        $inv = app('db')->select("SELECT * FROM `mes_qto` 
JOIN `inv_return` ON `inv_return`.`ret_invnum` = `mes_qto`.`po_id` 
WHERE `po_status`=1 AND `po_sup_id`='$cust' AND `po_auth`='1'
AND `inv_return`.`ret_proceed`!=0");
        */
        //$invdt="No invoices";
        
        for($i=0; $i<count($inv); $i++){
            $qtoid = $inv[$i]->po_id;
           $chkk = app('db')->select("SELECT * FROM `inv_return` WHERE `ret_invnum`='$qtoid' AND `ret_stetus`=1 AND `ret_proceed`='0'");
           if(count($chkk)<1){
               $paym = app('db')->select("SELECT * FROM `mes_payment` WHERE `pay_stetus`=1 AND `pay_invid`='$qtoid' AND `pay_authrize`='0'");
                if(count($paym)<1){
                    $invdt[] = array($inv[$i]->po_code,$inv[$i]->po_id);
                }else{
                    
                }
               
           }
               
        }
        
        if(count($inv)<1){
          $invdt="No invoices";
        }
        if(empty($invdt)){
          $invdt="No invoices";
        }
        
        $data['invoice'] = $invdt;
        
        $reason = app('db')->select("SELECT `ret_reason_id`,`ret_reason` FROM `mes_ret_reason` WHERE `ret_reason_status` =1");
        
        $data['ret_reason'] = $reason;
        
        $dataa = response()->json($data);
            return $dataa;
   }
   
   function all_return(Request $request){
       
       $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $user_id = $user_data[0]->user_id;
       
       $inv = app('db')->select("SELECT * FROM `inv_return` LEFT JOIN `mes_qto` ON `mes_qto`.`po_id` = `inv_return`.`ret_invnum` 
       LEFT JOIN `mes_ret_reason` ON `mes_ret_reason`.`ret_reason_id` = `inv_return`.`ret_reason`  where `mes_qto`.`po_ref_id`='$user_id' ORDER BY `ret_id` DESC");
        
        for($i=0; $i<count($inv); $i++){
            $poid = $inv[$i]->po_id;
            
            $qt = app('db')->select("SELECT * FROM `mes_qto` LEFT JOIN `mes_customer` ON `mes_customer`.`cust_id` = `mes_qto`.`po_sup_id` WHERE `po_id` = '$poid'");
            $invid = $inv[$i]->ret_code.$inv[$i]->ret_id;
            
            if($inv[$i]->ret_proceed==1){
                        if($inv[$i]->ret_stetus==1){
                        $sts = "Authorized";
                        }else{
                        $sts = "Invoice Cancelled";}
                        
                    }else{
                        if($inv[$i]->ret_stetus==1){
                        $sts = "Pending Authorize";
                        }else{
                        $sts = "Invoice Cancelled";}
                        
                    }
                   $link = "https://demo.webip.lk/nance/pdf_invrtn/".$inv[$i]->ret_id;
            $invdt[] = array('return_id'=>$invid,'invoice_'=>$inv[$i]->ret_invnum,'Customer'=>$qt[0]->cust_company,
            'reason'=>$inv[$i]->ret_reason,'retirn_qty'=>$inv[$i]->ret_totqty,'returnQty'=>$inv[$i]->ret_cdate,$sts,'return_amnt'=>$inv[$i]->ret_amount,'link'=>$link); 
        }
       
       if(empty($invdt)){
           $invdt = "No return Notes";
       }
       
        $dataa = response()->json($invdt);
            return $dataa;
       
   }
   
   function get_inv_product(Request $request){
       
       $this->validate($request, [
            'inv_id' => 'required'
            
        ]);
       
       $inv_id = $request->input('inv_id');
      // $grndata = app('db')->select("SELECT * FROM `mes_grn` WHERE `grn_stetus` =1 AND `grn_id` = '$inv_id'");
       $dataa = app('db')->select("SELECT * FROM `qto_items` WHERE `po_aprvl` ='0' AND `po_itm_po_id` = '$inv_id'");
       $det= [];
       for($i=0; $i<count($dataa); $i++){ 
           $item_id = $dataa[$i]->po_itm_item_id;
           
            $item_dt = new Invoice(); 
            $data = $item_dt->get_sin_item_model($item_id);
            
            $rec = app('db')->select("SELECT sum(return_items.ret_itm_qty) as rec, sum(return_items.free_item) as free FROM `return_items` 
            WHERE `ret_inv_id` = '$inv_id' AND `ret_aprvl` = 1 AND `ret_itm_item_id` = '$item_id'");
                    
            
            if($rec[0]->rec){$rc=$rec[0]->rec; $rcfr=$rec[0]->free;
                
            }else{
                $rec = app('db')->select("SELECT sum(`mes_inventry`.`invt_qty`) as rec FROM `inv_return`
                        LEFT JOIN `mes_inventry` ON `mes_inventry`.`invt_type_id` = `inv_return`.`ret_id` 
                WHERE `inv_return`.`ret_invnum` = '$inv_id' AND `mes_inventry`.`invt_type` = 'INVRTN' AND `mes_inventry`.`invt_itemid` = '$item_id' AND `invt_proc`=1");
           
                if($rec[0]->rec){$rc=$rec[0]->rec; $rcfr=0;}else{
                    $rc=0; $rcfr=0;
                }
               $rcfr=0;
                
            }
                        $rem = $dataa[$i]->po_itm_qty - $rc;
                        $remfree = $dataa[$i]->free_item - $rcfr;
                        
            $det[] = array('item_id'=>$dataa[$i]->po_itm_item_id,'item'=>$data[0]->cat_shortcode."-".$data[0]->item_id,
            'item_des'=>$data[0]->itm_name,'invoiced_price'=>$dataa[$i]->po_itm_unitprice,'invoiced_qty'=>$dataa[$i]->po_itm_qty,
            'already_returned_qty'=>$rc,'free_item'=>$dataa[$i]->free_item,'already returned free'=>$rcfr); 
            
          /*  $det[] = array('item_id'=>$dataa[$i]->po_itm_item_id,'item'=>$data[0]->cat_shortcode."-".$data[0]->item_id,
            'item_des'=>$data[0]->itm_name,'invoiced_price'=>$dataa[$i]->po_itm_unitprice,'invoiced_qty'=>$dataa[$i]->po_itm_qty,
            'already_returned_qty'=>$rc); */
       }
       
       $dataa = response()->json($det);
            return $dataa;
   }
   
    function save_return(Request $request){
        $this->validate($request, [
            'ids' => 'required',
            'values' => 'required',
            'inv_id' => 'required',
            'ret_amnt' => 'required',
            'ret_reason' => 'required',
            'free_return' => 'required'
            
        ]);
        
        //'free_return' => 'required',
        $str_arr = $request->input('ids'); 
        $str_arr1 = $request->input('values'); 
        
        $id = explode (",", $str_arr);
        $qt = explode (",", $str_arr1);
        $inv_id = $request->input('inv_id');
        $ret_amnt = $request->input('ret_amnt');
        $ret_reason = $request->input('ret_reason');
        $free_return = $request->input('free_return');
        if($free_return!=""){
            $frr = explode (",", $free_return);
        }else{
            $frr = 0;
        }
            
        $today = date('Y-m-d');    
        $tot = 0;
        
       
       $headers = $request->header('Authorization');
        $dt = new User;
        $user_data = $dt->getBearerToken($headers);
        $u_name = $user_data[0]->user_name;
        $u_depo = $user_data[0]->user_depoid;
        
        $inv_det = app('db')->select("SELECT `po_discount` FROM `mes_qto` WHERE `po_id` ='$inv_id'");
        if($inv_det[0]->po_discount>0){
            $disval = ($ret_amnt/$inv_det[0]->po_discount)*100; 
            $ret_amnt= $ret_amnt-$disval;}
        
        $add_invntry = app('db')->insert("INSERT INTO `inv_return` (`ret_invnum`, `ret_totqty`, `ret_amount`, `ret_reason`, `ret_depo`, `ret_cuser`, `ret_cdate`) 
        VALUES ('$inv_id', '$tot','$ret_amnt','$ret_reason','$u_depo','$u_name','$today') ");  
        
        $det = app('db')->select("SELECT `ret_id` FROM `inv_return` WHERE `ret_cuser` ='$u_name' ORDER BY `ret_id` DESC LIMIT 1");
        $insert_id = $det[0]->ret_id;
        
        for($i=0; $i<count($id); $i++){
                if($qt[$i]!=""){
                    
                       // $un_pr = app('db')->select("SELECT `po_itm_unitprice` FROM `qto_items` WHERE `po_itm_po_id` ='$inv_id' and `po_itm_item_id` ='$qt[$i]'");
                       // $unit_price = $un_pr[0]->po_itm_unitprice;
                   
                    $data = app('db')->insert("INSERT INTO `mes_inventry` (`invt_type`, `invt_type_id`, `invt_itemid`, `invt_qty`, `cal`, `invt_cuser`, `invt_cdate`) 
                    VALUES ('INVRTN','$insert_id','$id[$i]','$qt[$i]','plus','$u_name','$today') ");
                    
                      $data = app('db')->insert("INSERT INTO `return_items` (`ret_itm_item_id`, `depo_id`, `ret_note_id`, `ret_inv_id`, `ret_itm_qty`, `free_item`, 
                     `ret_aprvl`, `ret_user`) 
                    VALUES ('$id[$i]', '$u_depo', $insert_id, '$inv_id', '$qt[$i]', '$frr[$i]','0', '$u_name') ");  
                    
                    $tot = $tot+$qt[$i];
                }
            }
            
            $updt = app('db')->update("UPDATE `inv_return` SET `ret_totqty`='$tot' WHERE `ret_id`='$insert_id'");
            
            if($updt){
                $send = "New Invoice Return Created";
            }else{
                $send = "Please Retry";
            }
            
        $gtcustom = app('db')->select("SELECT `po_sup_id` FROM `mes_qto` WHERE `po_id` ='$inv_id'");
        $cust_id = $det[0]->po_sup_id;    
        
        $credit_cal = new Payment();
       $chk = $credit_cal->cal_credit_limit($cust_id);    
            
        $dataa = response()->json($send);
            return $dataa;    
            
    }  
    
    function grn_auth(Request $request){
        $this->validate($request, [
            'ret_id' => 'required'
            
        ]);
        
        $id = $request->input('ret_id');
        $data = app('db')->select("SELECT * FROM `mes_inventry` WHERE `invt_type` ='INVRTN' and `invt_type_id` ='$id' and `invt_proc` ='0' ");
        $dep = app('db')->select("SELECT * FROM `inv_return` WHERE `ret_id` ='$id'");
        $dept = $dep[0]->ret_depo;
        for($i=0; $i<count($data); $i++){
                    $invv = $data[$i]->invt_id;
                 $updt = app('db')->update("UPDATE `mes_inventry` SET `invt_proc`='1' WHERE `invt_type`='INVRTN' and `invt_id`='$invv'");
                 
                  $cal = new Invoice();
                 $cal_stock = $cal->cal_stock_no_inventry('$dept',"INVRTN",'$id','$data[$i]->invt_itemid','$data[$i]->invt_qty',"plus","0"); 
            }
            
         $updt = app('db')->update("UPDATE `inv_return` SET `ret_proceed`='1' WHERE `ret_id`='$id'");
         $inv = app('db')->select("SELECT * FROM `mes_qto` WHERE `po_id` ='$dept'");
         
         if($inv[0]->po_payment < 1){
                    $new_amnt = $inv[0]->return_amnt + $dep[0]->ret_amount; 
                    
                   $updt = app('db')->update("UPDATE `mes_qto` SET `return_amnt`='$new_amnt' WHERE `po_id`='$dept'");
                   $updt = app('db')->update("UPDATE `inv_return` SET `ret_to_inv`='1' WHERE `ret_id`='$id'");
                }
        $ret = "Return Data Authorized";
        
        $dataa = response()->json($ret);
            return $dataa;  
    } 
    
}
