<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Invoice;
use App\User;
use App\Payment;

class PaymentController extends Controller
{
 
    public function __construct()
    {
       // $this->middleware('auth');
    }

    function inv_to_pay(Request $request){
        
        $this->validate($request, [
            'cust_id' => 'required'
            
        ]);
       $cust = $request->input('cust_id');
       
      // $inv = app('db')->select("SELECT * FROM `mes_qto` WHERE `po_payment` = 0 AND `po_status`=1 AND `po_auth`=1 AND `po_sup_id`='$cust'");
       $inv = app('db')->select("SELECT * FROM `mes_qto` WHERE `po_payment` = 0 AND `po_status`=1 AND `po_sup_id`='$cust'");
      
        
        //for($i=0; $i<count($inv); $i++){
          //  $paym = app('db')->select("SELECT * FROM `mes_qto` WHERE `po_payment` = 0 AND `po_status`=1 AND `po_auth`=1 AND `po_sup_id`='$cust'");
            // $invdt[] = array($inv[$i]->po_code,$inv[$i]->po_id); 
        //}
        for($i=0; $i<count($inv); $i++){
            $qtoid = $inv[$i]->po_id;
           $chkk = app('db')->select("SELECT * FROM `inv_return` WHERE `ret_stetus`=1 AND `ret_invnum`='$qtoid' 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);
                //}
               
           }
               
        }
        
        if(empty($invdt)){
            $invdt = "";
        }
        
        $custom = app('db')->select("SELECT * FROM `mes_customer` WHERE `cust_id`='$cust'");
        $data['invoice'] = $invdt;
        $data['return_excess'] = $custom[0]->cust_return_excess;
        $data['payment_excess'] = $custom[0]->cust_pay_excess;;

        $data = response()->json($data);
           return $data;
    }
    
