<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Softon\Indipay\Facades\Indipay;  
use App\Libraries\Crypto;
use App\Models\User;
use App\Models\News;
use App\Models\NewsCategories;
use App\Models\NewsMeta;
use App\Models\Option;
use App\Models\Subscribers;
use App\Models\Trackingreport;
use App\Models\SubscribersMeta;
use App\Models\FAQ;
use App\Models\FAQMeta;
use App\Models\CourseApplied;
use App\Models\Members;
use App\Models\Payments;
use App\Models\EventCategories;
use App\Models\Events;
use App\Models\Eventsport;
use App\Models\GalleryCategories;
use App\Models\MembersMeta;
use App\Models\Gallery;
use App\Models\Upload;
use App\Models\Eventregistration;
use App\Models\Eventregistrationcustomfields;
use App\Models\Customfieldmeta;
use App\Models\Customfield;
use App\Models\Jobopportunities;
use DateTime;
use Response;
use Validator;
use Redirect;
use DB;
use Session;
use Crypt;

class FrontendController extends Controller
{
    public function indexpageget(){
    	return view("frontend/index");
    }
    
    public function testingg(){
        return Hash::make('password');
    }

    public function aboutpageget(){
    	return view("frontend/about");
    }

    public function pastpresidentspageget(){
    	return view("frontend/past-presidents");
    }

    public function executivecomitteepageget(){
    	return view("frontend/executive-comittee");
    }

    public function ourfacilitiespageget(){
    	return view("frontend/our-facilities");
    }

    public function courseofferedpageget(){
    	return view("frontend/course-offered");
    }

    public function eligibilitypageget(){
        return view("frontend/eligibility");
    }

    public function facultypageget(){
        return view("frontend/faculty");
    }

    public function courseapplicationpageget(){
        return view("frontend/course-application");
    }

    public function custom_fields_exist($dynamic_field,$type,$name) {
        $exist = false;
        $value = '';
        if(isset($dynamic_field[$name])) {
            $exist = true;
            $value = $dynamic_field[$name];
        }
        if($type == 'value') {
            return $value;
        }else{
            return $exist;
        }
    }

    public function eventregistrationpost(Request $req){
        try{
            $input = $req->all();
            $id = decrypt($req->hiddenId);
            $info = Events::find($id);

            $isSport = $info->isSportEvent;
            if($isSport == 'yes'){

            }
            $m_type = $info->isSportEvent;
            $e_type = $info->entryType;
            $entryAmount = 0;
            
            if($m_type == 'badminton' || $m_type == 'tennis'){
                $msg = ['required'=>'this field is required'];
                $validation = Validator::make($input, ['typeOfTeam'=>'required'], $msg);
                if ($validation->fails()) {
                    return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                }
                if($e_type == 'paid'){
                    if($input['typeOfTeam'] == 'single'){
                        if($input['userType'] == 'yes'){
                            $entryAmount = $info->memberFee * $input['singlePlayerCount'];
                        }else{
                            $entryAmount = $info->nonMemberFee * $input['singlePlayerCount'];
                        }

                        $crules = [];
                        for($i = 1; $i<= $input['singlePlayerCount']; $i++){
                            $crules['singleplayer_'.$i] = 'required';
                        }
                        $crules['singlePlayerCount'] = 'required';
                        if(count($crules) != 0){
                            $crules['singlePlayerCount'] = 'required';
                            $msg = ['required'=>'this field is required'];
                            $validation = Validator::make($input, $crules, $msg);
                            if ($validation->fails()) {
                                return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                            }
                        }

                    }else if($input['typeOfTeam'] == 'double'){
                        if($input['userType'] == 'yes'){
                            $entryAmount = $info->doublesMemberFee * $input['doublePlayerCount'];
                        }else{
                            $entryAmount = $info->doublesNonMemberFee * $input['doublePlayerCount'];
                        }
                        $crules = [];
                        for($i = 1; $i<= ($input['doublePlayerCount'] * 2); $i++){
                            $crules['doubleplayer_'.$i] = 'required';
                        }
                        $crules['doublePlayerCount'] = 'required';
                        if(count($crules) != 0){
                             $crules['doublePlayerCount'] = 'required';
                             $msg = ['required'=>'this field is required'];
                            $validation = Validator::make($input, $crules, $msg);
                            if ($validation->fails()) {
                                return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                            }
                        }

                    }else if($input['typeOfTeam'] == 'both'){
                        if($input['userType'] == 'yes'){
                            $entryAmount = $info->memberFee * $input['singlePlayerCount'];
                            $entryAmount = $entryAmount + ($info->nonMemberFee * $input['doublePlayerCount']);
                        }else{
                            $entryAmount = $info->nonMemberFee * $input['singlePlayerCount'];
                            $entryAmount = $entryAmount + ($info->doublesNonMemberFee * $input['doublePlayerCount']);
                        }
                        $crules = [];
                        for($i = 1; $i<= $input['singlePlayerCount']; $i++){
                            $crules['singleplayer_'.$i] = 'required';
                        }
                        $crules['singlePlayerCount'] = 'required';
                        if(count($crules) != 0){
                            $msg = ['required'=>'this field is required'];
                            $validation = Validator::make($input, $crules, $msg);
                            if ($validation->fails()) {
                                return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                            }
                        }
                        $crules = [];
                        for($i = 1; $i<= ($input['doublePlayerCount'] * 2); $i++){
                            $crules['doubleplayer_'.$i] = 'required';
                        }
                        $crules['doublePlayerCount'] = 'required';
                        if(count($crules) != 0){
                            $msg = ['required'=>'this field is required'];
                            $validation = Validator::make($input, $crules, $msg);
                            if ($validation->fails()) {
                                return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                            }
                        }
                    }
                }
            }else if($m_type == 'cricket'){
                if($e_type == 'paid'){
                    if($input['userType'] == 'yes'){
                        $entryAmount = $info->memberFee;
                    }else{
                        $entryAmount = $info->nonMemberFee;
                    }
                }
                $crules = [];
                for($i = 1; $i<= $info->maximumPlayer; $i++){
                    $crules['cplayer_'.$i] = 'required';
                }
                if(count($crules) != 0){
                     $msg = ['required'=>'this field is required'];
                    $validation = Validator::make($input, $crules, $msg);
                    if ($validation->fails()) {
                        return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                    }
                }
            }else if($m_type == 'no'){
                if($e_type == 'paid'){
                    if($input['userType'] == 'yes'){
                        $entryAmount = $info->memberFee;
                    }else{
                        $entryAmount = $info->nonMemberFee;
                    }
                }
            }

            if($info && $entryAmount > 0){
                $fees = $entryAmount;
                $tickets = $input['tickets'];
                //validation
                    $rules = [];
                    $custom_fields = Customfield::Event($id)->NotDeleted()->ModuleName('event_reg')->Required()->get();
                    foreach($custom_fields as $field){
                        if($field->field_type == 'single_file_upload' || $field->field_type == 'multiple_file_upload') {
                            if(!$req->hasFile($field->field_slug)){
                                $input[$field->field_slug] = '';
                                $rules[$field->field_slug] = 'required';
                            }else{
                                if($field->field_type == 'single_file_upload'){ 
                                    $rules[$field->field_slug] = "mimes:png,jpg,jpeg,pdf,doc"; 
                                }else{ 
                                    $rules[$field->field_slug.'.*'] = "mimes:png,jpg,jpeg,pdf,doc";
                                }
                            }
                        }else if($field->field_type == 'datepicker' || $field->field_type == 'dateandtime'){
                            $rules[$field->field_slug] = 'required|date';
                        }else if($field->field_type == 'phonenumber' || $field->field_type == 'numbers'){
                            $rules[$field->field_slug] = 'required|integer';
                        }else if($field->field_type == 'amount'){
                            $rules[$field->field_slug] = 'required|numeric';
                        }else if($field->field_type == 'email'){
                            $rules[$field->field_slug] = 'required|email';
                        }else{
                            $rules[$field->field_slug] = 'required';
                        }
                    }
                    $msg = ['required'=>'this field is required','image'=>'file required','mimes'=>'wrong file format','date'=>'enter valid date','numeric'=>'enter valid number','integer'=>'enter valid number','email'=>'enter valid email'];
                    $validation = Validator::make($input, $rules, $msg);
                    if ($validation->fails()) {
                        return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                    }
                //validation
                $fees = $entryAmount;
                $tickets = $req->tickets;
                $amount = $tickets*$fees;
                $gst = Option::getvalue('GST');
                //$gstAmount =($amount*$gst)/100;
                $gstAmount = 0;
                $totalAmount = $amount+$gstAmount;

                //insert event 
                $insert = new Eventregistration();
                $insert->eventId = $id;
                $insert->userId = Auth::id();
                $insert->email = Auth::user()->email;
                $insert->tickets = $tickets;
                $insert->amount = $fees;
                $insert->gstPercentage = $gst;
                $insert->emailStatus = 'no';
                $insert->totalAmount = $totalAmount;

                $typeOfTeam = '';
                if(isset($input['typeOfTeam'])){    
                    $typeOfTeam = $input['typeOfTeam'];
                }
                $insert->typeOfTeam = $typeOfTeam;
                $insert->isSportEvent = $info->isSportEvent;
                $insert->save();

                $uniqueID = "E".date('Ymd').str_pad($insert->id, 5, '0', STR_PAD_LEFT);
                $update = Eventregistration::find($insert->id);
                $update->uniqueId = $uniqueID;
                $update->save();
                //insert event

                //insert dynamic fields
                foreach($input as $key=>$value) {
                    $custom_fields = Customfield::Event($id)->NotDeleted()->ModuleName('event_reg')->Slug($key)->first();
                    if($custom_fields){
                        $replace_val = $value;
                        $tmp_name_string = '';
                        $tmp_name = '';
                        if($custom_fields->field_type == 'multiple_file_upload' || $custom_fields->field_type == 'single_file_upload'){
                            $destinationPath = 'backend/uploads/customfields/'; 
                            if($custom_fields->field_type == 'multiple_file_upload') {
                                $files = $req->file($key);
                                $s = 0;
                                foreach($files as $file){
                                    $original_name = pathinfo($file, PATHINFO_FILENAME);
                                    $filename = $file->getClientOriginalName();
                                    $extension = $file->getClientOriginalExtension();
                                    //check if name exist
                                        $tmp_name = $filename;
                                        if ($pos = strrpos($filename, '.')) {
                                            $name = substr($filename, 0, $pos);
                                            $ext = substr($filename, $pos);
                                        } else {
                                            $name = $filename;
                                        }
                                        $uniq_no = 0;
                                        $file_exists = public_path($destinationPath . $filename);
                                        while (file_exists($file_exists)) {
                                            $tmp_name = $name .'_'. $uniq_no . $ext;
                                            $uniq_no++;
                                            $file_exists = public_path($destinationPath . $tmp_name);
                                        }
                                        $upload_success = $file->move($destinationPath, $tmp_name);
                                        $img_url = $destinationPath.$tmp_name;
                                        if($s == 0){
                                            $replace_val = $img_url;
                                            $tmp_name_string = $tmp_name;
                                        }else{
                                            $replace_val = $replace_val.'||'.$img_url;
                                            $tmp_name_string = $tmp_name_string.'||'.$tmp_name;
                                        }
                                        $s++;
                                }
                            }else{
                                $file = $req->file($key);
                                $original_name = pathinfo($file, PATHINFO_FILENAME);
                                $filename = $file->getClientOriginalName();
                                $extension = $file->getClientOriginalExtension();
                                //check if name exist
                                    $tmp_name = $filename;
                                    if ($pos = strrpos($filename, '.')) {
                                        $name = substr($filename, 0, $pos);
                                        $ext = substr($filename, $pos);
                                    } else {
                                        $name = $filename;
                                    }
                                    $uniq_no = 0;
                                    $file_exists = public_path($destinationPath . $filename);
                                    while (file_exists($file_exists)) {
                                        $tmp_name = $name .'_'. $uniq_no . $ext;
                                        $uniq_no++;
                                        $file_exists = public_path($destinationPath . $tmp_name);
                                    }
                                    $upload_success = $file->move($destinationPath, $tmp_name);
                                    $img_url = $destinationPath.$tmp_name;
                                    $replace_val = $img_url;
                                    $tmp_name_string = $tmp_name;
                            }
                        }
                        $insert_custom = new Eventregistrationcustomfields();
                        $insert_custom->event_reg_id = $insert->id;
                        $insert_custom->field_slug = $key;
                        $insert_custom->customfield_id = $custom_fields->id;
                        $insert_custom->field_name = $custom_fields->label_name;
                        $insert_custom->field_value = $replace_val;
                        $insert_custom->extra_field = $tmp_name_string;
                        $insert_custom->field_type = $custom_fields->field_type;
                        $insert_custom->event_id = $id;
                        $insert_custom->user_id = Auth::id();
                        $insert_custom->save();
                    }
                }
                //insert dynamic fields

                if($m_type == 'badminton' || $m_type == 'tennis'){
                    if($input['typeOfTeam'] == 'single'){
                        for($i = 1; $i<= $input['singlePlayerCount']; $i++){
                            $eventsport = new Eventsport();
                            $eventsport->event_id = $id;
                            $eventsport->event_reg_id = $insert->id;
                            $eventsport->player_name = $input['singleplayer_'.$i];
                            $eventsport->status = 'active';
                            $eventsport->typeOfTeam = 'single';
                            $eventsport->save();
                        }
                    }else if($input['typeOfTeam'] == 'double'){
                        for($i = 1; $i<= ($input['doublePlayerCount'] * 2); $i++){
                            $eventsport = new Eventsport();
                            $eventsport->event_id = $id;
                            $eventsport->event_reg_id = $insert->id;
                            $eventsport->player_name = $input['doubleplayer_'.$i];
                            $eventsport->status = 'active';
                            $eventsport->typeOfTeam = 'double';
                            $eventsport->save();
                        }
                    }else if($input['typeOfTeam'] == 'both'){
                        for($i = 1; $i<= $input['singlePlayerCount']; $i++){
                            $eventsport = new Eventsport();
                            $eventsport->event_id = $id;
                            $eventsport->event_reg_id = $insert->id;
                            $eventsport->player_name = $input['singleplayer_'.$i];
                            $eventsport->status = 'active';
                            $eventsport->typeOfTeam = 'single';
                            $eventsport->save();
                        }
                        for($i = 1; $i<= ($input['doublePlayerCount'] * 2); $i++){
                            $eventsport = new Eventsport();
                            $eventsport->event_id = $id;
                            $eventsport->event_reg_id = $insert->id;
                            $eventsport->player_name = $input['doubleplayer_'.$i];
                            $eventsport->status = 'active';
                            $eventsport->typeOfTeam = 'double';
                            $eventsport->save();
                        }
                    }
                }else if($m_type == 'cricket'){
                    for($i = 1; $i<= $info->maximumPlayer; $i++){
                        $eventsport = new Eventsport();
                        $eventsport->event_id = $insert->id;
                        $eventsport->player_name = $input['cplayer_'.$i];
                        $eventsport->status = 'active';
                        $eventsport->typeOfTeam = 'double';
                        $eventsport->save();
                    }
                }

                //payment template start
                    $key = $insert->id;
                    $reqID = $uniqueID;
                    $price = $totalAmount;
                    $tID = time();
                    $billing_email = Auth::user()->email;
                    $billing_name = Auth::user()->firstName." ".Auth::user()->lastName;
                    $billing_address = Auth::user()->address;
                    $billing_tel = Auth::user()->phone;

                    $payu_url = '';
                    $payu_merchant_key = '';
                    $payu_salt = '';

                    if(env('PAYMENT_MODE') == 'test'){
                        $payu_url = env('PAYMENT_TEST_URL');
                        $payu_merchant_key = env('PAYMENT_TEST_MERCHANT_KEY');
                        $payu_salt = env('PAYMENT_TEST_SALT');
                    }else if(env('PAYMENT_MODE') == 'live'){
                        $payu_url = env('PAYMENT_LIVE_URL');
                        $payu_merchant_key = env('PAYMENT_LIVE_MERCHANT_KEY');
                        $payu_salt = env('PAYMENT_LIVE_SALT');
                    }

                    $basicInfo = [
                        'merchant_key' =>$payu_merchant_key,
                        'salt' => $payu_salt,
                        'payu_base_url' => $payu_url, //https://secure.payu.in/_payment
                        'txn_id' => $reqID,
                        'amount' => number_format($price, 2, '.', ''),
                        'productinfo' => 'Event Registration',
                        'firstname' => $billing_name,
                        'email' => $billing_email,
                        'phone' => $billing_tel,
                        'udf1' => 'Event Registration',
                        'udf2' => $key,
                        'udf3' => "",
                        'udf4' => "",
                        'udf5' => "",
                        'udf6' => "",
                        'udf7' => "",
                        'udf8' => "",
                        'udf9' => "",
                        'udf10' => "",
                        'surl' => route('payment.success'),//route('payment.success'),
                        'furl' => route('payment.failure'), //route('payment.failure')
                    ];
                    $hashSequence = "merchant_key|txn_id|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
                    $hashVarsSeq = explode('|', $hashSequence);
                    $hash_string = '';
                    foreach($hashVarsSeq as $hash_var) {
                        $hash_string .= isset($basicInfo[$hash_var]) ? $basicInfo[$hash_var] : '';
                        $hash_string .= '|';
                    }                
                    $hash_string = $hash_string.$basicInfo['salt'];
                    $hash = strtolower(hash('sha512', $hash_string));
                    $basicInfo['hash_string'] = $hash;
                    $template = view('frontend.payment-form-template')->with('basicInfo', $basicInfo)->render();
                //payment template end
                return response()->json(['status'=>'success','template'=>$template]);
            }else{
                return response()->json(['status'=>'error','msg'=>'Error. Please try again']);
            }
        } catch (Exception $e) {
            return response()->json(['status'=>'error','msg'=>'Error. Please try again','res'=>$e->getMessage().'__'.$e->getLine()]);
        }
    }

