<?php
defined($security_key) or exit;
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);  
//------------------------------------------
// placeorder handler
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

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

//ENSURE CART, CHECK_OUT_INPUT AND CUSTOMER DATA IS SEND
if (isset($post_content['cart']) && isset($post_content['checkout_input']) && isset($post_content['customer_details'])){
   
    $errors = validateCheckoutData($post_content);
    
    //IF ERRORS RETURN
    if (!empty($errors)){
        $messages = [
            "error" => $errors
        ];
    } 
    else { 
    
    //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'],
        "payment_method" => $post_content['checkout_input']['payment_method']
    ];
    
    //Customer details
    $customer_details = [
        'account_id' => $post_content['customer_details']['account_id'] ?? '',
        'email' => $post_content['customer_details']['email'] ?? '',
        'first_name' => $post_content['customer_details']['first_name'] ?? '',
        'last_name' => $post_content['customer_details']['last_name'] ?? '',
        'address_street' => $post_content['customer_details']['address_street'] ?? '',
        'address_city' => $post_content['customer_details']['address_city'] ?? '',
        'address_state' => $post_content['customer_details']['address_state'] ?? '',
        'address_zip' => $post_content['customer_details']['address_zip'] ?? '',
        'address_country' => $post_content['customer_details']['address_country'] ?? '',
        'address_phone' => $post_content['customer_details']['address_phone'] ?? ''
    ];

    //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
    );

    //Recalculate the checkout
    $products_in_cart = $calculator->calculateTotals();

        $subtotal = $products_in_cart['totals']['subtotal'];
        $shippingtotal = $products_in_cart['totals']['shippingtotal'];
        $discounttotal = $products_in_cart['totals']['discounttotal'];
        $taxtotal = $products_in_cart['totals']['taxtotal'];
        $total = $products_in_cart['totals']['total'];

    //BUILD UP PARTNERHIERARCHY FROM USER
    $partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);

    // Generate unique transaction ID
    $txn_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5));
    
    // Insert transaction header
    $stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, address_phone, account_id, payment_method, shipping_method, shipping_amount, discount_amount, discount_code, tax_amount,accounthierarchy) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->execute([
        $txn_id,
        $total,
        0,
        $customer_details['email'],
        $customer_details['first_name'],
        $customer_details['last_name'],
        $customer_details['address_street'],
        $customer_details['address_city'],
        $customer_details['address_state'],
        $customer_details['address_zip'],
        $customer_details['address_country'],
        $customer_details['address_phone'],
        $customer_details['account_id'],
        $checkout_input['payment_method'],
        $checkout_input['selected_shipping_method'],
        $shippingtotal,
        $discounttotal,
        $checkout_input['discount_code'],
        $taxtotal,
        $partner_product
    ]);
    // Get order ID
    $transaction_id = $pdo->lastInsertId();

    //Insert transaction items
    foreach ($products_in_cart['cart_details']['products'] as $product) {
        // JSON_ENCODE OPTIONS
        $options = json_encode($product['options'],JSON_UNESCAPED_UNICODE) ?? '';
        // For every product in the shopping cart insert a new transaction_item
        $stmt = $pdo->prepare('INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options) VALUES (?,?,?,?,?)');
        $stmt->execute([$transaction_id, $product['id'], $product['options_price'], $product['quantity'], $options]);
    }

    //CHECK IF GIFTCARD IS USED AND THEN DISABLE IT
    if ($checkout_input['discount_code'] !=''){
        useGiftCart($pdo,$checkout_input['discount_code'],$partner_product);
    }

    //Return to checkout page
    $messages = [
        "id" => $transaction_id,
        "transaction_id" => $txn_id,
        "payment_amount" => $total,
        "payment_method" => $checkout_input['payment_method'],
        "products_checked-out" => $products_in_cart['cart_details'],
        "subtotal" => $subtotal,
        "discounttotal" => $discounttotal,
        "shippingtotal" => $shippingtotal,
        "taxtotal" => $taxtotal,
        "messages" => '',
        "error" => ''
    ];
    }

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

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