<?php
// ini_set("error_reporting", E_ALL);
// ini_set("display_errors", true);

	header('Access-Control-Allow-Origin: *');
	header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

	include 'inc/database.php';
	require_once 'vendor/autoload.php';
	include_once 'requestFunctions.php'; 

	\Stripe\Stripe::setApiKey($stripe['secret_key']);

	if(isset($_REQUEST['store_hash']) && isset($_REQUEST['action']) && $_REQUEST['action'] == "unsubscribe") {
		$store_hash = $_REQUEST["store_hash"];
		$store_data["status"] = "deactive";
		$store_data["unsubscribed_at"] = date("Y-m-d H:i:s");
		$store_data["updated_at"] = date("Y-m-d H:i:s");	
		$channel_id = $_REQUEST["channel_id"];
		$checkIfStripCutomer = $db->select("subscription","*" ,array( "store_id" => $store_hash, "channel_id"=> $channel_id));
		$return_res = array();
		if($checkIfStripCutomer['id']){
			try{
				$stripe_obj = new \Stripe\StripeClient(
					$stripe['secret_key']
				);
				$cancelObj = $stripe_obj->subscriptions->cancel(
					$checkIfStripCutomer["stripe_subscription_id"]
				);
				$store_settings = $db->update( "subscription",
					$store_data, array("store_id" => $store_hash, "channel_id"=> $channel_id)
				);
				$store_data1['script_enabled'] = 0;
				$store_data1["updated_at"] = date("Y-m-d H:i:s");
				$store_settings = $db->update( "stores",
					$store_data1, array("store_id" =>  $store_hash, "channel_id"=> $channel_id)
				);
				$return_res = array(
					"status"=> true
				);
			}

			catch (Exception $e){
				$return_res = array(
					"status"=> false,
				);
			}
			echo json_encode($return_res);
		}
	}
?>