<?php
/**copyright*/

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
	require_once('../../includes/config.inc.php');
	
	/* system controller */
	require_once(RL_INC . 'control.inc.php');

	/* load system configurations */
	$config = $rlConfig->allConfig();
	
	require_once(RL_CLASSES . 'rlGateway.class.php');
	$reefless->loadClass('Payment');
	$reefless->loadClass('Stripe', null, 'stripe');
	$reefless->loadClass('Json');

	/* save response to log */
	if ($GLOBALS['config']['stripe_test_mode']) {
		$file = fopen('response.log', 'a');

		if ($file) {                      
			$line = "\n\n" . date( 'Y.m.d H:i:s' ) . ":\n";
		    fwrite($file, $line);          

		    fwrite($file, @file_get_contents("php://input"));
			fclose($file);
		}
	}

	$response = trim(@file_get_contents("php://input"));
	$response = $rlJson->decode($response);	
	$subscription = $response->data->object->lines->data[0]->type;
	$txn_id = $rlValid->xSql($response->data->object->charge);
	$total = round((float)$response->data->object->lines->data[0]->amount / 100, 2);

	if ($response->type == 'invoice.payment_succeeded' && $subscription) {
		if (version_compare($GLOBALS['config']['rl_version'], '4.4.0') >= 0) {
			$subscription_id = $rlValid->xSql($response->data->object->lines->data[0]->id);
			$subscription_info = $rlStripe->getSubscriptionByID($subscription_id);

			$items = $subscription_info['Stirpe_item_data'];

			$data = array(
				'plan_id' => $subscription_info['Plan_ID'],
				'item_id' => $subscription_info['Item_ID'],
				'account_id' => $subscription_info['Account_ID'],
				'total' => $total,
				'txn_gateway' => $txn_id ,
				'params' => $items[12]
			);

			if ($subscription_info) {
				$sql = "UPDATE `" . RL_DBPREFIX . "subscriptions` SET `Count` = `Count` + 1 WHERE `ID` = '{$subscription_info['ID']}' LIMIT 1";
				$rlDb->query($sql);

				$sql = "SELECT * FROM `" . RL_DBPREFIX . "transactions` WHERE `ID` = '{$items[3]}' LIMIT 1";
				$transaction = $rlDb->getRow($sql);
				
	            if (empty($transaction['ID'])) {
					$insert = array(
							'Service' => $subscription_info['Service'],
							'Account_ID' => $subscription_info['Account_ID'],
							'Item_ID' => $subscription_info['Item_ID'],
							'Plan_ID' => $subscription_info['Plan_ID'],
							'Total' => $total,
							'Txn_ID' => $txn_id,
							'Date' => 'NOW()',
							'Item_name' => $subscription_info['Item_name'],
							'Gateway' => 'stripe',
							'Status' => 'paid'
						);

					$rlActions->insertOne($insert, 'transactions');
	            } else {
					$sql = "UPDATE `" . RL_DBPREFIX . "transactions` SET `Txn_ID` = '{$txn_id}', `Status` = 'paid' WHERE `ID` = '{$items[3]}' LIMIT 1";
					$rlDb->query($sql);
	            }

				$rlPayment->complete($data, $items[0], $items[1], $items[2]);
			}
		} else {
			$subscription_info = $rlStripe->getSubscriptionByID($subscription_id);
			$items = $subscription_info['Item_data'];

			$sql = "UPDATE `" . RL_DBPREFIX . "stripe_subscriptions` SET `Count` = `Count` + 1, `Date` = NOW() WHERE `ID` = '".$subscription_info['ID']."' LIMIT 1";
			$rlDb->query($sql);

			$callback_class = $items[4];
			$callback_method = $items[5];

			$reefless->loadClass(str_replace('rl', '', $callback_class), null, $items[6] ? $items[6] : false);
			$GLOBALS[$callback_class]->$callback_method($items[1], $items[0], $items[2], $txn_id, 'stripe', $total);
		}
	}

	if (version_compare(PHP_VERSION, '5.4.0') >= 0) {
		http_response_code(200);
	}
}