<?php
defined($security_key) or exit;
//------------------------------------------
// Checkout 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['cart']) && isset($post_content['checkout_input'])){
     
    //CHECKOUT INPUT   
    $checkout_input = [
        "products_validated" => $post_content['cart'],
        "selected_country" => $post_content['checkout_input']['selected_country'],
        "selected_shipping_method" => $post_content['checkout_input']['selected_shipment_method'],
        "business_type" => $post_content['checkout_input']['business_type'],
        "discount_code" => $post_content['checkout_input']['discount_code']
    ];

    //Initialize calculator
    $calculator = new ShoppingCartCalculator(
        $checkout_input['products_validated'],
        $checkout_input['selected_country'],
        $checkout_input['selected_shipping_method'],
        $checkout_input['business_type'],
        $checkout_input['discount_code'],
        $pdo
    );

    // Get all calculations in one array
    $messages = $calculator->calculateTotals();

    //------------------------------------------
    //JSON_ENCODE
    //------------------------------------------
    $messages = json_encode($messages, JSON_UNESCAPED_UNICODE);

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