<?php

/*
 * Following code will list all the products
 */
// array for JSON response
$response = array();

// include db connect class
include("db_connect.php");

// connecting to db
$con = new DB_CONNECT();
$connection = $con->connect();

$connection->query("SET NAMES 'utf8'");

$connection->query("SET CHARACTER SET utf8");

$connection->query("SET SESSION collation_connection = 'utf8_unicode_ci'");

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');

header('Content-Type: application/json');


// get all products from products table
// Start Functionality  
$Req = $_GET;

if (isset($Req['cart_id'])&&!empty($Req['cart_id'])) {

    $cart_id = $Req['cart_id'];
    $quantity = $Req['quantity'];

    
    $query_select = $connection->query("SELECT * FROM `cart` WHERE `cart_id`='" . $cart_id . "' ORDER BY `cart_id` LIMIT 1");
    $row_select = mysqli_fetch_array($query_select);
    $size_id = $row_select['size_id'];
    $addition_id=$row_select['addition_id'];
    $get_size_price = get_size_price_from_id($size_id);
    $addition_price = 0;


    if ($addition_id != '') {
        $addition_id_all = explode(',', $addition_id);
        foreach ($addition_id_all as $one) {
            $get_addition_price = get_addition_price_from_id($one);
            $addition_price += $get_addition_price;
        }
    }

    $total = $get_size_price + $addition_price ;

    $total_price = $quantity * $total;
    $price = $total_price;

    $result = $connection->query("UPDATE `cart` SET `price`='$price',`quantity`='$quantity' WHERE `cart_id`='$cart_id'");


    $response["product"] = array();

    // temp user array
    $product = array();
    $product["cart_id"] = $cart_id;


    array_push($response["product"], $product);


    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "تم ألتحديث بنجاح.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "عفوا لقد حدث خطأ.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "هناك بيانات مفقوده برجاء مراجعة بياناتك";

    // echoing JSON response
    echo json_encode($response);
}
?>