    function all_pay(Request $request){
         $headers = $request->header('Authorization');
                        $dt = new User;
                        $user_data = $dt->getBearerToken($headers);
                        $user_name = $user_data[0]->user_name;
                        $user_id = $user_data[0]->user_id;
        
        $inv = app('db')->select("SELECT `mes_payment_main`.*,`mes_customer`.`cust_company` FROM `mes_payment_main` 
        JOIN `mes_customer` on `mes_customer`.`cust_id`=`mes_payment_main`.`pay_cust_id` WHERE `pay_stetus`=1 AND `mes_customer`.`cust_salseperson`= '$user_id' ORDER BY `pay_id` DESC");
        
        
        for($i=0; $i<count($inv); $i++){
            $link = 'https://demo.webip.lk/nance/payslip/'.$inv[$i]->pay_uniqid;
            
            $invdt[] = array('payment_id'=>$inv[$i]->pay_id,'link'=>$link); 
        }
        
        if(count($inv)<1){
            $invdt[] = array();
        }
        
        $data = $invdt;
       array_push($inv,$invdt);

        $data = response()->json($inv);
            return $data;
    }
    
    function sin_inv_data(Request $request){
        $this->validate($request, [
            'invid' => 'required'
        ]);

       $id = $request->input('invid');
        $inv = app('db')->select("SELECT `po_final_tot`,`return_amnt` FROM `mes_qto` WHERE `po_id`='$id'");
        if(count($inv)>0){
            $data['inv_amnt'] = $inv[0]->po_final_tot;
         $data['return_amnt'] = $inv[0]->return_amnt;
        
       // $invbal = app('db')->select("SELECT SUM(`pay_amount`) AS `pay_amount` FROM `mes_payment` WHERE `pay_stetus` = 1 AND `pay_authrize` = 1 AND `pay_invid` = '$id'");
        $invbal = app('db')->select("SELECT SUM(`pay_amount`) AS `pay_amount` FROM `mes_payment` WHERE `pay_stetus` = 1 AND `pay_invid` = '$id'");
        
        if(is_null($invbal[0]->pay_amount)){$data['inv_bal'] = 0;}else{$data['inv_bal'] = $invbal[0]->pay_amount;}
        
        }else{
            $data['inv_amnt'] = 0;
         $data['return_amnt'] = 0;
         $data['inv_bal'] = 0;
           // $data = "Incorrect ID";
        }
        
        $data['tot_balance'] = ($data['inv_amnt'] - $data['return_amnt']-$data['inv_bal']);
        
        $dataa = response()->json($data);
            return $dataa;
        
    }
    
    function save_payment(Request $request){
        
        $this->validate($request, [
            'paytype' => 'required',
            'amount' => 'required',
            'cust_id' => 'required'
            
        ]);
        
            $invid = "";
            $pay_bbranch = $chk_id=$chk_bank=$chk_date=0;
            $paytype = $request->input('paytype');
            if (!empty($request->input('chk_id'))) {
                  $chk_id = $request->input('chk_id');
                }
            if (!empty($request->input('chk_bank'))) {
                  $chk_bank = $request->input('chk_bank');
                } 
            
            $chk_date = $request->input('chk_date');
           
                if (!empty($request->input('pay_branch'))) {
                  $pay_bbranch = $request->input('pay_branch');
                }
                
                    if (!empty($request->input('user_name'))) {
                      $user_name = $request->input('user_name');
                    }else{
                        $headers = $request->header('Authorization');
                        $dt = new User;
                        $user_data = $dt->getBearerToken($headers);
                        $user_name = $user_data[0]->user_name;
                    }
                
            $pay_amount = $request->input('amount');
            $chk_remark = $request->input('remark');
            $cust_id = $request->input('cust_id');
            $invo = $request->input('invoices');
            $valu = $request->input('values');
            $ref = $user_name;
            //$balance = $request->input('balance');
            $today = date('Y-m-d');
            $unc = new Invoice();
            $uniq_id = $unc->unique_code(10);
            if($chk_date==""){
               $chk_date = "1999-01-01";
            }
            $chk_date = date("Y-m-d H:i:s", strtotime($chk_date));
            
            
            
               $invoices = explode(",",$invo);
                $values = explode(",",$valu);
                $inv_tval = 0;
                for($i=0; $i<count($invoices); $i++){
                   $inv_tval= $inv_tval+ $values[$i];
                }
            $balance = $pay_amount - $inv_tval;
            if($balance < 0){
                $ret = "Incorrect amount for Invoices";
            }else{
                
                $cust_dt = app('db')->select("SELECT `cust_salseperson`,`cust_pay_excess`, `cust_return_excess` FROM `mes_customer` WHERE `cust_id`='$cust_id'");
                    $sale_ref = $cust_dt[0]->cust_salseperson;
                      
                    $main = app('db')->insert("INSERT INTO `mes_payment_main` (`pay_type`,`pay_uniqid`,`pay_cust_id`,`pay_ref_id`, `pay_chkid`, `pay_chkbnk`,`pay_bbranch`, `pay_chkdate`,
                    `pay_amount`, `pay_date`, `pay_user`, `pay_remark`,`pay_balance`) VALUES
                    ('$paytype','$uniq_id', '$cust_id','$sale_ref','$chk_id', '$chk_bank', '$pay_bbranch', '$chk_date','$pay_amount', '$today', '$ref', '$chk_remark','$balance')");
                    
                    $main_data = app('db')->select("SELECT `pay_id` FROM `mes_payment_main` WHERE `pay_user` = '$ref' ORDER BY `pay_id` DESC");
                    $main_id = $main_data[0]->pay_id;
                    $invoices = explode(",",$invo);
                    $values = explode(",",$valu);
                    
                    if($main){
                            for($i=0; $i<count($invoices); $i++){
                        
                             $result = app('db')->insert("INSERT INTO `mes_payment` (`pay_type`,`pay_uniqid`, `pay_chkid`, `pay_chkbnk`,`pay_bbranch`, `pay_chkdate`, `pay_amount`, `pay_invid`, `pay_date`, `pay_user`, `pay_remark`,`pay_main_id`) VALUES
                                ('$paytype','$uniq_id', '$chk_id', '$chk_bank', '$pay_bbranch','$chk_date', '$values[$i]', '$invoices[$i]','$today','$ref','$chk_remark','$main_id')");
                            }
                    
                         $ret = "New Payment Saved";
                        if($paytype==3){
                            $rem_pay = $cust_dt[0]->cust_pay_excess;
                            $new_pay = $rem_pay - $inv_tval;
                            $updt = app('db')->update("UPDATE `mes_customer` SET `cust_pay_excess`='$new_pay' WHERE `cust_id`='$cust_id'");
        
                        }elseif($paytype==4){
                            $rem_pay = $cust_dt[0]->cust_return_excess;
                            $new_pay = $rem_pay - $inv_tval;
                            $updt = app('db')->update("UPDATE `mes_customer` SET `cust_return_excess`='$new_pay' WHERE `cust_id`='$cust_id'");
                        }
                        
                         $cust_det = app('db')->select("SELECT `cust_salseperson`,`cust_pay_excess`, `cust_return_excess` FROM `mes_customer` WHERE `cust_id`='$cust_id'");
                        if(($balance>0)&&($paytype<3)){
                            $rem_pay = $cust_det[0]->cust_pay_excess;
                            $new_pay = $rem_pay + $balance;
                            $updt = app('db')->update("UPDATE `mes_customer` SET `cust_pay_excess`='$new_pay' WHERE `cust_id`='$cust_id'");
                        } 
                         
                    }else{
                        $ret = "Please Re enter all details";
                    }
                
            } 
      //delete this if error occured      
        $credit_cal = new Payment();
       $chk = $credit_cal->cal_credit_limit($cust_id);
       
        $dataa = response()->json($ret);
        return $dataa;
       
    }

    function authpay(Request $request){
        $this->validate($request, [
            'payid' => 'required',
            'username' => 'required',
            
        ]);
        $username = $request->input('username');
        $payid = $request->input('payid');
        $today = date('Y-m-d');
        
        $result = app('db')->update("UPDATE `mes_payment` SET `pay_authrize`='1',`pay_authuser`='$username',`pay_authdate`='$today' WHERE `pay_id` = '$payid'");
        
        if($result){
                    $ret[0] = "Payment Authorize";
                }else{
                    $ret[0] = "No Invoice Found";
                }
        $inv = app('db')->select("SELECT `pay_invid` FROM `mes_payment` WHERE `pay_id`='$payid'");
        $invid = $inv[0]->pay_invid;
        
        $det = app('db')->select("SELECT `po_final_tot` FROM `mes_qto` WHERE `po_id`='$invid'");
        $invidtot = $det[0]->po_final_tot;
        
        $invbal = app('db')->select("SELECT SUM(`pay_amount`) AS `pay_amount` FROM `mes_payment` WHERE `pay_stetus` = 1 AND `pay_authrize` = 1 AND `pay_invid` = '$invid'");
        $paytot = $invbal[0]->pay_amount;  
        
        if($invidtot <= $paytot){
                 $result = app('db')->update("UPDATE `mes_qto` SET `po_payment`='1' WHERE `po_id` = '$invid'");
       
                 if($result){
                    $ret[1] = "Invoice Payment Completed";
                }else{
                    
                    $ret[1] = "Invoice Not Complete";
                }
            }else{
                $ret[1] = "Invoice Not Complete";
            }
            
        $dataa = response()->json($ret);
            return $dataa;    
        
    }
    
    function cancelpay(Request $request){
        $this->validate($request, [
            'payid' => 'required',
            'username' => 'required',
            
        ]);
        $username = $request->input('username');
        $payid = $request->input('payid');
        $today = date('Y-m-d');
        
        
        $result = app('db')->update("UPDATE `mes_payment` SET `pay_stetus`='0',`pay_canuser`='$username',`pay_candate`='$today' WHERE `pay_id` = '$payid'");
        if($result){
                    $ret[0] = "Invoice Payment Cancled";
                }else{
                    
                    $ret[0] = "Please Retry";
                }
                
        $inv = app('db')->select("SELECT `pay_invid` FROM `mes_payment` WHERE `pay_id`='$payid'");
        $invid = $inv[0]->pay_invid;        
        
        $det = app('db')->select("SELECT `po_final_tot` FROM `mes_qto` WHERE `po_id`='$invid'");
        $invidtot = $det[0]->po_final_tot;
        
        $invbal = app('db')->select("SELECT SUM(`pay_amount`) AS `pay_amount` FROM `mes_payment` WHERE `pay_stetus` = 1 AND `pay_authrize` = 1 AND `pay_invid` = '$invid'");
        $paytot = $invbal[0]->pay_amount; 
        
        if($invidtot >= $paytot){
                
                 $result = app('db')->update("UPDATE `mes_qto` SET `po_payment`='0' WHERE `po_id` = '$invid'");
                 if($result){
                    $ret[1] = "Pending Payment";
                }else{
                    
                    $ret[1] = "Invoice Payment Completed";
                }
            }else{
                $ret[1] = "Invoice Payment Completed";
            }
        $dataa = response()->json($ret);
            return $dataa;      
    }
    
    function get_bank(){
        $inv = app('db')->select("SELECT `bank_id`,`bank_name` FROM `mes_bank` WHERE `bank_stetus`=1");
        $data = response()->json($inv);
            return $data;
        
    }
    
    function get_bank_branch(){
        $results = app('db')->select("SELECT `id`,`name_en` from `cities`");
        $data = response()->json($results);
            return $data;
        
    }
}
