<?php

session_start();
ini_set('memory_limit', '1024M');
require_once ("db/AppManager.php");
require_once ("./amazon/.config.inc.php");
require_once ("./amazon/ListOrdersClass.php");
require_once ("./amazon/ListOrderItemsClass.php");
require_once ("./amazon/ListOrdersByNextTokenClass.php");
require_once ("./amazon/GetOrderRequest.php");
require_once ("./aws/aws_signed_request.php");
require_once ("./amazon/GetMatchingProductForIdSample.php");
require_once ("./amazon/GetMatchingProductForIdRequest.php");
if (!empty($_SESSION['step3'])) {
    session_destroy();
    header('location:index.php');
}

//hymsalih@gmail.com
//order_id = 111-0796385-2395440
//code = 0001

$action = (!empty($_REQUEST['action']) ? $_REQUEST['action'] : '');
if (empty($action)) {
    session_destroy();
    header('location:index.php');
    die();
}
switch ($action) {
    case "amazon_key":
        amazon_key_manage();
        break;
    case "insert_sort_url":
        insert_ASIN_sort_url();
        break;
    case "delete_ASIN_URL":
        delete_ASIN_URl();
        break;
    case "update_ASIN_URL":
        asin_sortURL_update();
        break;
    case "charityUpdate":
        charityUpdate();
        break;
    case "deleteQuestionTitle":
        deleteQuestionTitle();
        break;
    case "questionTitleView":
        questionTitleView();
        break;
    case "questionTitleDelete":
        questionTitleDelete();
        break;
    case "insertCharity":
        insertCharity();
        break;
    case "deleteCharity":
        deleteCharity();
        break;
    case "passwordChange":
        passwordChange();
        break;
    case "updateQuestionTitle":
        updateQuestionTitle();
        break;
    case "passwordChangeView":
        passwordChangeView();
        break;
    case "step_1":
        $_SESSION['step1'] = 'true';
        $order_id = $_REQUEST['order_id'];
        $email_address_ = $_REQUEST['email_address'];
        $_SESSION['amazon_o_ID'] = $order_id;
        $_SESSION['email'] = $email_address_;
        $is_order_used = isCheckOrderAlreadyUsed($order_id);
        $isvalid = isCheckOrderAlreadyvalid($order_id);
        if (!empty($is_order_used)) {
            $_SESSION['error'] = "order_id_Exisist";
            header('Location:error.php');
        } else if (empty($isvalid)) {
            $pm = AppManager::getPM();
            $pm->executeQuery("INSERT INTO `order_details` (`id`, `email`, `amazon_order_id`, `status`) VALUES (NULL, '" . $email_address_ . "', '" . $order_id . "', '0')");
            $sql = "SELECT * FROM order_details WHERE amazon_order_id = '" . $order_id . "' AND email='" . $email_address_ . "'";
            $is_order_used = $pm->fetchResult($sql);
            step_one_success($email_address_, $is_order_used[0]['id']);
            isCheckAmazonOrderIsValid($order_id);
        } else if (!empty($isvalid)) {
            $pm = AppManager::getPM();
            $sql = "SELECT * FROM order_details WHERE amazon_order_id = '" . $order_id . "'";
            $is_order_used = $pm->fetchResult($sql);
            step_one_success($email_address_, $is_order_used[0]['id']);
            isCheckAmazonOrderIsValid($order_id);
        } else {
            $_SESSION['error'] = "order_not_found";
            header('Location:error.php');
        }
        break;
    case "step_2":
        $_SESSION['step2'] = 'true';
        $pm = AppManager::getPM();
        $sql = "SELECT * FROM answers WHERE amazon_order_id = '" . $_SESSION['amazon_order_id'] . "'";
        $answerFound = $pm->fetchResult($sql);
        if (empty($answerFound)) {
            $sql = "INSERT INTO `answers` (`id`, `amazon_order_id`, `question_page` ,`answer`) VALUES (NULL,'1', '" . $_SESSION['amazon_order_id'] . "','" . json_encode($_REQUEST) . "');";
            $pm->executeQuery($sql);
        }
        $_SESSION['yes/no'] = $_POST['is_yes'];
        $_SESSION['star'] = $_POST['star'];
        header('Location:step_2.php');
        break;
    case "step_3":
        $_SESSION['step3'] = 'true';
        $pm = AppManager::getPM();
        $arr = array("rebate" => addslashes($_POST['rebate']), "name" => addslashes($_POST['name']), "address" => addslashes($_POST['address']), "city" => addslashes($_POST['city']), "state" => addslashes($_POST['state']), "Zip" => addslashes($_POST['Zip']));
        $arr2 = json_encode($arr);
        $sql = "INSERT INTO `answers` (`id`, `amazon_order_id`, `question_page` ,`answer`) VALUES (NULL, '" . addslashes($_SESSION['amazon_order_id']) . "','2', '" . json_encode($arr) . "');";
        $pm->executeQuery($sql);
        $sql2 = "UPDATE `order_details` SET `status`='1' WHERE id='" . trim(addslashes($_SESSION['amazon_order_id'])) . "'";
        $pm->executeQuery($sql2);
        if (empty($_POST['name'])) {
            $arr3 = array("name" => addslashes($_SESSION["Customer_name"]), "address" => addslashes($_SESSION["address"]), "city" => addslashes($_SESSION["city"]), "state" => addslashes($_SESSION["state"]), "Zip" => addslashes($_SESSION['zip_code']));
            $arr4 = json_encode($arr3);
            $sql3 = 'insert into all_information(`id`,`amazon_order_id`,`email`,`rebate`,`star`,`charity`,`address`) values("null","' . trim(addslashes($_SESSION["amazon_order_id"])) . '","' . addslashes($_SESSION['email']) . '","' . addslashes($_POST['rebate']) . '","' . $_SESSION['star'] . '","' . $_POST['charity'] . '",' . json_encode($arr4) . ')';
            $pm->executeQuery($sql3);
        } else {
            $arr5 = array("name" => addslashes($_POST["name"]), "address" => addslashes($_POST["address"]), "city" => addslashes($_POST["city"]), "state" => addslashes($_POST["state"]), "Zip" => addslashes($_POST['Zip']));
            $arr6 = json_encode($arr5);
            $sql4 = 'insert into all_information(`id`,`amazon_order_id`,`email`,`rebate`,`star`,`charity`,`address`) values("null","' . trim(addslashes($_SESSION['amazon_order_id'])) . '","' . addslashes($_SESSION['email']) . '","' . addslashes($_POST['rebate']) . '","' . $_SESSION['star'] . '","' . $_POST['charity'] . '",' . json_encode($arr6) . ')';
            $pm->executeQuery($sql4);
        }
        if ($_SESSION['star'] > 3) {
            $asin = $_SESSION['asin'];
            $sqlredi = 'select * from sortlink_asin where `ASIN`="' . $asin . '"';
            $result = $pm->fetchResult($sqlredi);
            if (!empty($result)) {
                $url = $result[0]['sort_link'];
                header("Location:$url");
            } else {
                echo "Default URL redirection";
            }
            // header('Location:please_wait.php');
//            header("Refresh:1; url=index.php");
        } else if ($_SESSION['star'] < 4) {
            header('Location:info.php');
        }



        break;
    case "customer_details":
        $code = $_GET['code'];
        if (!empty($code)) {
            $sql = "SELECT * FROM item WHERE amazon_order_id = '" . addslashes($code) . "' LIMIT 1";
            $customer_details = $pm->fetchResult($sql);
            echo json_encode($customer_details[0]);
        }
        break;
    case "login":
        $username = $_REQUEST['user_name'];
        $Password = $_REQUEST['password'];
        $sql = "SELECT * FROM user WHERE user_name = '" . addslashes($username) . "' AND password = '" . sha1($Password) . "' LIMIT 1";
        $log = $pm->fetchResult($sql);
        if (!empty($log)) {
            // session_start();
            $_SESSION['user_name'] = $log[0]['user_name'];
            $_SESSION['log'] = "true";
            header('Location:manage_questions.php');
        } else {
            //  session_start();
            $_SESSION['error_log'] = "1";
            $_SESSION['error'] = "Invalid user name and password";
            header('Location:login.php');
        }
        break;
    default:
        break;
}