    public function courseapplicationpagepost(Request $req){
        try {
            //return DB::transaction(function() use($req){
                $input = $req->all();
                $rules = [
                    "name"=>"required",
                    "father_name"=>"required",
                    "address1"=>"required",
                    "address2"=>"required",
                    "dob"=>"required|date",
                    "phone"=>"required",
                    "mobile"=>"required",
                    "emailid"=>"required|email",
                    "photo"=>"required|image|mimes:jpg,png,jpeg",
                    "comment"=>"required",
                    "paymentType"=>"required",
                ];
                $messages = [
                    "required"=>"You can't leave this field empty",
                    "image"=>"Please upload image file only",
                    "date"=>"Please enter a valid date",
                ];
                $validation = Validator::make($input, $rules, $messages);
                if($validation->fails()){
                    return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                }

                $url = "";
                if($req->hasFile('photo')){
                    $file = $req->file('photo');
                    $destinationPath = 'frontend/uploads/'; // upload path
                    $extension = $file->getClientOriginalExtension(); // getting file extension
                    $name = $file->getClientOriginalName();// getting original file name
                    $check = CourseApplied::checkimages(substr($name, 0, -(strlen($extension) + 1)), "/".$destinationPath, $extension);
                    $fileName = $check.'.'.$extension; // renameing image
                    $upload_success = $file->move($destinationPath, $fileName); // uploading file to given path
                    $img_url = $destinationPath.$fileName;
                    $url = URL::asset($img_url);
                }

                $education = array();
                for($i = 0;$i < $input["educationLength"];$i++){
                    $education[$i]['year'] = $input['year'.$i];
                    $education[$i]['school'] = $input['school'.$i];
                    $education[$i]['university'] = $input['university'.$i];
                    $education[$i]['degree'] = $input['degree'.$i];
                    $education[$i]['mark'] = $input['mark'.$i];
                }
                $education = json_encode($education);

                $experience = array();
                for($i = 0;$i < $input["experienceLength"];$i++){
                    $experience[$i]['period'] = $input['period'.$i];
                    $experience[$i]['organisation'] = $input['organisation'.$i];
                    $experience[$i]['designation'] = $input['designation'.$i];
                    $experience[$i]['work'] = $input['work'.$i];
                }
                $experience = json_encode($experience);

                $courseFee = Option::getvalue("courseFee");

                $insert = new CourseApplied();
                $insert->name = $input["name"];
                $insert->father_name = $input["father_name"];
                $insert->address1 = $input["address1"];
                $insert->address2 = $input["address2"];
                $insert->dob = date("Y-m-d", strtotime($input["dob"]));
                $insert->phone = $input["phone"];
                $insert->mobile = $input["mobile"];
                $insert->emailid = $input["emailid"];
                $insert->comment = $input["comment"];
                $insert->education = $education;
                $insert->workexp = $experience;
                $insert->photo = $url;
                $insert->registration_date = date("Y-m-d H:i:s");
                $insert->courseFee = $courseFee;
                $insert->paymentType = $input["paymentType"];
                $insert->status = "inactive";
                $insert->createdBy = Auth::User()->id;
                $insert->save();

                $uniqueID = "APP".date('Ymd').str_pad($insert->id, 3, '0', STR_PAD_LEFT);
                $update = CourseApplied::find($insert->id);
                $update->unique_id = $uniqueID;
                $update->save();

                if($input["paymentType"] == "offline"){
                    $url = url("course-offered/course-application/course-application-payment-offline/".Crypt::encrypt($insert->id));
                    return response()->json(['status'=>'success','type'=>'offline','url'=>$url]);
                }
                //payment if online
                    $key = Crypt::encrypt($insert->id);
                    $info = CourseApplied::find($insert->id);
                    $reqID = $info->unique_id;
                    $price = $info->courseFee;
                    $tID = time();
                    $billing_email = $info->emailid;
                    $billing_name = $info->name;
                    $billing_address = $info->address1;
                    $billing_tel = $info->mobile;

                    // $parameters = [
                    //     'tid' => $tID,
                    //     'order_id' => $reqID,
                    //     'amount' => $price,
                    //     'billing_email'=>$billing_email,
                    //     'billing_name'=>$billing_name,
                    //     'billing_address'=>$billing_address,
                    //     'billing_tel'=>$billing_tel,
                    //     'merchant_param1'=>'Course Application',
                    //     'merchant_param2'=>$key,
                    // ];
                    
                    // $order = Indipay::prepare($parameters);
                    // $response = Indipay::process($order);
                    // return $response;

                    $payu_url = '';
                    $payu_merchant_key = '';
                    $payu_salt = '';

                    if(env('PAYMENT_MODE') == 'test'){
                        $payu_url = env('PAYMENT_TEST_URL');
                        $payu_merchant_key = env('PAYMENT_TEST_MERCHANT_KEY');
                        $payu_salt = env('PAYMENT_TEST_SALT');
                    }else if(env('PAYMENT_MODE') == 'live'){
                        $payu_url = env('PAYMENT_LIVE_URL');
                        $payu_merchant_key = env('PAYMENT_LIVE_MERCHANT_KEY');
                        $payu_salt = env('PAYMENT_LIVE_SALT');
                    }

                    $basicInfo = [
                        'merchant_key' => $payu_merchant_key,
                        'salt' => $payu_salt,
                        'payu_base_url' => $payu_url, //https://secure.payu.in/_payment
                        'txn_id' => $reqID,
                        'amount' => number_format($price, 2, '.', ''),
                        'productinfo' => 'Course Application',
                        'firstname' => $billing_name,
                        'email' => $billing_email,
                        'phone' => $billing_tel,
                        'udf1' => 'Course Application',
                        'udf2' => $key,
                        'udf3' => "",
                        'udf4' => "",
                        'udf5' => "",
                        'udf6' => "",
                        'udf7' => "",
                        'udf8' => "",
                        'udf9' => "",
                        'udf10' => "",
                        'surl' => route('payment.success'),//route('payment.success'),
                        'furl' => route('payment.failure'), //route('payment.failure')
                    ];
                    $hashSequence = "merchant_key|txn_id|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
                    $hashVarsSeq = explode('|', $hashSequence);
                    $hash_string = '';
                    foreach($hashVarsSeq as $hash_var) {
                        $hash_string .= isset($basicInfo[$hash_var]) ? $basicInfo[$hash_var] : '';
                        $hash_string .= '|';
                    }                
                    $hash_string = $hash_string.$basicInfo['salt'];
                    $hash = strtolower(hash('sha512', $hash_string));
                    $basicInfo['hash_string'] = $hash;
                    $template = view('frontend.payment-form-template')->with('basicInfo', $basicInfo)->render();
                    return response()->json(['status'=>'success','template'=>$template,'type'=>'online']);

                 //payment if online
            //});
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            return response()->json(['status'=>'error','msg'=>'Error. Please try again']);
        }
    }

