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

	include_once 'inc/functions.php';
	include_once 'inc/database.php';
	include_once 'requestFunctions.php';

    if( isset($_REQUEST['signed_payload']) || (isset($_REQUEST['store_hash']) && !empty($_REQUEST['store_hash'])) ){
		$data = decodeSignedRequest($_REQUEST['signed_payload']);
		$hash = isset($data['store_hash']) ? $data['store_hash'] : $_REQUEST['store_hash'];

		$access_payload	= $_REQUEST['signed_payload'];
		$access_token = $db->getSingleColumn( "stores", "access_token", array( "store_id" => $hash ));
		if( $access_token == ""){
            die("store access token not found.");
        }

		$config = array(
			'client_id'  => CLIENT_ID,
			'auth_token' => $access_token,
			'store_hash' => $hash
		);
        $API_PATH = 'https://api.bigcommerce.com/stores/'.$hash;

        $headers = array(
            "accept: application/json",
            "content-type: application/json",
            "x-auth-client: ".CLIENT_ID,
            "x-auth-token: ".$access_token
        );

        if(isset($_POST["coupon_submit"])){
            $count = $_POST["limit"];
            $type = $_POST["type"];
            $timezone_val = $_POST["timezone"];
            $end_time_ajusted = "T23:59:59".$timezone_val;
            $expiry = date("Y-m-d", strtotime($_POST["expiry"]));
            $amount = $_POST["amount"];
            $expiry = $expiry.$end_time_ajusted;
            $date = new DateTime($expiry);
            $expiry = $date->format(DateTime::RFC2822);
            $coupon_generated = 0;
            $csv_data = [["Name", "Code", "Type", "Amount", "Expiry"]];
            while($count > 0){
                $code = uniqid();
                $data = array(
                    "code" => $code,
                    "name" => $code,
                    "type" => $type,
                    "enabled" => true,
                    "amount" => $amount,
                    "expires" => $expiry,
                    "max_uses" => 1,
                    "applies_to" => array(
                        "entity" => "categories",
                        "ids" => [0]
                    )
                );
                $data = json_encode($data);
                $url = $API_PATH."/v2/coupons";
                $res = curlPostRequest($url, $headers, $data);
                if($res["id"]){
                    $coupon_generated++;
                    $gen_csv_row = array(
                        $res["name"], $res["code"], $res["type"], $res["amount"], $res["expires"]
                    );
                    $csv_data[] = $gen_csv_row;	
                }
                $count--;
            }
            echo json_encode(
                array(
                    "data" => $csv_data, 
                    "status" => true,
                    "counts" => $coupon_generated
                )
            );
        }
    }
?>