<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        // fetch RAW input
        $json = file_get_contents('php://input');

        // decode json
        $charge = json_decode($json);

        function getApiToken(){
			$tokens = array("sk_1x1_d93b5d9b570c3bf99ade11c925389a3765f5cd368876e22f3daefac73fad6f5f","sk_2x1_0880989c800db489685aa7656f46ec1fd9a7a50d48b84f5216769d85c18f71f9","sk_2x1_df71bbd5413fbfddf2929ac5a2b99b7f25bc3926a585f95b061d1b8104c6fe31","sk_2x1_ff63809f7d58693e38c6d167d5dfcd463f0421f7e9fafb58337126f097aa44e7");
			$k = array_rand($tokens);
			return $token = $tokens[$k];
		}

        //if (strpos($charge->charge->tags, 'Subscription First Order') === false) {
			function orderUpdate($order_id,$date){

				$token = getApiToken();

	          $ch = curl_init("https://api.rechargeapps.com/orders/".$order_id."/change_date");
	          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	          curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
	          curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($date));
	          $response1 = json_decode(curl_exec($ch));
	          if(isset($response1->error) || empty($response1->order->address_id)){
	            $result = orderUpdateError($order_id,$date);
	            if(isset($result->error) || empty($result->order->address_id)){
	              $result1 = orderUpdateError($order_id,$date);
	              if(isset($result1->error) || empty($result1->order->address_id)){
	                $result2 = orderUpdateError($order_id,$date);
	                if(isset($result2->error) || empty($result2->order->address_id)){
	                	file_put_contents('trial-log.txt', "====order step 5===",FILE_APPEND);
	                  $result3 = orderUpdateError($order_id,$date);
	                  return $result3;
	                }else{
	                	file_put_contents('trial-log.txt', "====order step 4===",FILE_APPEND);
	                  return $result2;
	                }
	              }else{
	              	file_put_contents('trial-log.txt', "====order step 3===",FILE_APPEND);
	                return $result1;
	              }
	            }else{
	            	file_put_contents('trial-log.txt', "====order step 2===",FILE_APPEND);
	              return $result;
	            }
	          }else{
	          	file_put_contents('trial-log.txt', "====order step 1===",FILE_APPEND);
	            return $response1;
	          }
	        }

	        function orderUpdateError($order_id,$date){

	        	$token = getApiToken();

	          $ch = curl_init("https://api.rechargeapps.com/orders/".$order_id."/change_date");
	          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	          curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
	          curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($date));
	          $response1 = json_decode(curl_exec($ch));
	          return $response1;
	        }

	        function nextChargeDateUpdate($data = array(),$subscription_id=''){

	        	$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/subscriptions/".$subscription_id."/set_next_charge_date");
	          	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	          	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	          	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
	          	curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
	          	$response = json_decode(curl_exec($ch));
	          	curl_close($ch);

	          	$ch = curl_init("https://api.rechargeapps.com/subscriptions/".$subscription_id."/set_next_charge_date");
	          	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	          	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	          	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
	          	curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
	          	$response = json_decode(curl_exec($ch));
	          	curl_close($ch);

	          	if(isset($response->error)){
		            $response1 = nextChargeDateUpdateError($data,$subscription_id);
		            file_put_contents('trial-log.txt', "====next charge step 1===",FILE_APPEND);
		            if(isset($response1->error)){
		            	file_put_contents('trial-log.txt', "====next charge step 2===",FILE_APPEND);
		              	$response2 = nextChargeDateUpdateError($data,$subscription_id);
		              if(isset($response2->error)){
		              	file_put_contents('trial-log.txt', "====next charge step 3===",FILE_APPEND);
		                $response3 = nextChargeDateUpdateError($data,$subscription_id);
		                if(isset($response3->error)){
		                	file_put_contents('trial-log.txt', "====next charge step 4===",FILE_APPEND);
		                  	$response4 = nextChargeDateUpdateError($data,$subscription_id);
		                }
		              }
		            }
		        }

			}

			function nextChargeDateUpdateError($data = array(),$subscription_id=''){

				$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/subscriptions/".$subscription_id."/set_next_charge_date");
	          	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	          	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	          	curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
	          	curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($data));
	          	$response = curl_exec($ch);
	          	curl_close($ch);

			}


			function getSubscriptionInfo($subscription_id=''){

				$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/subscriptions/".$subscription_id);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
				$reponse = curl_exec($ch);

				file_put_contents('trial-log.txt', "===subscription data ===".$reponse,FILE_APPEND);
				
				$subscription = json_decode($reponse);
				curl_close($ch);

				if(isset($subscription->error) || empty($subscription->subscription->properties)){
					$response1 = getSubscriptionInfoError($subscription_id);
					if(isset($response1->error) || empty($response1->subscription->properties)){
						
						$response2 = getSubscriptionInfoError($subscription_id);
						if(isset($response2->error) || empty($response2->subscription->properties)){
							$response3 = getSubscriptionInfoError($subscription_id);
							file_put_contents('trial-log.txt', "===subscription step 4===",FILE_APPEND);
							return $response3;
						}else{
							file_put_contents('trial-log.txt', "===subscription step 3===",FILE_APPEND);
							return $response2;
						}
						
					}else{
						file_put_contents('trial-log.txt', "===subscription step 2===",FILE_APPEND);
						return $response1;
					}
				}else{
					file_put_contents('trial-log.txt', "===subscription step 1===",FILE_APPEND);
					return $subscription;
				}
			}

			function getSubscriptionInfoError($subscription_id=''){

				$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/subscriptions/".$subscription_id);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
				$subscription = json_decode(curl_exec($ch));

				curl_close($ch);

				return $subscription;
			}


			function getChargeInfo($charge_id=''){

				$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/orders?charge_id=".$charge_id);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
                $response = json_decode(curl_exec($ch));

                curl_close($ch);

				if(isset($response->error)){
					
					$response1 = getChargeInfoError($charge_id);
					if(isset($response1->error)){
						file_put_contents('trial-log.txt', "====Charge step 3===",FILE_APPEND);
						$response2 = getChargeInfoError($charge_id);
						return $response2;
					}else{
						file_put_contents('trial-log.txt', "====Charge step 2===",FILE_APPEND);
						return $response1;
					}
				}else{
					file_put_contents('trial-log.txt', "====Charge step 1===",FILE_APPEND);
					return $response;
				}
			}

			function getChargeInfoError($charge_id=''){

				$token = getApiToken();

				$ch = curl_init("https://api.rechargeapps.com/orders?charge_id=".$charge_id);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
                curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json','x-recharge-access-token: '.$token));
                $response = json_decode(curl_exec($ch));

                curl_close($ch);

                return $response;
			}

			file_put_contents('trial-log.txt', "===Charge ID: ".$charge->charge->id."===",FILE_APPEND);

			foreach ($charge->charge->line_items as $key => $value) {

				file_put_contents('trial-log.txt', "===Subscription ID: ".$value->subscription_id."===",FILE_APPEND);
				
				$subscription = getSubscriptionInfo($value->subscription_id);

				$token = getApiToken();
				
				$checkReplace = '';
				foreach ($subscription->subscription->properties as $k => $v) {
					if($v->name=="trial"){
						$checkReplace = $v->value;
						file_put_contents('trial-log.txt', "====trial=replace===",FILE_APPEND);
					}
				}

				file_put_contents('trial-log.txt', "====Paid=No===",FILE_APPEND);
				file_put_contents('trial.txt', "===========Paid=====No=======",FILE_APPEND);
				file_put_contents('trial-log.txt', $charge->charge->email,FILE_APPEND);
	        	file_put_contents('trial.txt', $charge->charge->email,FILE_APPEND);

				if($checkReplace=="replace"){
					file_put_contents('trial.txt', "===========Paid============",FILE_APPEND);
	        		file_put_contents('trial.txt', $charge->charge->email,FILE_APPEND);
	        		file_put_contents('trial-log.txt', "====Paid=Yes===",FILE_APPEND);
					file_put_contents('trial-log.txt', $charge->charge->email,FILE_APPEND);
					$month = date("M");
					$day = date("d");
					$year = date("Y");
					$month = date("M");

		            if($month=="Sep" || $month=="Oct" || $month=="Nov"){
		                $nextDate = date('Y', strtotime('+1 year'))."-09-01";
		            }elseif($month=="Dec") {
		                $nextDate = date('Y', strtotime('+1 year'))."-12-01";
		            }elseif($month=="Mar" || $month=="Apr" || $month=="May"){
		                $nextDate = date('Y', strtotime('+1 year'))."-03-01";
		            }elseif($month=="Jun" || $month=="Jul" || $month=="Aug"){
		                $nextDate = date('Y', strtotime('+1 year'))."-06-01";
		            }elseif($month=="Jan" || $month=="Feb"){
		                  $nextDate = date('Y')."-12-01";
		            }


					if($charge->charge->id!=''){

						file_put_contents('trial-log.txt', "====Charge Condition===",FILE_APPEND);
						$response = getChargeInfo($charge->charge->id);

                      	foreach ($response->orders as $count=>$order) {
	                        if($count==0){
	                          if($month=="Sep" || $month=="Oct" || $month=="Nov"){
	                              $nextDate1 = date("Y",strtotime('+1 year'))."-06-01";
	                           }elseif($month=="Dec") {
	                              $nextDate1 = date("Y",strtotime('+1 year'))."-09-01";
	                           }elseif($month=="Mar" || $month=="Apr" || $month=="May"){
	                              $nextDate1 = date('Y')."-12-01";
	                           }elseif($month=="Jun" || $month=="Jul" || $month=="Aug"){
	                              $nextDate1 = date('Y', strtotime('+1 year'))."-03-01";
	                           }elseif($month=="Jan" || $month=="Feb"){
	                                $nextDate1 = date('Y')."-09-01";
	                           }
	                        }

	                        if($count==1){
	                          	if($month=="Sep" || $month=="Oct" || $month=="Nov"){
	                              	$nextDate1 = date("Y",strtotime('+1 year'))."-03-01";
	                           	}elseif($month=="Dec") {
	                              	$nextDate1 = date("Y",strtotime('+1 year'))."-06-01";
	                           	}elseif($month=="Mar" || $month=="Apr" || $month=="May"){
	                              	$nextDate1 = date('Y')."-09-01";
	                           	}elseif($month=="Jun" || $month=="Jul" || $month=="Aug"){
	                              	$nextDate1 = date('Y')."-12-01";
	                           	}elseif($month=="Jan" || $month=="Feb"){
	                                $nextDate1 = date('Y')."-06-01";
	                           	}
	                        }

	                        if($count==2){
	                          	if($month=="Sep" || $month=="Oct" || $month=="Nov"){
	                              	$nextDate1 = date('Y')."-12-01";
	                           	}elseif($month=="Dec") {
	                              	$nextDate1 = date("Y",strtotime('+1 year'))."-03-01";
	                           	}elseif($month=="Mar" || $month=="Apr" || $month=="May"){
	                              	$nextDate1 = date('Y')."-06-01";
	                           	}elseif($month=="Jun" || $month=="Jul" || $month=="Aug"){
	                              	$nextDate1 = date('Y')."-09-01";
	                           	}elseif($month=="Jan" || $month=="Feb"){
	                                $nextDate1 = date('Y')."-03-01";
	                           	}
	                        }

	                        $data = array("scheduled_at" => $nextDate1);
                          	$res = orderUpdate($order->id,$data);
                      	}

					}

					$data = array("date" => $nextDate);
		          	nextChargeDateUpdate($data,$value->subscription_id);
				}
			}
	    //}
    }else{
    	echo "empty";
    }
	
	