function insert_ASIN_sort_url() {
    $pm = AppManager::getPM();
    $asin = $_POST['asin'];
    $url = $_POST['url'];
    $sql = 'insert into sortlink_asin(`ASIN`,`sort_link`) values("' . $asin . '","' . $url . '")';
    $result = $pm->executeQuery($sql);
    echo json_encode($result);
}

function delete_ASIN_URl() {
    $pm = AppManager::getPM();
    $asin = $_POST['asin'];

    $sql = 'delete from sortlink_asin where `ASIN`="' . $asin . '"';
    $result = $pm->executeQuery($sql);
    echo json_encode($result);
}

function asin_sortURL_update() {

    $pm = AppManager::getPM();
    $asin = $_POST['asin'];
    $url = $_POST['url'];
    $old = $_POST['oldasin'];
    $sql = 'update  sortlink_asin set `ASIN`="' . $asin . '",`sort_link`="' . $url . '" where `ASIN`="' . $old . '"';
    $result = $pm->executeQuery($sql);
    echo json_encode($result);
}

function deleteQuestionTitle() {
    $pm = AppManager::getPM();
    $receive_id = $_POST['id'];
    $resultarr = $pm->executeQuery('delete from questions where id="' . $receive_id . '"');
    echo json_encode($receive_id);
}