    public function courseapplicationofflinepaymentconfirmationpage($key){
        $id = Crypt::decrypt($key);
        $info = CourseApplied::find($id);
        if($info){
            if($info->emailStatus == "no"){
               try{
                    // Mail::send("emails/courseApplied", ["uniqueID"=>$info->unique_id], function($message) use($info){
                    //     $message->from(Option::getvalue('senderEmail') , Option::getvalue('senderName'));
                    //     $message->to($info->emailid, $info->name);
                    //     $notificationEmail = Option::getvalue("emailNotification");
                    //     if($notificationEmail != ''){
                    //         $message->bcc($notificationEmail, "AdClubMadras");
                    //     }
                    //     $message->subject("New Course Application!");
                    // });
               }catch(\Exception $s){}
                $mobileNumber = '91'.$info->mobile;
                $apiKey = urlencode('OBrkzlECvHw-MfbwgdmGMaXzfy2GBhNB5Jm3VMdR9J');
                $numbers = array($mobileNumber);
                $sender = urlencode('ADCLUB');
                $message = rawurlencode('Your PGDA Course Application submitted successfully. ID '.$info->unique_id.'. Thank you for registering at Ad Club Madras');
                $numbers = implode(',', $numbers);
                $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
                try{
                   // $ch = curl_init('https://api.textlocal.in/send/');
                   //  curl_setopt($ch, CURLOPT_POST, true);
                   //  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                   //  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                   //  $response = curl_exec($ch);
                   //  curl_close($ch);
                   //  $response = json_decode($response);
                   //  $status = $response->status;
                   //  if($status == 'failure'){
                   //      $message = $response->errors[0]->message;
                   //  }
               }catch(\Exception $s){}
            }
            $update = CourseApplied::find($id);
            $update->emailStatus = "yes";
            $update->save();
            return view("frontend/course-application-payment-offline")->with(["info"=>$info]);
        }
        return "Something went wrong, Please contact system Admin";
    }


