<?php
session_start();

if (!isset($_POST['submit'])) {
    exit('Fail!');
}
include('../../conf/conn.php');

if (!@$_SESSION["username"]) {
    $Tusername = date("Y-m-d H:i:s") . rand();
    $_SESSION["username"] = $Tusername;
    $_SESSION["Tusername"] = $Tusername;
    $_SESSION["id"] = rand();
}

//Function to create a div with css preset class.
function colorDiv($color, $char, $linebreak = false) {
    $color = empty($color) ? "Dark" : $color;
    $linebreak = $linebreak === true ? "<br>" : "";
    return "<div class=\"{$color}\">{$char}</div>{$linebreak}";
}

//Function to create chained divs using colorDiv()
function createLetterDivs($num, $wordBreak = 5) {
    $result = '';
    for ($i = 1; $i < $num + 1; $i++) {
        $break = false;
        if ($i % $wordBreak === 0)
            $break = true;
        $result .= colorDiv($_POST[$i . "color"], $_POST[$i . "tel"], $break);
    }
    return $result;
}

//A workaround to support both old(use product name) and new method(use id)
if (isset($_POST["productId"])) {
    $productId = mysqlSecurity($conn, $_POST["productId"]);
    $query = "select * from `products` where `id`='$productId'";
} else {
    $product_name = mysqlSecurity($conn, $_POST["name"]);
    $query = "select * from products where zh_name='$product_name'";
}

$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);

$amount = mysqlSecurity($conn, $_POST["quantity"]);
$username = $_SESSION["username"];
$id = $row["id"];
$image = $row["image"];
$price = $row["price"];
if (isset($row["original price"])) {
    $original_price = $row["original price"];
} else {
    $original_price = $row["price"];
}
$time = date("Y-m-d H:i:s");

//The method should run fine as long as $_GET['letter'] is a integer.
if (is_numeric($_GET['letter'])) {

    $letters = $_GET['letter'];

    $break = 5;
    if ($letters < 10)
        $break = 11;
    if ($letters == 30)
        $break = 6;

    $product_name = $_POST["name"] . "<br>";
    $product_name .= createLetterDivs($_GET['letter'], $break);
    $product_name = mysqlSecurity($conn, $product_name);

    $query = "select * from cart where username='$username' and product_name='$product_name'";
    $result = mysqli_query($conn, $query);
    if (!$row = mysqli_fetch_assoc($result)) {
        $_SESSION["page"] = 1;
        $query = "insert into cart(id,username,product_name,image,original_price,price,amount,time) values ('$id','$username','$product_name','$image','$original_price','$price','$amount','$time')";
        $result = mysqli_query($conn, $query);
    } else {
        $_SESSION["page"] = 1;
        $query = "select * from cart where username='$username' and product_name='$product_name'";
        $result = mysqli_query($conn, $query);
        $row = mysqli_fetch_assoc($result);
        $amount = $row["amount"] + $amount;
        $query = "UPDATE cart SET amount = '$amount' WHERE cart.username = '$username' and cart.product_name = '$product_name'";
        $result = mysqli_query($conn, $query);
        $addcartinfo = "1";
        $_SESSION["addcartinfo"] = $addcartinfo;
    }

    /*
     * A bypass for ajax query
     */
    if ($_GET['responseJSON'] == true) {
        die($result);
    }

    $url = "../e-shop.php";
    echo "<script language='javascript' 
	type='text/javascript'>";
    echo "window.location.href='$url'";
    echo "</script>";
}
?>
<html>
    <head>
        <!-- Facebook Pixel Code -->
        <script>
            !function (f, b, e, v, n, t, s) {
                if (f.fbq)
                    return;
                n = f.fbq = function () {
                    n.callMethod ?
                            n.callMethod.apply(n, arguments) : n.queue.push(arguments)
                };
                if (!f._fbq)
                    f._fbq = n;
                n.push = n;
                n.loaded = !0;
                n.version = '2.0';
                n.queue = [];
                t = b.createElement(e);
                t.async = !0;
                t.src = v;
                s = b.getElementsByTagName(e)[0];
                s.parentNode.insertBefore(t, s)
            }(window,
                    document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', '1251610718262776', {
                em: 'insert_email_variable,'
            });
            fbq('track', 'PageView');

            fbq('track', 'AddToCart');

        </script>
    <noscript><img height="1" width="1" style="display:none"
                   src="https://www.facebook.com/tr?id=1251610718262776&ev=PageView&noscript=1"
                   /></noscript>
    <!-- DO NOT MODIFY -->
    <!-- End Facebook Pixel Code -->

</head>
<body>
</body>
</html>