function updateQuestionTitle() {
    $pm = AppManager::getPM();
    $receive_id = $_POST['id'];
    $receive_title = $_POST['title'];
    $resultarr = $pm->executeQuery('update questions set title="' . $receive_title . '" where id="' . $receive_id . '"');
    echo json_encode($receive_id);
}

function questionTitleView() {
    $pm = AppManager::getPM();
    $receive_id = $_POST['id'];
    $resultarr = $pm->fetchResult("select * from questions where id='" . $receive_id . "'");
    $resulttitle = $resultarr[0]['title'];
    $resulid = $resultarr[0]['id'];
    $myarray['id'] = $resulid;
    $myarray['title'] = $resulttitle;
    echo json_encode($myarray);
}

function passwordChangeView() {
    $pm = AppManager::getPM();
    $resultarr = $pm->fetchResult('select * from user');
    $id = $resultarr[0]['id'];
    $userName = $resultarr[0]['user_name'];
    $Password = $resultarr[0]['password'];
    $send['id'] = $id;
    $send['user_name'] = $userName;
    echo json_encode($send);
}

function passwordChange() {
    $pm = AppManager::getPM();
    $resultarr = $pm->fetchResult('select * from user');
    $id = $resultarr[0]['id'];
    $receive_name = $_POST['user'];
    $recieve_password = $_POST['password'];
    if (!empty($_POST['password']) && $_POST['password'] == "undefined") {
        $recieve_password = "";
    }
    if (!empty($recieve_password)) {
        $recieve_password = sha1($recieve_password);
        $resultarr = $pm->executeQuery('update user set user_name="' . $receive_name . '",password="' . $recieve_password . '" where id="' . $id . '"');
    } else {
        $resultarr = $pm->executeQuery('update user set user_name="' . $receive_name . '" where id="' . $id . '"');
    }
    echo json_encode($receive_name);
}

function deleteCharity() {
    $pm = AppManager::getPM();
    $receive_id = $_POST['id'];
    $resultarr = $pm->executeQuery('delete from charity  where id="' . $receive_id . '"');
    echo json_encode(array("results" => "success"));
}

