<?php
namespace App\Http\Controllers;
use App\Helpers\Frontend;
use App\Models\Admin_user;
use App\Models\Otpsession;
use App\Models\User;
use App\Models\Webhook;
use App\Models\School_setting;
use App\Models\Feesallotment;
use App\Models\Online_payment;
use App\Models\Feescollection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use DB;

class WebhookInstamojo extends Controller
{



	public function index(Request $request)
	{
		$data = $request->all();;
        // dd($data);

        // $webhook_data = array(
        //     'type'=>'instamojo',
        //     'data'=>json_encode($data)
        // );

        // Webhook::create($webhook_data);



		$ver = explode('.', phpversion());
		$major = (int) $ver[0];
		$minor = (int) $ver[1];

		if($major >= 5 and $minor >= 4){
		     ksort($data, SORT_STRING | SORT_FLAG_CASE);
		}
		else{
		     uksort($data, 'strcasecmp');
		}

		// $mac_calculated = hash_hmac("sha1", implode("|", $data), "21038af8125f493cb615c5b48d3a93c7");

		// if($mac_provided == $mac_calculated){

		    // Do something here


		    if($data['status'] == "Credit"){



		    	$pay_req_id = $data['payment_request_id'];
        		$payment_id = $data['payment_id'];

               $onlinePayment =  Online_payment::where(['payment_request_id'=>$pay_req_id])->first();

               $paymentCredintials = School_setting::where(['admin_id'=>$onlinePayment->admin_id,'school_id'=>$onlinePayment->school_id])->first();

               $api_key = $paymentCredintials->instamojo_key??'';
               $api_token = $paymentCredintials->instamojo_token??'';


        		 if (!empty($pay_req_id) && !empty($payment_id))
		        {
                    $data = array(
		                        'trans_id' => $payment_id,
		                        'status' => $data['status'],

		                    );

                        Online_payment::where(['payment_request_id'=>$pay_req_id])->update($data);




		            // Start Payment Request -------------------------------------------
		            $ch = curl_init();
		            curl_setopt($ch, CURLOPT_URL, 'https://www.instamojo.com/api/1.1/payments/'.$payment_id . '/');
		            // curl_setopt($ch, CURLOPT_URL, PAYMENT_URL . $payment_id . '/');
		            curl_setopt($ch, CURLOPT_HEADER, FALSE);
		            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

		            curl_setopt($ch, CURLOPT_HTTPHEADER,
                        array(
                            'X-Api-Key: '.$api_key.'',
                            'X-Auth-Token: '.$api_token.''
                        )
                    );



		            $response = curl_exec($ch);
		            curl_close($ch);

		            // End Payment Request -------------------------------------------
		            $res = json_decode($response);

		            if ($res->success)
		            {
		                $payemntDetails = $res->payment;

		                if ($payemntDetails->status == "Credit")
		                {
		                    $_transID              = $payemntDetails->payment_id;
		                    $_status               = $payemntDetails->status;

		                    $_amount               = $payemntDetails->amount;

		                    $_fees                 = $payemntDetails->fees;

		                    $_payment_request      = $payemntDetails->payment_request;
		                    $_instrument_type      = $payemntDetails->instrument_type;
		                    $_created_at           = $payemntDetails->created_at;

		                    // Update Status of Billing Table
		                    $u_data = array(
		                        // 'trans_id' => $_transID,
		                        // 'paymentstatus' => $_status,
		                        'instrument_type' => $_instrument_type
		                    );

                            Online_payment::where(['payment_request_id'=>$pay_req_id])->update($u_data);

                           $feesallotment_ids =  explode(",",$onlinePayment->feesallotment_id);
                           if(!empty($feesallotment_ids))
                           {
                            foreach($feesallotment_ids as $feesallotment_id)
                            {
                                $feesallotment = Feesallotment::where(['id'=>$feesallotment_id])->first(['amount']);

                                $data = array(
                                    'user_id'=>$onlinePayment->user_id,
                                    'feesallotment_id'=>$feesallotment_id,
                                    'amount'=>$feesallotment->amount,
                                    'payment_id'=>$_transID,
                                    'mode'=>$_instrument_type,
                                    'fine'=>0,
                                    'discount'=>0,
                                    'note'=>'online',
                                    'payment_status'=>$payemntDetails->status,
                                    'payment_date'=>date('Y-m-d'),
                                );

                                Feescollection::create($data);

                            }
                           }



                            return redirect('thankyou?transaction_id='.$_transID);

		                }
		                else
		                {
		                    return redirect('thankyou');
		                }
		            }
		            else
		            {
		                return redirect('thankyou');
		            }
		        }
		        else
		        {
		            return redirect('thankyou');
		        }


		    }
		    else{
		       // Payment was unsuccessful, mark it as failed in your database
		    }
		// }
		// else{
		//     echo "Invalid MAC passed";
		// }


	}








}