<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
ini_set('memory_limit', '1024M');

require_once("./amazon_sp_api/.config.inc.php"); // SP APU details and fetch credenatils

use Tops\AmazonSellingPartnerAPI\Api\OrdersApi;
use Tops\AmazonSellingPartnerAPI\Api\CatalogItemsApi20220401;


if (!empty($_SESSION['step3'])) {
    session_destroy();
    header('location:index.php');
}

$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');
        } elseif (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);
        } elseif (!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'] > 0) {
            $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";
            }
        } elseif ($_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['user_name'] = $log[0]['user_name'];
            $_SESSION['log'] = "true";
            header('Location:manage_questions.php');
        } else {
            $_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'];
    $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'];
    $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'];
    $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);
        $pm->executeQuery('update user set user_name="' . $receive_name . '",password="' . $recieve_password . '" where id="' . $id . '"');
    } else {
        $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'];
    $pm->executeQuery('delete from charity  where id="' . $receive_id . '"');
    echo json_encode(array("results" => "success"));
}

function insertCharity()
{
    $pm = AppManager::getPM();
    $receive_title = $_POST['mytxt'];
    $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 to handle errors
function handleErrors($errorMessage)
{
    $_SESSION['error'] = $errorMessage;
    header('Location: error.php');
    exit;
}

function isCheckAmazonOrderIsValid($order_id)
{

    $pm = AppManager::getPM();
    $order_client = new OrdersApi([
        'access_token' => SP_API_ACCESS_TOKEN,
        'access_key' => SP_API_ACCESS_KEY,
        'secret_key' => SP_API_SECRET_KEY,
        'region' => SP_API_AWS_REGION,
        'host' => SP_API_BASE_URL
    ]);


    // Fetch order details
    $ordersResponse = $order_client->getOrder($order_id);
    $ordersBuyerResponse = $order_client->getOrderBuyerInfo($order_id);
    $ordersAddressResponse = $order_client->getOrderAddress($order_id);

    // Check for errors
    if (empty($ordersResponse['payload']) || empty($ordersBuyerResponse['payload']) || empty($ordersAddressResponse['payload'])) {
        handleErrors("Something went wrong. Please try again with valid details.");
    }

    // Extract data from responses
    $list_orders_result = $ordersResponse['payload'];
    $list_orders_buyer_result = $ordersBuyerResponse['payload'];
    $list_orders_address_result = $ordersAddressResponse['payload'];

    $amazon_order_id = $list_orders_result['AmazonOrderId'];
    $amazon_order_status = $list_orders_result['OrderStatus'];

    // Extract customer address details
    $customer_address = $list_orders_address_result['ShippingAddress']['AddressLine1'];
    if (isset($list_orders_address_result['ShippingAddress']['AddressLine2'])) {
        $customer_address .= " " . $list_orders_address_result['ShippingAddress']['AddressLine2'];
    }

    $customer_city = $list_orders_address_result['ShippingAddress']['City'];
    $customer_state = $list_orders_address_result['ShippingAddress']['StateOrRegion'];
    $zip_code = $list_orders_address_result['ShippingAddress']['PostalCode'];

    $customer_name = $list_orders_buyer_result['BuyerName'];

    // Check if Amazon order ID matches
    if (!empty($amazon_order_id) && $amazon_order_id == $order_id) {
        // Fetch order items with retries
        $orderItemResponse = retryable(
            fn () => $order_client->getOrderItems($amazon_order_id),
            5,
            10
        );

        // Check if order items are available
        if (isset($orderItemResponse['payload']['OrderItems']) && !empty($orderItemResponse['payload']['OrderItems'])) {
            // Check if the order ID is present in the database
            $orderId = $pm->fetchResult("SELECT * FROM order_details WHERE status = 0 AND amazon_order_id = '$order_id'");

            if (!empty($orderId)) {
                $orderItems = $orderItemResponse['payload']['OrderItems'];

                // Process order items
                foreach ($orderItems as $orderItem) {
                    $asin = $orderItem['ASIN'];

                    if (!empty($asin)) {
                        $includedData = ["Images"];
                        $itemsImages = fetchCatalogItems($asin, $includedData);
                        $imageURL = getImageURL($itemsImages);

                        // Insert data into the database
                        $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);
                    }
                }

                // Set session variables
                $_SESSION["amazon_order_id"] = $orderId[0]['id'];
                $_SESSION["order_status"] = $amazon_order_status;
                $_SESSION["asin"] = $asin;  // Note: This will only store the last processed ASIN
                $_SESSION["Customer_name"] = $customer_name;
                $_SESSION["address"] = $customer_address;
                $_SESSION["city"] = $customer_city;
                $_SESSION["state"] = $customer_state;
                $_SESSION['zip_code'] = $zip_code;

                // Redirect to the next step
                header('Location: step_1.php');
            }
        }
    } else {
        // Amazon order ID does not match
        handleErrors("Order not found");
    }
}

// Function to retry an operation with a specified number of retries and interval
function retryable(callable $operation, int $maxRetries, int $retryInterval)
{
    $retries = 0;

    while ($retries < $maxRetries) {
        try {
            return $operation();
        } catch (Exception $e) {
            sleep($retryInterval);
            $retries++;
        }
    }

    // If all retries fail, rethrow the last exception
    throw $e;
}

// Function to fetch image URL based on specified conditions
function getImageURL($itemsImages)
{
    $imageURL = "";

    foreach ($itemsImages['images'] as $images) {
        if ($images['variant'] == 'MAIN' && $images['height'] === 500) {
            $imageURL = $images['link'];
            break;
        }
    }

    return $imageURL;
}

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 || !$pxml) {
        return "";
    }

    return !empty($pxml->Items->Item->LargeImage->URL) ? (string) $pxml->Items->Item->LargeImage->URL : '';
}

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

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

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']) . "'";
        $pm->executeQuery($sql);
        $_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']) . "')";
        $pm->executeQuery($sql);

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

function fetchCatalogItems($asinList, $includedData)
{
    try {
        // Create a CatalogItemsApi20220401 object with configuration options
        $objCatalog = new CatalogItemsApi20220401([
            'access_token' => SP_API_ACCESS_TOKEN,
            'access_key' => SP_API_ACCESS_KEY,
            'secret_key' => SP_API_SECRET_KEY,
            'region' => SP_API_AWS_REGION,
            'host' => SP_API_BASE_URL
        ]);

        $requestParams = [
            'marketplaceIds' => 'ATVPDKIKX0DER',
            'includedData' => implode(',', $includedData),
        ];

        // Make the API request to search for catalog items
        $itemResult = $objCatalog->getCatalogItem($requestParams, $asinList);

        // Check for errors in the API response
        if (isset($itemResult['errors'])) {
            throw new Exception("Something went wrong. Please try again later.");
        }

        // Check if there are results and populate the $items array
        return (!empty($itemResult['images'])) ? $itemResult['images'][0] : [];
    } catch (Exception $e) {
        $_SESSION['error'] = $e->getMessage();
        header('Location: error.php');
        exit;
    }
}