function insertCharity() {
    $pm = AppManager::getPM();
    $receive_title = $_POST['mytxt'];
    $resultarr = $pm->executeQuery('insert into charity(value) values("' . $receive_title . '")');
    echo json_encode($receive_title);
}

function charityUpdate() {
    $pm = AppManager::getPM();
    $receive_id = $_POST['id'];
    $receive_title = $_POST['title'];
    $pm->executeQuery('update charity set value="' . $receive_title . '" where id="' . $receive_id . '"');
    echo 1;
}

function step_one_success($email_address, $order_id) {
    $pm = AppManager::getPM();
    $sql = "UPDATE `order_details` SET `email`='" . trim(addslashes($email_address)) . "' WHERE id='" . trim(addslashes($order_id)) . "'";
    $pm->executeQuery($sql);
}

function isCheckAmazonOrderIsValid($order_id) {
    //session_start();
    $pm = AppManager::getPM();
    $ordersResponseXML = getOrderStatus($order_id);
    if (empty($ordersResponseXML)) {
        header('Location:index.php');
        die();
    }

    $amazon_order_id = (string) $ordersResponseXML->GetOrderResult->Orders->Order->AmazonOrderId;
    $amazon_order_status = (string) $ordersResponseXML->GetOrderResult->Orders->Order->OrderStatus;

    $customer_name = (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->Name;
    $customer_address = (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->AddressLine1;
    if (!empty((string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->AddressLine2)) {
        $customer_address = $customer_address . " " . (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->AddressLine2;
    }
    $customer_city = (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->City;
    $customer_state = (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->StateOrRegion;
    $zip_code = (string) $ordersResponseXML->GetOrderResult->Orders->Order->ShippingAddress->PostalCode;

    if (!empty($amazon_order_id) & $amazon_order_id == $order_id) {
        $orderItemResponse = getItem($amazon_order_id);
        while (isset($orderItemResponse['response']) && $orderItemResponse['response'] == "Request is throttled") {
            sleep(10);
            $orderItemResponse = getItem($amazon_order_id);
        }
        if (isset($orderItemResponse->ListOrderItemsResult->OrderItems->OrderItem)) {
            $orderItems = $orderItemResponse->ListOrderItemsResult->OrderItems->OrderItem;
            $sql = "SELECT * FROM order_details WHERE status = 0 AND amazon_order_id = '" . $order_id . "'";
            $orderId = $pm->fetchResult($sql);
            if (!empty($orderId)) {
                foreach ($orderItems as $orderItem) {
                    $asin = (string) $orderItem->ASIN;
                    $asinLists = array($asin);
                    $response = getMatchingProductForIdASIN($asinLists);
                    $macthingProductResponse = invokeGetMatchingProductForId($response['service'], $response['request']);
                    $macthingProductResponse = $macthingProductResponse->GetMatchingProductForIdResult;

                    if (!empty($macthingProductResponse->Error) && $macthingProductResponse->Error->Code == "RequestThrottled") {
                        sleep(5);
                        $response = getMatchingProductForIdASIN($asinLists);
                        $macthingProductResponse = invokeGetMatchingProductForId($response['service'], $response['request']);
                        $macthingProductResponse = $macthingProductResponse->GetMatchingProductForIdResult;
                    }
                    $item = $macthingProductResponse->Products->Product;
                    $imageURL = (!empty($item->AttributeSets->ItemAttributes->SmallImage->URL) ? (string) $item->AttributeSets->ItemAttributes->SmallImage->URL : '');
                    $imageURL = str_replace("_SL75_", "_SX522_", $imageURL);
                    $sql = "INSERT INTO `item` (`id`, `amazon_order_id`,`asin`, `item_url`,`customer_name`,`address`,`city`,`state`,`zip`) VALUES (NULL, '" . $orderId[0]['id'] . "',  '" . $asin . "','" . $imageURL . "','" . $customer_name . "','" . $customer_address . "','" . $customer_city . "','" . $customer_state . "','" . $zip_code . "');";
                    $pm->executeQuery($sql);
                }

                $_SESSION["amazon_order_id"] = $orderId[0]['id'];
                $_SESSION["order_status"] = $amazon_order_status;
                $_SESSION["asin"] = $asin;
                $_SESSION["Customer_name"] = $customer_name;
                $_SESSION["address"] = $customer_address;
                $_SESSION["city"] = $customer_city;
                $_SESSION["state"] = $customer_state;
                $_SESSION['zip_code'] = $zip_code;

                header('Location:step_1.php');
            } else {

                $_SESSION['error'] = "order_not_found";
                header('Location:error.php');
            }
        }
    } else {
        // session_start();
        $_SESSION['error'] = "order_not_found";
        header('Location:error.php');
    }
}

function getImage($asin) {
    $public_key = "AKIAJ6WX4CZGTNJL2AJQ";
    $private_key = "jtOXoKmH8SF1IvqwwKgamOQhaEJRPapzpt8Wztoc";
    $requestparams = array(
        "Operation" => "ItemLookup",
        "Condition" => "All",
        "ItemId" => $asin,
        "ResponseGroup" => "Images"
    );
    $pxml = aws_signed_request("com", $requestparams, $public_key, $private_key);


    if ($pxml === False) {
        return "";
    } else {
        if ($pxml) {
            return (!empty($pxml->Items) ? (string) $pxml->Items->Item->LargeImage->URL : '');
        } else {
            return "";
        }
    }
}

function isCheckOrderAlreadyUsed($order_id_) {
    $pm = AppManager::getPM();
    $sql = "SELECT * FROM order_details WHERE status = 1 AND amazon_order_id = '" . $order_id_ . "'";
    $isNotUsed = $pm->fetchResult($sql);
    return $isNotUsed;
}

function isCheckOrderAlreadyvalid($order_id_) {
    $pm = AppManager::getPM();
//    $sql = "SELECT * FROM order_details WHERE status = 0 AND amazon_order_id = '" . $order_id_ . "' and email='" . $email_address_ . "'";
    $sql = "SELECT * FROM order_details WHERE status = 0 AND amazon_order_id = '" . $order_id_ . "'";
    $isvalid = $pm->fetchResult($sql);
    return $isvalid;
}

function amazon_key_manage() {
    $pm = AppManager::getPM();
    $sql = "SELECT * FROM amazon_key";
    $isFound = $pm->fetchResult($sql);
    if (!empty($isFound)) {
        $sql = "UPDATE `amazon_key` SET `market_place`='" . trim($_REQUEST['market_place']) . "',`aws_access_key_id`='" . trim($_REQUEST['aws_access_key_id']) . "',`aws_secret_key_id`='" . trim($_REQUEST['aws_secret_key_id']) . "',`merchant_id`='" . trim($_REQUEST['merchant_id']) . "',`market_place_id`='" . trim($_REQUEST['market_place_id']) . "' WHERE id='" . trim($isFound[0]['id']) . "'";
        $ex = $pm->executeQuery($sql);
        //  session_start();
        $_SESSION['status'] = "key_updated";
        header('location:amazon_key.php?success=updated');
    } else {
        $sql = "INSERT INTO amazon_key VALUES('','" . trim($_REQUEST['market_place']) . "','" . trim($_REQUEST['aws_access_key_id']) . "','" . trim($_REQUEST['aws_secret_key_id']) . "','" . trim($_REQUEST['merchant_id']) . "','" . trim($_REQUEST['market_place_id']) . "')";
        $ex = $pm->executeQuery($sql);

        $_SESSION['status'] = "key_inserted";
        header('location:amazon_key.php?success=inserted');
    }
}
