<?php
defined($security_key) or exit;

//------------------------------------------
// Shopping Cart handler
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

//CONTENT FROM API (POST)
$post_content = json_decode($input,true);


//ENSURE PRODUCTROWID IS SEND
if (isset($post_content['product']) && $post_content['product'] != '' && isset($post_content['quantity']) && $post_content['quantity'] != ''){
    
    //ProductID
    $product_ID = $post_content['product'];

    // abs() function will prevent minus quantity and (int) will ensure the value is an integer (number)
    $quantity = abs((int)$post_content['quantity']);

    //GET CATALOG ITEM SEND
    $api_url = '/v2/catalog/product_id='.$product_ID;
    $products = ioApi($api_url,'',$clientsecret);
    $products = json_decode($products,true);
 
    //manage versions
    if (isset($post_content['version']) && $post_content['version'] !=''){
        foreach($products as $product){
         
            if ($product['version_id'] == $post_content['version']){
                $product_in_cart = $product;
            }
        }
    } else {
        $product_in_cart = $products[0];
    }

    $selected_options = $post_content['option'];
    $result = calculateTotalPrice($product_in_cart, $selected_options);
    $options_price = $result['total_price'] < 0 ? 0 : $result['total_price'];
    $options_weight = 0;
    $options =  $result['selected_items'];

    //------------------------------------------
    // ADD Product categories
    //------------------------------------------
    $cat_products = ioAPIv2('/v2/products_categories/status=1&product_id='.$product_ID,'',$clientsecret);
    $cat_products = json_decode($cat_products,true);
    
    $cat_input = '';
    foreach($cat_products as $cat_product_id){
        $cat_input .= $cat_product_id['rowID'].',';
    }
    $categories = substr($cat_input,0,-1);    
      

    $products_validated = [
        'id' => $product_in_cart['rowID'],
        'meta' => 
            [
            "img" => $product_in_cart['full_path'],
            "name" => $product_in_cart['productname'],
            "productcode" => $product_in_cart['productcode'],
            "category_ids" => $categories
            ],
        'quantity' => $quantity,
        'options' => [$options],
        'options_price' => str_replace(',', '.',str_replace('.', '', number_format($options_price, 2,",","."))),
        'options_weight' => $options_weight,
        'shipping_price' => 0.00
    ];
    
    //------------------------------------------
    //JSON_ENCODE
    //------------------------------------------
    $messages = json_encode($products_validated, JSON_UNESCAPED_UNICODE);

    //Send results
    echo $messages;
} 
else
{
    //------------------------------------------
    // Payload not correct
    //------------------------------------------ 
    http_response_code(400); // Payload not correct
}
?>