    public function eventregistrationconfirmationpage($key){
        try {
            $id = $key;
            $info = Eventregistration::find($id);
            if($info){
                if($info->emailStatus == "no"){
                    try{
                        // Mail::send("emails/eventRegistration", ["uniqueID"=>$info->uniqueId], function($message) use($info){
                        //     $message->from(Option::getvalue('senderEmail'), Option::getvalue('senderName'));
                        //     $message->to($info->email, '');
                        //     $notificationEmail = Option::getvalue("emailNotification");
                        //     if($notificationEmail != ''){
                        //         $message->bcc($notificationEmail, "AdClubMadras");
                        //     }
                        //     $message->subject("Event Registration!");
                        // });
                    }catch(\Exception $s) {
                    }
                    $info->emailStatus = "yes";
                    $info->save();
                }
                return view("frontend/event-registration-payment-online")->with(["info"=>$info]);
            }
            return "Something went wrong, Please contact system Admin";
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function courseapplicationonlinepaymentconfirmationpage($req){
        try {
            $id = Crypt::decrypt($req);
            $info = CourseApplied::find($id);
            if($info){
                if($info->emailStatus == "no"){
                    
                    try{
                        // Mail::send("emails/courseApplied", ["uniqueID"=>$info->unique_id], function($message) use($info){
                        //     $message->from(Option::getvalue('senderEmail'), Option::getvalue('senderName'));
                        //     $message->to($info->emailid, $info->name);
                        //     $notificationEmail = Option::getvalue("emailNotification");
                        //     if($notificationEmail != ''){
                        //         $message->bcc($notificationEmail, "AdClubMadras");
                        //     }
                        //     $message->subject("New Course Application!");
                        // });
                    }catch(\Exception $s){}

                    $info->emailStatus = "yes";
                    $info->save();

                    $mobileNumber = '91'.$info->mobile;
                    $apiKey = urlencode('OBrkzlECvHw-MfbwgdmGMaXzfy2GBhNB5Jm3VMdR9J');
                    $numbers = array($mobileNumber);
                    $sender = urlencode('ADCLUB');
                    $message = rawurlencode('Your PGDA Course Application submitted successfully. ID '.$info->unique_id.'. Thank you for registering at Ad Club Madras');
                    $numbers = implode(',', $numbers);
                    $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
                     try{
                        // $ch = curl_init('https://api.textlocal.in/send/');
                        // curl_setopt($ch, CURLOPT_POST, true);
                        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        // $response = curl_exec($ch);
                        // curl_close($ch);
                        // $response = json_decode($response);
                        // $status = $response->status;
                        // if($status == 'failure'){
                        //     $message = $response->errors[0]->message;
                        // }
                    }catch(\Exception $s){}
                }
                return view("frontend/course-application-payment-online")->with(["info"=>$info]);
            }
            return "Something went wrong, Please contact system Admin";
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function postpaymentsuccesspage(Request $req){

        try {

                $payu_salt = '';
                if(env('PAYMENT_MODE') == 'test'){
                    $payu_salt = env('PAYMENT_TEST_SALT');
                }else if(env('PAYMENT_MODE') == 'live'){
                    $payu_salt = env('PAYMENT_LIVE_SALT');
                }

                $status=$req->status;
                $firstname=$req->firstname;
                $amount=$req->amount;
                $txnid=$req->txnid;
                $posted_hash=$req->hash;
                $key=$req->key;
                $productinfo=$req->productinfo;
                $email=$req->email;
                $udf1=$req->udf1;
                $udf2=$req->udf2;
                $salt=$payu_salt;
                // If (isset($_POST["additionalCharges"])) {
                //     $additionalCharges=$_POST["additionalCharges"];
                //     $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                // } else {
                //     $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                // }
                $retHashSeq = $salt.'|'.$status.'|||||||||'.$udf2.'|'.$udf1.'|'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                $hash = hash("sha512", $retHashSeq);
                if ($hash != $posted_hash) {
                    //return "Invalid Transaction. Please try again";
                    //Trackingreport::track("error", "Invalid Transaction. Please try again", "", "", "Course Application");
                    return redirect('/');
                } else {
                    // return "Your order status is ". $status . "Your transaction id for this transaction is ".$txnid.". You may try making the payment by clicking the link below.";
                }

                $insert = new Payments();
                $insert->order_id = $req->txnid;
                $insert->tracking_id = $req->txnid;
                $insert->bank_ref_no = $req->bank_ref_num;
                $insert->order_status = $req->status;
                $insert->failure_message = $req->unmappedstatus;
                $insert->payment_mode = $req->mode;
                $insert->card_name = $req->name_on_card;
                $insert->status_code = $req->error;
                $insert->status_message = $req->field9;
                $insert->amount = $req->amount;
                $insert->trans_date = date("Y-m-d H:i:s");
                $insert->response = json_encode($req->all);
                $insert->save();

                if($req->udf1 == "Course Application" && $req->status == 'success'){
                    //Update Courses
                    $id = Crypt::decrypt($req->udf2);
                    $info = CourseApplied::find($id);
                    $info->paymentStatus = $req->status;
                    $info->paymentMode = $req->mode;
                    $info->trackingID = $req->txnid;
                    $info->paymentDate = date("Y-m-d H:i:s");
                    $info->status = "active";
                    $info->save();
                    return redirect("course-offered/course-application/course-application-payment-online/".$req->udf2);
                }

                if($req->udf1 == "Members Registration" && $req->status == 'success'){
                    //Update Members
                    $id = Crypt::decrypt($req->udf2);
                    $info = Members::find($id);
                    $info->paymentStatus = $req->status;
                    $info->paymentMode = $req->mode;
                    $info->trackingID = $req->txnid;
                    $info->paymentDate = date("Y-m-d H:i:s");
                    $info->status = "active";
                    $info->save();

                    return redirect("membership/membership-application/membership-application-payment-confirmation/".$req->udf2);
                }

                if($req->udf1 == "Membership Renewal" && $req->status == 'success'){
                    //Update Members
                    $id = Crypt::decrypt($req->udf2);
                    $info = Members::find($id);
                    $info->paymentStatus = $req->status;
                    $info->paymentMode = $req->mode;
                    $info->trackingID = $req->txnid;
                    $info->paymentDate = date("Y-m-d H:i:s");
                    $info->status = "active";
                    $info->save();
                    return redirect("membership/membership-application/membership-application-renewal-payment-confirmation/".$req->udf2);
                }


                if($req->udf1 == "Event Registration" && $req->status == 'success'){
                    //Update Members
                    $id = $req->udf2;
                    $info = Eventregistration::find($id);
                    $info->paymentStatus = $req->status;
                    $info->paymentMode = $req->mode;
                    $info->trackingID = $req->txnid;
                    $info->paymentDate = date("Y-m-d H:i:s");
                    $info->status = "active";
                    $info->save();
                    return redirect("eventregistration/confirmationpage/".$req->udf2);
                }

                if($req->status != 'success'){
                    $paymentID = Crypt::encrypt($insert->id);
                    return redirect("payment/gateway/failure/".$paymentID);
                }

        }  catch (Exception $e) {
            //return $e->getMessage().'_'.$e->getLine();
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            //return redirect()->back()->with("error", "Something went wrong");
            return redirect('/');
        }
    }

    public function postpaymentfailurepage(Request $req){
        try {
                $payu_salt = '';
                if(env('PAYMENT_MODE') == 'test'){
                    $payu_salt = env('PAYMENT_TEST_SALT');
                }else if(env('PAYMENT_MODE') == 'live'){
                    $payu_salt = env('PAYMENT_LIVE_SALT');
                }

                //return $req->all();
                $status=$req->status;
                $firstname=$req->firstname;
                $amount=$req->amount;
                $txnid=$req->txnid;
                $posted_hash= $req->hash;
                $key= $req->key;
                $productinfo= $req->productinfo;
                $email= $req->email;
                $udf1= $req->udf1;
                $udf2= $req->udf2;
                $salt= $payu_salt;
                // If (isset($_POST["additionalCharges"])) {
                //     $additionalCharges=$_POST["additionalCharges"];
                //     $retHashSeq = $additionalCharges.'|'.$salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                // } else {
                //     $retHashSeq = $salt.'|'.$status.'|||||||||||'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                // }
                $retHashSeq = $salt.'|'.$status.'|||||||||'.$udf2.'|'.$udf1.'|'.$email.'|'.$firstname.'|'.$productinfo.'|'.$amount.'|'.$txnid.'|'.$key;
                $hash = hash("sha512", $retHashSeq);
                if ($hash != $posted_hash) {
                    //return "Invalid Transaction. Please try again";
                    //Trackingreport::track("error", "Invalid Transaction. Please try again", "", "", "Course Application");
                    return redirect('/');
                } else {
                    //return "Your order status is ". $status . "Your transaction id for this transaction is ".$txnid.". You may try making the payment by clicking the link below.";
                }

                $insert = new Payments();
                $insert->order_id = $req->txnid;
                $insert->tracking_id = $req->txnid;
                $insert->bank_ref_no = $req->bank_ref_num;
                $insert->order_status = $req->status;
                $insert->failure_message = $req->unmappedstatus;
                $insert->payment_mode = $req->mode;
                $insert->status_code = $req->error;
                $insert->status_message = $req->field9;
                $insert->amount = $req->amount;
                $insert->trans_date = date("Y-m-d H:i:s");
                $insert->response = json_encode($req->all);
                $insert->save();
                $paymentID = Crypt::encrypt($insert->id);
                return redirect("payment/gateway/failure/".$paymentID);
        }  catch (Exception $e) {
           // Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            //return $e->getMessage();
            return redirect('/');
        }
    }

    public function getpaymentfailurepage($key){
        $id = Crypt::decrypt($key);
        $check = Payments::find($id);
        if($check){
            return view("frontend/payment-failure")->with(["uniqueID"=>$check->order_id, "status"=>$check->order_status]);
        }
        return "This transaction can't be found";
    }

    public function membershippageget(){
        return view("frontend/membership");
    }

    public function membershipapplicationpageget(){
        $auth_id = 'tesitgn';
        if(Auth::check()){
            $auth_id = Auth::id();
        }
        $record = Members::where('createdBy', $auth_id)->where('status', 'active')->orderBy('id', 'DESC')->first();
        return view("frontend/membership-application", compact('record'));
    }

    public function postmembershipapplicationpage(Request $req){
        try {
            return DB::transaction(function() use($req){
                $input = $req->all();
                $rules = [
                    "category"=>"required",
                    "companyname_c"=>"required_if:category, corporate",
                    "contactperson_c"=>"required_if:category, corporate",
                    "address1_c"=>"required_if:category, corporate",
                    "phoneno_c"=>"required_if:category, corporate",
                    "mobileno_c"=>"required_if:category, corporate",
                    "emailid_c"=>"required_if:category, corporate",
                    "fb_c"=>"required_if:category, corporate",
                    "twi_c"=>"required_if:category, corporate",
                    "ln_c"=>"required_if:category, corporate",
                    "companyname_i" => "required_if:category, individual",
                    "contactperson_i" => "required_if:category, student|required_if:category, individual",
                    "address1_i" => "required_if:category, student|required_if:category, individual",
                    "phoneno_i" => "required_if:category, student|required_if:category, individual",
                    "mobileno_i" => "required_if:category, student|required_if:category, individual",
                    "emailid_i" => "required_if:category, student|required_if:category, individual",
                    "fb_i" => "required_if:category, student|required_if:category, individual",
                    "twi_i" => "required_if:category, student|required_if:category, individual",
                    "ln_i" => "required_if:category, student|required_if:category, individual",
                ];

                $messages = [
                    "required"=>"You can't leave this field empty",
                    "required_if"=>"You can't leave this field empty",
                    "image"=>"Please upload image file only",
                    "date"=>"Please enter a valid date",
                ];

                $validation = Validator::make($input, $rules, $messages);
                if($validation->fails()){
                    return redirect()->back()->withInput()->withErrors($validation);
                }

                if($input["category"] == "corporate"){
                    $endDate = date("Y-m-d", strtotime("+365 Day"));
                    $time = date("H:i:s");
                    $parsed = date_parse($time);
                    $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
                    $members = [];
                    $tot_member = 0;
                    for($i = 0; $i < $input['tot_mem']; $i++){
                        $members[$i]['name'] = trim($input['name'.$i]); 
                        $members[$i]['designation'] = trim($input['designation'.$i]);
                        $members[$i]['email'] = trim($input['email'.$i]);
                        $members[$i]['mobile'] = trim($input['mobile'.$i]);
                        $tot_member++;
                    }
                    $members = json_encode($members);

                    if($input['tot_mem'] > 5){
                        $payable = Option::getvalue('corporate') + (600 * ($input['tot_mem'] - 5));
                    }else{
                        $payable = Option::getvalue('corporate');
                    }
                    $GST = Option::getvalue('GST');
                    $amount = $payable / 100;
                    $pay = ceil($payable + ($amount * $GST));
                    $status = "inactive";

                    // $check = Members::where('email', $input['emailid_c'])->where('status', 'active')->count();
                    // if($check > 0){
                    //     return redirect()->back()->withInput()->with('warnings', 'Registered email-id already exist!!!');
                    // }

                    $insert = new Members();
                    $insert->mem_category = $input["category"];
                    $insert->org_name = $input["companyname_c"];
                    $insert->con_person = $input["contactperson_c"];
                    $insert->address = $input["address1_c"];
                    $insert->phone = $input["phoneno_c"];
                    $insert->mobile = $input["mobileno_c"];
                    $insert->email = $input["emailid_c"];
                    $insert->facebook = $input["fb_c"];
                    $insert->twitter = $input["twi_c"];
                    $insert->linkedin = $input["ln_c"];
                    $insert->members = $members;
                    $insert->date_registered = date('Y-m-d H:i:s');
                    $insert->status = 'inactive';
                    $insert->price = $pay;
                    $insert->total_mem = $tot_member;
                    $insert->expiryDate = $endDate;
                    $insert->timing = $seconds;
                    $insert->createdBy = Auth::User()->id;
                    $insert->save();

                    $uniqueID = "ACM".date('Ymd').str_pad($insert->id, 3, '0', STR_PAD_LEFT);
                    $update = Members::find($insert->id);
                    $update->unique_id = $uniqueID;
                    $update->save();

                    $basicInfo = $this->membersapplicationpaymentpost(Crypt::encrypt($insert->id));
                    return view('frontend.membership-application', compact('basicInfo'));
                }elseif($input["category"] == "individual"){
                    // $check = Members::where('email', $input['emailid_i'])->where('status', 'active')->count();
                    // if($check > 0){
                    //     return back()->withInput()->with('warnings', 'Registered email-id already exist!!!');
                    // }
                    $status = "inactive";
                    $individual = Option::getvalue('individual');
                    $GST = Option::getvalue('GST');
                    $amount = $individual / 100;
                    $pay = ceil($individual + ($amount * $GST));
                    $endDate = date("Y-m-d", strtotime("+365 Day"));
                    $time = date("H:i:s");
                    $parsed = date_parse($time);
                    $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

                    $insert = new Members();
                    $insert->mem_category = $input["category"];
                    $insert->org_name = $input["companyname_i"];
                    $insert->con_person = $input["contactperson_i"];
                    $insert->address = $input["address1_i"];
                    $insert->phone = $input["phoneno_i"];
                    $insert->mobile = $input["mobileno_i"];
                    $insert->email = $input["emailid_i"];
                    $insert->facebook = $input["fb_i"];
                    $insert->twitter = $input["twi_i"];
                    $insert->linkedin = $input["ln_i"];
                    $insert->date_registered = date('Y-m-d H:i:s');
                    $insert->status = 'inactive';
                    $insert->price = $pay;
                    $insert->expiryDate = $endDate;
                    $insert->timing = $seconds;
                    $insert->createdBy = Auth::User()->id;
                    $insert->save();

                    $uniqueID = "ACM".date('Ymd').str_pad($insert->id, 3, '0', STR_PAD_LEFT);
                    $update = Members::find($insert->id);
                    $update->unique_id = $uniqueID;
                    $update->save();

                    $basicInfo = $this->membersapplicationpaymentpost(Crypt::encrypt($insert->id));
                    return view('frontend.membership-application', compact('basicInfo'));
                }else if($input["category"] == "student"){
                    // $check = Members::where('email', $input['emailid_i'])->where('status', 'active')->count();
                    // if($check > 0){
                    //     return redirect()->back()->withInput()->with('warnings', 'Registered email-id already exist!!!');
                    // }
                    $status = "inactive";
                    $student = Option::getvalue('student');
                    $GST = Option::getvalue('GST');
                    $amount_stu = $student / 100;
                    $pay = ceil($student + ($amount_stu * $GST));
                    $endDate = date("Y-m-d", strtotime("+365 Day"));
                    $time = date("H:i:s");
                    $parsed = date_parse($time);
                    $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

                    $insert = new Members();
                    $insert->mem_category = $input["category"];
                    $insert->org_name = $input["companyname_i"];
                    $insert->con_person = $input["contactperson_i"];
                    $insert->address = $input["address1_i"];
                    $insert->phone = $input["phoneno_i"];
                    $insert->mobile = $input["mobileno_i"];
                    $insert->email = $input["emailid_i"];
                    $insert->facebook = $input["fb_i"];
                    $insert->twitter = $input["twi_i"];
                    $insert->linkedin = $input["ln_i"];
                    $insert->date_registered = date('Y-m-d H:i:s');
                    $insert->status = 'inactive';
                    $insert->price = $pay;
                    $insert->expiryDate = $endDate;
                    $insert->timing = $seconds;
                    $insert->createdBy = Auth::User()->id;
                    $insert->save();

                    $uniqueID = "ACM".date('Ymd').str_pad($insert->id, 3, '0', STR_PAD_LEFT);
                    $update = Members::find($insert->id);
                    $update->unique_id = $uniqueID;
                    $update->save();

                    $basicInfo = $this->membersapplicationpaymentpost(Crypt::encrypt($insert->id));
                    return view('frontend.membership-application', compact('basicInfo'));
                }
            });
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            return redirect()->back()->with("error", "Something went wrong");
        }
    }




    public function membersapplicationpaymentpost($key){
        try {
            return DB::transaction(function() use($key){
                $id = Crypt::decrypt($key);
                $info = Members::find($id);
                $reqID = $info->unique_id;
                $price = $info->price;
                $tID = time();
                $billing_email = $info->email;
                $billing_name = $info->con_person;
                $billing_address = $info->address;
                $billing_tel = $info->mobile;
                

                $payu_url = '';
                $payu_merchant_key = '';
                $payu_salt = '';

                if(env('PAYMENT_MODE') == 'test'){
                    $payu_url = env('PAYMENT_TEST_URL');
                    $payu_merchant_key = env('PAYMENT_TEST_MERCHANT_KEY');
                    $payu_salt = env('PAYMENT_TEST_SALT');
                }else if(env('PAYMENT_MODE') == 'live'){
                    $payu_url = env('PAYMENT_LIVE_URL');
                    $payu_merchant_key = env('PAYMENT_LIVE_MERCHANT_KEY');
                    $payu_salt = env('PAYMENT_LIVE_SALT');
                }

                 $basicInfo = [
                    'merchant_key' => $payu_merchant_key,
                    'salt' => $payu_salt,
                    'payu_base_url' => $payu_url, //https://secure.payu.in/_payment
                    'txn_id' => $reqID,
                    'amount' => number_format($price, 2, '.', ''),
                    'productinfo' => 'Members Registration',
                    'firstname' => $billing_name,
                    'email' => $billing_email,
                    'phone' => $billing_tel,
                    'udf1' => 'Members Registration',
                    'udf2' => $key,
                    'udf3' => "",
                    'udf4' => "",
                    'udf5' => "",
                    'udf6' => "",
                    'udf7' => "",
                    'udf8' => "",
                    'udf9' => "",
                    'udf10' => "",
                    'surl' => route('payment.success'),//route('payment.success'),
                    'furl' => route('payment.failure'), //route('payment.failure')
                ];
                $hashSequence = "merchant_key|txn_id|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
                $hashVarsSeq = explode('|', $hashSequence);
                $hash_string = '';
                foreach($hashVarsSeq as $hash_var) {
                    $hash_string .= isset($basicInfo[$hash_var]) ? $basicInfo[$hash_var] : '';
                    $hash_string .= '|';
                }                
                $hash_string = $hash_string.$basicInfo['salt'];
                $hash = strtolower(hash('sha512', $hash_string));
                $basicInfo['hash_string'] = $hash;
                $type = 'online';
                return $basicInfo;
                $template = view('frontend.payment-form-template')->with('basicInfo', $basicInfo)->render();
                return view('frontend.payment-form-template', compact('basicInfo', 'type'));
                return response()->json(['status'=>'success','template'=>$template,'type'=>'online']);
            });/* end of db transaction */
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            //return redirect()->back()->with("error", "Something went wrong");
            return response()->json(['status'=>'error','msg'=>'Error. Please try again']);
        }
    }

    public function getmembersapplicationpaymentconfirmationpage($key){
        try {
            $id = Crypt::decrypt($key);
            $info = Members::find($id);
            if($info){
                if($info->emailStatus == "no"){
                    Mail::send("emails/membersRegistration", ["uniqueID"=>$info->unique_id], function($message) use($info){
                        $message->from(Option::getvalue('senderEmail'), Option::getvalue('senderName'));
                        $message->to($info->email, $info->con_person);
                        $notificationEmail = Option::getvalue("emailNotification");
                        if($notificationEmail != ''){
                            $message->bcc($notificationEmail, "AdClubMadras");
                        }
                        $message->subject("New Membership Registration!!!");
                    });
                    $info->emailStatus = "yes";
                    $info->save();


                    $mobileNumber = '91'.$info->mobile;
                    $apiKey = urlencode('OBrkzlECvHw-MfbwgdmGMaXzfy2GBhNB5Jm3VMdR9J');
                    $numbers = array($mobileNumber);
                    $sender = urlencode('ADCLUB');
                    $message = rawurlencode('Your Membership Registration done successfully. ID '.$info->unique_id.'. Thank you for registering at Ad Club Madras');
                    $numbers = implode(',', $numbers);
                    $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
                    $ch = curl_init('https://api.textlocal.in/send/');
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    $response = curl_exec($ch);
                    curl_close($ch);
                    $response = json_decode($response);
                    $status = $response->status;
                    if($status == 'failure'){
                        $message = $response->errors[0]->message;
                    }
                }
                return view("frontend/membership-registration-confirmation")->with(["info"=>$info]);
            }
            return "Something went wrong, Please contact system Admin";
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function getmembersrenewalapplicationpaymentconfirmationpage($key){
        try {
            $id = Crypt::decrypt($key);
            $info = Members::find($id);
            if($info){
                if($info->emailStatus == "no"){
                   try{
                    // Mail::send("emails/membersRegistration", ["uniqueID"=>$info->unique_id], function($message) use($info){
                    //     $message->from(Option::getvalue('senderEmail'), Option::getvalue('senderName'));
                    //     $message->to($info->email, $info->con_person);
                    //     $notificationEmail = Option::getvalue("emailNotification");
                    //     if($notificationEmail != ''){
                    //         $message->bcc($notificationEmail, "AdClubMadras");
                    //     }
                    //     $message->subject("Membership Renewal");
                    // });
                   }catch(\Exception $s){}

                    $info->emailStatus = "yes";
                    $info->save();

                    $mobileNumber = '91'.$info->mobile;
                    $apiKey = urlencode('OBrkzlECvHw-MfbwgdmGMaXzfy2GBhNB5Jm3VMdR9J');
                    $numbers = array($mobileNumber);
                    $sender = urlencode('ADCLUB');
                    $message = rawurlencode('Your Membership Renewal done successfully. ID '.$info->unique_id.'. Thank you for registering at Ad Club Madras');
                    $numbers = implode(',', $numbers);
                    $data = array('apikey' => $apiKey, 'numbers' => $numbers, "sender" => $sender, "message" => $message);
                    try{
                        // $ch = curl_init('https://api.textlocal.in/send/');
                        // curl_setopt($ch, CURLOPT_POST, true);
                        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        // $response = curl_exec($ch);
                        // curl_close($ch);
                        // $response = json_decode($response);
                        // $status = $response->status;
                        // if($status == 'failure'){
                        //     $message = $response->errors[0]->message;
                        // }
                    }catch(\Exception $s){}
                }
                return view("frontend/membership-renewal-confirmation")->with(["info"=>$info]);
            }
            return "Something went wrong, Please contact system Admin";
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function contactpageget(){
        return view("frontend/contact");
    }

    public function contactpost(Request $req){
        try{
            $input = $req->all();
            $rules = [
                "name" => "required",
                "company_name" => "required",
                "email"=>"required|email",
                "contact_number"=>"required|numeric|digits:10",
                "comments"=>"required",
                'g-recaptcha-response' => 'required|recaptchav3:register,0.5'
            ];
            $messages = [
                "required"=>"You can't leave this field empty",
            ];
            $validation = Validator::make($input, $rules, $messages);
            if($validation->fails()){
                return redirect()->back()->withInput()->withErrors($validation);
            }
            //Admin Email
             $notificationEmail = Option::getvalue("emailNotification");
            if($notificationEmail){
                Mail::send("emails/contactForm", ["input"=>$input], function($message) use($input, $notificationEmail){
                    $message->from(Option::getvalue('senderEmail') , Option::getvalue('senderName'));
                    $message->to("sarathinnce@gmail.com", "AdClubMadras");//$notificationEmail
                    $message->subject("Contact us Details");
                });
            }
            return redirect()->back()->with('success', 'Contact us details submitted successfully.');
        }catch(\Exception $e){
            return back()->with('error', $e->getMessage()."_".$e->getLine());
        }
    }

    public function jobopportunitiespageget() {
        return view('frontend/job-opportunities');
    }

    public function jobopportunitiessave(Request $req){
        try{
            $input = $req->all();
            $rules = [
                "email"=>"required|email",
                "job_title"=>"required",
                "description"=>"required",
                "application_email"=>"required",
                "company_name"=>"required",
                "logo"=>"nullable|image|mimes:jpg,png,jpeg,gif",
                "website"=>"nullable|url",
            ];
            $messages = [
                "required"=>"You can't leave this field empty",
            ];
            $validation = Validator::make($input, $rules, $messages);
            if($validation->fails()){
                return redirect()->back()->withInput()->withErrors($validation);
            }
            $logo = NULL;
            if($req->hasFile('logo')){
                $file = $req->file('logo');
                $destinationPath = 'frontend/uploads/'; // upload path
                $extension = $file->getClientOriginalExtension(); // getting file extension
                $fileName = rand(11111, 99999) . '.' . $extension; // renameing image
                $upload_success = $file->move($destinationPath, $fileName); // uploading file to given path
                $logo = $destinationPath.$fileName;
            }
            $insert = new Jobopportunities();
            $insert->email = $input['email'];
            $insert->job_title = $input['job_title'];
            $insert->location = $input['location'];
            $insert->job_type = $input['job_type'];
            $insert->description = $input['description'];
            $insert->application_email = $input['application_email'];
            $insert->company_name = $input['company_name'];
            $insert->website = $input['website'];
            $insert->tagline = $input['tagline'];
            $insert->video = $input['video'];
            $insert->twitter_username = $input['twitter_username'];
            $insert->logo = $logo;
            if(Auth::check()){
                $insert->user_id = Auth::id();
            }
            $insert->save();
            //Admin Email
             $notificationEmail = '';//Option::getvalue("emailNotification");
            // if($notificationEmail){
                Mail::send("emails/jobOpportunities-admin", ["insert"=>$insert], function($message) use($insert, $notificationEmail){
                    $message->from(Option::getvalue('senderEmail') , Option::getvalue('senderName'));
                    $message->to("sarathinnce@gmail.com", "AdClubMadras");//$notificationEmail
                    $message->subject("New Job Opportunities");
                });
           //}

            //Customer Email
            Mail::send("emails/jobOpportunities-customer", ["insert"=>$insert], function($message) use($insert, $notificationEmail){
                $message->from(Option::getvalue('senderEmail') , Option::getvalue('senderName'));
                $message->to($insert->email, $insert->company_name);
                $message->subject("New Job Opportunities");
            });
            return redirect()->back()->with('success', 'Job opportunities details submitted successfully.');
        }catch(\Exception $e){
            return back()->with('error', $e->getMessage()."_".$e->getLine());
        }
        
    }

    public function gallerypageget(){
        return view("frontend/gallery");
    }

    public function newspageget(){
        return view("frontend/news");
    }

    public function newscategorypageget($categorySlug){
        if($categorySlug == 'upcoming'){
            $news = News::where("status", "active")->where("newsDate", ">=", date('Y-m-d'))->orderBy("newsDate", "DESC")->get();
            return view("frontend/newsCategory")->with(["news"=>$news, "slug"=>'upcoming']);
        }else{

            $categoryCheck = newsCategories::where('categorySlug', $categorySlug)->where('status', 'active')->first();
            if($categoryCheck){
                $categoriesIds = NewsMeta::where('categoryID', $categoryCheck->id)->pluck('newsID')->toArray();
                $cat = NewsCategories::findOrFail($categoryCheck->id);
                $news = News::where("status", "active")->whereIn("id", $categoriesIds)->orderBy("newsDate", "DESC")->get();
                return view("frontend/newsCategory")->with(["news"=>$news, "cat"=>$cat, 'slug' => $categorySlug]);
            }
        }
        return redirect('/events');
        
    }

    public function eventspageget(){
        return view("frontend/events");
    }

    public function eventscategorypageget($categorySlug){
        if($categorySlug == 'upcoming'){
            $events = Events::where("status", "active")->where("eventDate", ">=", date('Y-m-d'))->orderBy("eventDate", "DESC")->get();
            return view("frontend/eventsCategory")->with(["events"=>$events, "slug"=>'upcoming']);
        }elseif($categorySlug == 'upcoming-partner'){
            $events = Events::where("status", "active")->where("eventDate", ">=", date('Y-m-d'))->orderBy("eventDate", "DESC")->where('partner_event', 'yes')->get();
            return view("frontend/eventsCategory")->with(["events"=>$events, "slug"=>'upcoming-partner']);
        }else{
            $categoryCheck = EventCategories::where('categorySlug', $categorySlug)->where('status', 'active')->first();
            if($categoryCheck){
                $event = EventCategories::findOrFail($categoryCheck->id);
                $events = Events::where("status", "active")->where("eventCategoryID", $categoryCheck->id)->orderBy("eventDate", "DESC")->get();
                return view("frontend/eventsCategory")->with(["events"=>$events, "event"=>$event, 'slug' => $categorySlug]);
            }
        }
        return redirect('/events');
        
    }

    public function eventdetailspageget($categorySlug, $eventSlug){
        $categoryCheck = EventCategories::where('categorySlug', $categorySlug)->where('status', 'active')->first();
        if($categoryCheck){
            $eventCheck = Events::where('eventCategoryID', $categoryCheck->id)->where('status', 'active')->where('eventSlug', $eventSlug)->first();
            if($eventCheck){
                $event = Events::findOrFail($eventCheck->id);
                $custom_fields_reg = Customfield::Event($event->id)->NotDeleted()->ModuleName('event_reg')->get();
                $custom_info =  Customfield::Event($event->id)->NotDeleted()->ModuleName('event_info')->get();
                return view("frontend/event-details")->with(["event"=>$event,'custom_fields_reg'=>$custom_fields_reg, 'custom_info' => $custom_info]);
            }
        }
        return redirect('/events');
    }

    public function gallerycategorypageget($categorySlug){
        $categoryCheck = GalleryCategories::where('categorySlug', $categorySlug)->where('status', 'active')->first();
        if($categorySlug){
            $album = GalleryCategories::findOrFail($categoryCheck->id);
            $albums = Gallery::where("status", "active")->where("galleryCategoryID", $categoryCheck->id)->orderBy("galleryDate", "DESC")->get();
            return view("frontend/galleryCategories")->with(["albums"=>$albums, "id"=>$categoryCheck->id, "album"=>$album]);
        }
        return redirect('/gallery');
    }

    public function gallerydetailspage($categorySlug, $gallerySlug){
        $categoryCheck = GalleryCategories::where('categorySlug', $categorySlug)->where('status', 'active')->first();
        if($categoryCheck){
            $galleryCheck = Gallery::where('galleryCategoryID', $categoryCheck->id)->where('status', 'active')->where('gallerySlug', $gallerySlug)->first();
            if($galleryCheck){
                $album = Gallery::findOrFail($galleryCheck->id);
                $totalCount = Upload::where("type", "gallery")->where("productid", $album->id)->count();
                $photos = Upload::where("type", "gallery")->where("productid", $album->id)->paginate(20);
                return view("frontend/gallery-details")->with(["photos"=>$photos, "album"=>$album, 'totalCount' => $totalCount]);
            }
        }
        return redirect('/gallery');
    }

    //Login
    public function loginsignuppageget(){
        $intended = URL::previous();
        return view("frontend/login")->with(["intended"=>$intended]);
    }

    public function loginpagepost(Request $req){
        try {
            $input = $req->all();
            $rules = [
                "userEmail"=>"required|email",
                "userPassword"=>"required"
            ];
            $message = ['userEmail.required' => 'The email address field is required', 'userPassword.required' => 'The password field is required'];
            $validation = Validator::make($input, $rules, $message);
            if($validation->fails()){
                return back()->withErrors($validation)->withInput();
            }
            if (Auth::attempt(array('email' => $input['userEmail'], 'password' => $input['userPassword'], 'status' => 'active', 'userGroup' => 0))){
                $update = User::find(Auth::User()->id);
                $update->lastLogin = date('Y-m-d H:i:s');
                $update->save();
                if(Session::has('redirectUrl')){
                    $url = Session::get('redirectUrl');
                    Session::forget('redirectUrl');
                    return redirect($url);
                }
                return redirect()->intended('/');
            }
            return back()->with('loginErrorMessage', 'Credential wrong. Please try again with correct one.');
        } catch (Exception $e) {
            //$con = Auth::user()->userName.' has logged out at '.date("H:i:s");
            //TrackingReport::track('logout',$con,'','','admin logout');
        }
    }

    public function getlogoutpage(){
        //$con = Auth::user()->userName.' has logged out at '.date("H:i:s");
        //TrackingReport::track('logout',$con,'','','admin logout');
        Auth::logout();
        Session::flush();
        return redirect('/')->withSuccess('You are successfully logged out!!!');
    }

    public function privacypolicypageget(){
        return view("frontend/privacy-policy");
    }

    public function termsconditionspageget(){
        return view("frontend/terms-conditions");
    }

    public function returnpolicypageget(){
        return view("frontend/refund-cancellation");
    }

    //Demo Emails
    public function demoemails(){
        return view("emails/courseApplied");
    }

    //Sign-Up Form
    public function isUniqueValue(Request $req){
        try {
            return DB::transaction(function() use($req){
                return $input = $req->all();
                
                return Response::json(['status'=>'success']);
            });/* end of db transaction */
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage()."-".$e->getLine(), "", "", "Course Application");
            return Response::json(['status'=>'failure']);
        }
    }

    public function postsignupform(Request $req){
        try {
            return DB::transaction(function() use($req){
                $input = $req->all();
                $rules = ['signUpEmail'=>'required|unique:users,email','signUpFullName'=>'required', 'signUpPassword'=>'required|confirmed', 'signUpPassword_confirmation'=>'required|min:6'];
                $validation = Validator::make($input, $rules);
                if($validation->fails()){
                    return back()->with('signupError','')->withErrors($validation)->withInput();
                }
                $insert = new User();
                $insert->firstName = $input["signUpFullName"];
                $insert->email = $input["signUpEmail"];
                $insert->password = Hash::make($input["signUpPassword"]);
                $insert->status = "active";
                if($insert->save()){
                    Mail::send("emails/onlineUser", ["userName"=>$input["signUpFullName"]], function($message) use ($input){
                        $message->from(Option::getvalue("senderEmail"), Option::getvalue("senderName"));
                        $message->to($input['signUpEmail'], $input['signUpFullName'])
                        ->subject('Online User Registration!!!');
                    });
                }
                Auth::login($insert);
                return back()->with('signupError','')->with('signupSuccess', 'Your account has been created successfully');
            });/* end of db transaction */
        } catch (Exception $e) {
            return back()->with('signupError', 'Your account not created. Please try again');
        }
    }

    //Forgot Password
    public function postforgotpasswordform(Request $req){
        try {
            return DB::transaction(function() use($req){
                $input = $req->all();
                $rules = ['forgotEmail' => 'required|email'];
                $message = ['forgotEmail.required'=>'The forgot password field is required'];
                $validation = Validator::make($input, $rules, $message);
                if($validation->fails()){
                    return back()->withErrors($validation)->withInput()->with('forgotError', '');
                }
                $check = DB::table("users")->where("email", $input["forgotEmail"])->where("userGroup", 0)->where("status", "active")->first();
                if(!$check){
                    return back()->with('forgotError', 'Your email id is wrong. Please enter correct one.');
                }
                
                $code = Str::random(60);
                $update = DB::table('users')->where('email', $input['forgotEmail'])->update(['code'=>$code]);
                  
                Mail::send('emails/forgotPassword',array('userName'=>$check->firstName, 'code'=>$code, 'time'=>time()), function($message) use ($check) {
                    $message->from(Option::getvalue('senderEmail') ,Option::getvalue('senderName'));
                    $message->to($check->email, $check->firstName)->subject('Reset your Password');
                });
                return back()->with('forgotError', '')->with('forgotSuccess', 'Reset password link send to your email');
            });
        } catch (Exception $e) {
            return back()->with('forgotError', 'Your email id is wrong. Please enter correct one.');
        }
    }

    public function getforgetpasswordpage($code, $time){
        try {
            $time = Crypt::decrypt($time);
            $code = Crypt::decrypt($code);
            $timeDiff = strtotime('+12 hours', $time);
            if(time() <= $timeDiff){
                $check = DB::table('users')->where('code', $code)->first();
                if($check){
                    return view('frontend/forgotPassword')->with(['code'=>$code, 'time'=>$time, 'user'=>$check]);
                }
                return 'You are not an authorized user, You can not reset your password right now, Please try again';
            }
            return 'You are not an authorized user, You can not reset your password right now, Please try again';
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage()."-".$e->getLine(), "", "", "Course Application");
            return redirect()->back()->with('error', 'Error processing your request');
        }
    }

    public function postforgetpasswordpage(Request $req, $code, $time){
        try {
            return DB::transaction(function() use($req, $code, $time){
                $input = $req->all();
                $rules = [
                    'password'=>'required|min:6|confirmed',
                    'password_confirmation'=>'required'
                ];
                $validation = Validator::make($input, $rules);
                if($validation->fails()){
                    return redirect()->back()->withErrors($validation);
                }

                $time = Crypt::decrypt($time);
                $code = Crypt::decrypt($code);
                $timeDiff = strtotime('+12 hours', $time);
                if(time() <= $timeDiff){
                    $user = User::where('code', $code)->where('status', 'active')->first();
                    if($user){
                        $user->password = Hash::make($input['password']);
                        if($user->save()){
                            return redirect()->back()->with('success', 'Now you can login with your new password.');
                        }
                    }
                }
                return Redirect::back()->with('error','Please resubmit forgot password request');
            });/* end of db transaction */
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage()."-".$e->getLine(), "", "", "Course Application");
            return redirect()->back()->with('error', 'Error processing your request');
        }
    }

    //Individual Members
    public function individualmemberspageget(){
        return view("frontend/individual-members");
    }

    public function individualmemberspagepost(Request $req){
        try {
            $input = $req->all();
            if($input['currentAlphabet'] == 'All'){
                $members = Members::where("mem_category", "!=", "corporate")->where("status", "active")->where('sortBy', '!=','')->orderBy("sortBy")->get();
            }else{
                $members = Members::where("mem_category", "!=", "corporate")->where("status", "active")->where("sortBy", $input["currentAlphabet"])->get();
            }
            return $members;
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage()."-".$e->getLine(), "", "", "Course Application");
            return Response::json($e->getMessage());
        }
    }

    //Corporate Members
    public function corporatememberspageget(){
        return view("frontend/corporate-members");
    }

    public function corporatememberspagepost(Request $req){
        try {
            $input = $req->all();
            if($input['currentAlphabet'] == 'All'){
                $records = Members::where("mem_category", "=", "corporate")->where("status", "active")->where("sortBy", '!=', '')->orderBy('sortBy', 'asc')->get();
            }else{
                $records = Members::where("mem_category", "=", "corporate")->where("status", "active")->where("sortBy", $input["currentAlphabet"])->get();
            }
            
            $members = [];
            if(count($records) > 0){
                $i = 0;
                foreach($records as $record){
                    $nominees = [];
                    $members[$i]["org_name"] = $record->org_name;
                    $members[$i]["address"] = $record->address;
                    $members[$i]["phone"] = $record->phone." ".$record->mobile;
                    $members[$i]["email"] = $record->email;
                    $members[$i]["facebook"] = $record->facebook;
                    $members[$i]["twitter"] = $record->twitter;
                    $members[$i]["linkedin"] = $record->linkedin;

                    $ones = json_decode($record->members);
                    $addition = [];
                    foreach($ones as $one){
                        if($one->name != ""){
                            array_push($addition, $one->name);
                        }
                    }
                    $members[$i]["nominees"] = $addition;
                    $i++;
                }
            }
            return $members;
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage()."-".$e->getLine(), "", "", "Course Application");
            return Response::json($e->getMessage());
        }
    }

    //Profile
    public function profilepageget(){
        return view("frontend/profile");
    }

    public function profilepagepost(Request $req){
        try {
            $input = $req->all() ;
            $rules = [
                "fullName"=>"required",
                "contactNO"=>"required",
            ];
            $validation = Validator::make($input, $rules);
            if($validation->fails()){
                return redirect()->back()->withInput()->withErrors($validation);
            }
            $update = User::findOrFail(Auth::User()->id);
            $update->firstName = $input["fullName"];
            $update->phone = $input["contactNO"];
            $update->save();
            return redirect()->back()->withSuccess("User details updated successfully!!!");
        } catch (Exception $e) {
            
        }
    }

    public function postchangepassword(Request $req){
        try{
            $input = $req->all();
            $rules = array(
                "oldPassword"=>"required",
                "newPassword"=>"required",
                "confirmPassword"=>"required|same:newPassword"
            );

            $message = array(
                "required"=>"You can't leave this field empty",
            );

            $validation = Validator::make($input, $rules, $message);
            if($validation->fails()){
                return redirect()->back()->withErrors($validation)->withInput();
            }

            $currentPassword1 = Auth::user()->password;
            $currentPassword2 = $input["oldPassword"];
            if(Hash::check($currentPassword2, $currentPassword1)){
                $change = User::find(Auth::user()->id);
                $change->password = Hash::make($input["newPassword"]);
                $change->save();
                return redirect()->back()->with("success", "Password changed successfully!!");
            }
            return redirect()->back()->with("error", "Please enter valid details");
        } catch(Exception $e){
          
        }
    }

    public function getprofilemembershippage(){
        return view("frontend/membership-details");
    }

    public function postcheckrenewalstatus(Request $req){
        try {
            $input = $req->all();
            $uniqueID = Crypt::decrypt($input["uniqueID"]);
            $check = Members::where("unique_id", $uniqueID)->first();
            if($check){
                $nextRenewalDt = date("Y-m-d", strtotime("-7 days", strtotime(date("Y-m-d", strtotime($check->expiryDate)))));
                // if(date("Y-m-d") >= $nextRenewalDt){
                //     return Response::json(["status"=>"renewal", "url"=>"/profile/membership/renewal/form/".$input["uniqueID"]]);
                // } elseif(date("Y-m-d", strtotime($check->expiryDate)) <= date("Y-m-d")){
                    return Response::json(["status"=>"renewal", "url"=>"/profile/membership/renewal/form/".$input["uniqueID"]]);
                // } else{
                //     $nextRenewalDt = date("Y-m-d", strtotime("-7 days", strtotime(date("Y-m-d", strtotime($check->expiryDate)))));
                //     return Response::json(["status"=>"time", "msg"=>"You have time to renewal membership until ".$nextRenewalDt]);
                // }
            } else{
                return "Not Found";
            }
        } catch (Exception $e) {
            
        }
        
    }

    public function getmembershiprenewalpage($key){
        try {
            $uniqueID = Crypt::decrypt($key);
            $check = Members::where("unique_id", $uniqueID)->first();
            if($check){
                $nextRenewalDt = date("Y-m-d", strtotime("-7 days", strtotime(date("Y-m-d", strtotime($check->expiryDate)))));
                // if(date("Y-m-d") >= $nextRenewalDt){
                //     return view("frontend/membership-renewal-application")->with(["member"=>$check]);
                // } elseif(date("Y-m-d", strtotime($check->expiryDate)) <= date("Y-m-d")){
                    return view("frontend/membership-renewal-application")->with(["member"=>$check]);
                // } else{
                //     $nextRenewalDt = date("Y-m-d", strtotime("-7 days", strtotime(date("Y-m-d", strtotime($check->expiryDate)))));
                //     dd("You have time to renewal membership until ".$nextRenewalDt);
                // }
            } else{
                return "Membership Details Not Found";
            }
        } catch (Exception $e) {
            
        }
    }

    public function postmembershiprenewalpage(Request $req){
        try {
            return DB::transaction(function() use($req){
                $input = $req->all();
                $uniqueID = Crypt::decrypt($req->hiddenId);
                $rules = [
                    "category"=>"required",
                    "companyname_c"=>"required_if:category, corporate",
                    "contactperson_c"=>"required_if:category, corporate",
                    "address1_c"=>"required_if:category, corporate",
                    "phoneno_c"=>"required_if:category, corporate",
                    "mobileno_c"=>"required_if:category, corporate",
                    "emailid_c"=>"required_if:category, corporate|email",
                    "fb_c"=>"required_if:category, corporate",
                    "twi_c"=>"required_if:category, corporate",
                    "ln_c"=>"required_if:category, corporate",
                    "companyname_i" => "required_if:category, individual",
                    "contactperson_i" => "required_if:category, student|required_if:category, individual",
                    "address1_i" => "required_if:category, student|required_if:category, individual",
                    "phoneno_i" => "required_if:category, student|required_if:category, individual",
                    "mobileno_i" => "required_if:category, student|required_if:category, individual",
                    "emailid_i" => "required_if:category, student|required_if:category, individual",
                    "fb_i" => "required_if:category, student|required_if:category, individual",
                    "twi_i" => "required_if:category, student|required_if:category, individual",
                    "ln_i" => "required_if:category, student|required_if:category, individual",
                ];

                $messages = [
                    "required"=>"You can't leave this field empty",
                    "required_if"=>"You can't leave this field empty",
                    "image"=>"Please upload image file only",
                    "date"=>"Please enter a valid date",
                ];

                $validation = Validator::make($input, $rules, $messages);
                if($validation->fails()){
                    return response()->json(['status'=>'validation', 'validation'=>$validation->messages()]);
                }

                if($input["category"] == "corporate"){
                     $member = Members::where("unique_id", $uniqueID)->first();
                    if($member){
                        $renewal = $member->renewal + 1;

                        if(date("Y-m-d", strtotime($member->expiryDate)) > date("Y-m-d")){
                            $datetime1 = new DateTime(date("Y-m-d", strtotime($member->expiryDate)));
                            $datetime2 = new DateTime(date("Y-m-d"));
                            $difference = $datetime1->diff($datetime2);
                            $totalDays = $difference->days + 365;
                            $endDate = date("Y-m-d", strtotime("+".$totalDays." Day"));
                        } else{
                            $endDate = date("Y-m-d", strtotime("+365 Day"));
                        }

                        $time = date("H:i:s");
                        $parsed = date_parse($time);
                        $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
                        $members = [];
                        $tot_member = 0;
                        for($i = 0; $i < $input['tot_mem']; $i++){
                            $members[$i]['name'] = trim($input['name'.$i]); 
                            $members[$i]['designation'] = trim($input['designation'.$i]);
                            $members[$i]['email'] = trim($input['email'.$i]);
                            $members[$i]['mobile'] = trim($input['mobile'.$i]); 
                            $tot_member++;
                        }
                        $members = json_encode($members);

                        if($input['tot_mem'] > 5){
                            $payable = Option::getvalue('corporate') + (600 * ($input['tot_mem'] - 5));
                        }else{
                            $payable = Option::getvalue('corporate');
                        }

                        $GST = Option::getvalue('GST');
                        $amount = $payable / 100;
                        $pay = ceil($payable + ($amount * $GST));
                        $status = "inactive";

                        $check = Members::where('email', $input['emailid_c'])->count();
                        if($check > 1){
                            //return redirect()->back()->with('warnings', 'Registered email-id already exist!!!');
                            return response()->json(['status'=>'error','msg'=>'Registered email-id already exist!!!']);
                        }

                        $insert = Members::find($member->id);
                        $insert->mem_category = $input["category"];
                        $insert->org_name = $input["companyname_c"];
                        $insert->con_person = $input["contactperson_c"];
                        $insert->address = $input["address1_c"];
                        $insert->phone = $input["phoneno_c"];
                        $insert->mobile = $input["mobileno_c"];
                        $insert->email = $input["emailid_c"];
                        $insert->facebook = $input["fb_c"];
                        $insert->twitter = $input["twi_c"];
                        $insert->linkedin = $input["ln_c"];
                        $insert->members = $members;
                        $insert->date_renewed = date("Y-m-d H:i:s");
                        $insert->status = "inactive";
                        $insert->price = $pay;
                        $insert->total_mem = $tot_member;
                        $insert->expiryDate = $endDate;
                        $insert->timing = $seconds;
                        $insert->emailStatus = "no";
                        $insert->updatedBy = Auth::User()->id;
                        $insert->save();

                        $meta = new MembersMeta();
                        $meta->userID = $member->unique_id;
                        $meta->createdOn = date("Y-m-d H:i:s");
                        $meta->renewal = $renewal;
                        $meta->save();

                        $template = $this->membersapplicationrenewalpaymentpost(Crypt::encrypt($insert->id));
                        return response()->json(['status'=>'success','template'=>$template]);
                    }
                    return response()->json(['status'=>'error','msg'=>'Members details not found']);
                }elseif($input["category"] == "individual"){
                    $individual = Option::getvalue('individual');
                    $GST = Option::getvalue('GST');
                    $amount = $individual / 100;
                    $pay = ceil($individual + ($amount * $GST));

                    $member = Members::where("unique_id", $uniqueID)->first();
                    if($member){
                        $renewal = $member->renewal + 1;

                        if(date("Y-m-d", strtotime($member->expiryDate)) > date("Y-m-d")){
                            $datetime1 = new DateTime(date("Y-m-d", strtotime($member->expiryDate)));
                            $datetime2 = new DateTime(date("Y-m-d"));
                            $difference = $datetime1->diff($datetime2);
                            $totalDays = $difference->days + 365;
                            $endDate = date("Y-m-d", strtotime("+".$totalDays." Day"));
                        } else{
                            $endDate = date("Y-m-d", strtotime("+365 Day"));
                        }

                        $time = date("H:i:s");
                        $parsed = date_parse($time);
                        $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

                        $insert = Members::find($member->id);
                        $insert->mem_category = $input["category"];
                        $insert->org_name = $input["companyname_i"];
                        $insert->con_person = $input["contactperson_i"];
                        $insert->address = $input["address1_i"];
                        $insert->phone = $input["phoneno_i"];
                        $insert->mobile = $input["mobileno_i"];
                        $insert->email = $input["emailid_i"];
                        $insert->facebook = $input["fb_i"];
                        $insert->twitter = $input["twi_i"];
                        $insert->linkedin = $input["ln_i"];
                        $insert->date_renewed = date("Y-m-d H:i:s");
                        $insert->status = "inactive";
                        $insert->price = $pay;
                        $insert->renewal = $renewal;
                        $insert->expiryDate = $endDate;
                        $insert->timing = $seconds;
                        $insert->emailStatus = "no";
                        $insert->updatedBy = Auth::User()->id;
                        $insert->save();

                        $meta = new MembersMeta();
                        $meta->userID = $member->unique_id;
                        $meta->createdOn = date("Y-m-d H:i:s");
                        $meta->renewal = $renewal;
                        $meta->save();

                        $template = $this->membersapplicationrenewalpaymentpost(Crypt::encrypt($insert->id));
                        return response()->json(['status'=>'success','template'=>$template]);
                    }
                    return response()->json(['status'=>'error','msg'=>'Members details not found']);
                }else if($input["category"] == "student"){
                    $student = Option::getvalue('student');
                    $GST = Option::getvalue('GST');
                    $amount_stu = $student / 100;
                    $pay = ceil($student + ($amount_stu * $GST));
                    $time = date("H:i:s");
                    $parsed = date_parse($time);
                    $seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];

                    $member = Members::where("unique_id", $uniqueID)->first();
                    if($member){
                        $renewal = $member->renewal + 1;

                        if(date("Y-m-d", strtotime($member->expiryDate)) > date("Y-m-d")){
                            $datetime1 = new DateTime(date("Y-m-d", strtotime($member->expiryDate)));
                            $datetime2 = new DateTime(date("Y-m-d"));
                            $difference = $datetime1->diff($datetime2);
                            $totalDays = $difference->days + 365;
                            $endDate = date("Y-m-d", strtotime("+".$totalDays." Day"));
                        } else{
                            $endDate = date("Y-m-d", strtotime("+365 Day"));
                        }

                        $insert = Members::find($member->id);
                        $insert->mem_category = $input["category"];
                        $insert->org_name = $input["companyname_i"];
                        $insert->con_person = $input["contactperson_i"];
                        $insert->address = $input["address1_i"];
                        $insert->phone = $input["phoneno_i"];
                        $insert->mobile = $input["mobileno_i"];
                        $insert->email = $input["emailid_i"];
                        $insert->facebook = $input["fb_i"];
                        $insert->twitter = $input["twi_i"];
                        $insert->linkedin = $input["ln_i"];
                        $insert->date_renewed = date("Y-m-d H:i:s");
                        $insert->status = 'inactive';
                        $insert->price = $pay;
                        $insert->expiryDate = $endDate;
                        $insert->timing = $seconds;
                        $insert->emailStatus = "no";
                        $insert->updatedBy = Auth::User()->id;
                        $insert->save();

                        $meta = new MembersMeta();
                        $meta->userID = $member->unique_id;
                        $meta->createdOn = date("Y-m-d H:i:s");
                        $meta->renewal = $renewal;
                        $meta->save();  

                        $template = $this->membersapplicationrenewalpaymentpost(Crypt::encrypt($insert->id));
                        return response()->json(['status'=>'success','template'=>$template]);
                    }
                    return response()->json(['status'=>'error','msg'=>'Members details not found']);
                }
            });
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            return response()->json(['status'=>'error','msg'=>'Error. Please try again']);
        }
    }

    public function membersapplicationrenewalpaymentpost($key){
        try {
            return DB::transaction(function() use($key){
                $id = Crypt::decrypt($key);
                $info = Members::find($id);
                $reqID = $info->unique_id;
                $price = $info->price;
                $tID = time();
                $billing_email = $info->email;
                $billing_name = $info->con_person;
                $billing_address = $info->address;
                $billing_tel = $info->mobile;
                // $parameters = [
                //     'tid' => $tID,
                //     'order_id' => $reqID,
                //     'amount' => $price,
                //     'billing_email'=>$billing_email,
                //     'billing_name'=>$billing_name,
                //     'billing_address'=>$billing_address,
                //     'billing_tel'=>$billing_tel,
                //     'merchant_param1'=>'Membership Renewal',
                //     'merchant_param2'=>$key,
                // ];
                
                // $order = Indipay::prepare($parameters);
                // return Indipay::process($order);

                $payu_url = '';
                $payu_merchant_key = '';
                $payu_salt = '';

                if(env('PAYMENT_MODE') == 'test'){
                    $payu_url = env('PAYMENT_TEST_URL');
                    $payu_merchant_key = env('PAYMENT_TEST_MERCHANT_KEY');
                    $payu_salt = env('PAYMENT_TEST_SALT');
                }else if(env('PAYMENT_MODE') == 'live'){
                    $payu_url = env('PAYMENT_LIVE_URL');
                    $payu_merchant_key = env('PAYMENT_LIVE_MERCHANT_KEY');
                    $payu_salt = env('PAYMENT_LIVE_SALT');
                }

                $basicInfo = [
                    'merchant_key' => $payu_merchant_key,
                    'salt' => $payu_salt,
                    'payu_base_url' => $payu_url, //https://secure.payu.in/_payment
                    'txn_id' => $reqID,
                    'amount' => number_format($price, 2, '.', ''),
                    'productinfo' => 'Membership Renewal',
                    'firstname' => $billing_name,
                    'email' => $billing_email,
                    'phone' => $billing_tel,
                    'udf1' => 'Membership Renewal',
                    'udf2' => $key,
                    'udf3' => "",
                    'udf4' => "",
                    'udf5' => "",
                    'udf6' => "",
                    'udf7' => "",
                    'udf8' => "",
                    'udf9' => "",
                    'udf10' => "",
                    'surl' => route('payment.success'),//route('payment.success'),
                    'furl' => route('payment.failure'), //route('payment.failure')
                ];
                $hashSequence = "merchant_key|txn_id|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
                $hashVarsSeq = explode('|', $hashSequence);
                $hash_string = '';
                foreach($hashVarsSeq as $hash_var) {
                    $hash_string .= isset($basicInfo[$hash_var]) ? $basicInfo[$hash_var] : '';
                    $hash_string .= '|';
                }                
                $hash_string = $hash_string.$basicInfo['salt'];
                $hash = strtolower(hash('sha512', $hash_string));
                $basicInfo['hash_string'] = $hash;
                $template = view('frontend.payment-form-template')->with('basicInfo', $basicInfo)->render();
                return $template;

            });/* end of db transaction */
        } catch (Exception $e) {
            //Trackingreport::track("error", $e->getMessage(), "", "", "Course Application");
            return redirect()->back()->with("error", "Something went wrong");
        }
    }
    
}
