<?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  
$postdata = file_get_contents("php://input");
//$postdata = '{"payment_id":"1","deliver_id":"1","vehicle_id":"1","client_id":"94","client_address_id":"2","cart_id":"344"}';

if (isset($postdata) && !empty($postdata)) {
    $Req = json_decode($postdata, TRUE);

    $payment = $Req['payment'];

    $deliver_id = $Req['deliver_id'];

    $client_id = $Req['client_id'];

    $client_address_id = $Req['client_address_id'];

    $cart_id = $Req['cart_id'];

    $lang = $Req['lang'];

    $session_id = $Req['session_id'];

    $mobile_type = $Req['mobile_type'];

    $mobile_version = $Req['mobile_version'];
    
    $order_time = $Req['order_time'];
    $order_date = $Req['order_date'];
    
    $order_now = $Req['order_now']?:1;

    $vat = check_vat();
    $get_order_price = orderPrice($cart_id);

    if ($client_address_id != '') {
        $get_region_id = get_region_id($client_id, $client_address_id);
        $branch_id = get_branch_from_region_id($get_region_id)? : get_branch();
        $get_charge = get_charge($get_region_id);
    } else {
        $get_charge = 0;
        $branch_id = $Req['branch_id'];
    }


    $cart_id_all = explode(',', $cart_id);

    $check_discount = check_discount();
    $discount_percentage = $check_discount ? get_discount_percentage() : 0;
    $total_amount_after_disc = $get_order_price - (($discount_percentage / 100) * $get_order_price);


    $total = $total_amount_after_disc + $get_charge;
    $vat_added = number_format((float) ( (($vat / 100) * $total_amount_after_disc)), 3, '.', '');
    $net_price_after_vat = number_format((float) ($total + (($vat / 100) * $total_amount_after_disc)), 3, '.', '');



    $result = $connection->query("INSERT INTO orders(order_now,order_time,order_date,cart_id,client_id,client_address_id,branch_id,total_price,charge_cost,discount_percentage,vat,vat_percentage,net_price,order_status,order_follow,payment,deliver_id,mobile_type,mobile_version,date) 
	VALUES('$order_now','$order_time','$order_date','$cart_id','$client_id','$client_address_id','$branch_id','$get_order_price','$get_charge','$discount_percentage','$vat_added','$vat','$net_price_after_vat','0','0','$payment','$deliver_id','$mobile_type','$mobile_version','" . date("Y-m-d H:i:s") . "')");

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

    $product = array();
    $product["order_id"] = $order_id = mysqli_insert_id($connection);

    foreach ($cart_id_all as $one) {
        $result_two = $connection->query("UPDATE cart SET `status`='1' WHERE `cart_id`='$one' ");
    }

    if ($payment == "credit") {

        $connection->query("UPDATE `payment` SET `order_id`='$order_id' where `payment_id`='$session_id' ");
    }

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

    if ($result) {

        $response["success"] = 1;
        if ($lang == "ar") {
            $response["message"] = "تم تأكيد الطلب بنجاح.";
        } else {
            $response["message"] = "Order Confirmed Successfully";
        }

        $to = "apps@emcan-group.com";
        $subject = "Al Dahiya Restaurant App - New Order";
        $headers = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        $headers .= 'From: orders@aldahiyabh.com'       . "\r\n" .
                 'Reply-To: orders@aldahiyabh.com' . "\r\n";
        $message = send_email($order_id, $client_id, $client_address_id, $branch_id);
        mail($to, $subject, $message, $headers);

        // $to = "soon@gmail.com";
        // $subject = "Al Dahiya Restaurant App - New Order";
        // $headers = 'MIME-Version: 1.0' . "\r\n";
        // $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        // $headers .= 'From: orders@aldahiyabh.com'       . "\r\n" .
        //          'Reply-To: orders@aldahiyabh.com' . "\r\n";
        // $message = send_email($order_id, $client_id, $client_address_id, $branch_id);
        // mail($to, $subject, $message, $headers);


        //echo json for mobile//
        echo json_encode($response);
    } else {
        $response["success"] = 0;
        if ($lang == "ar") {
            $response["message"] = "عفوا لقد حدث خطأ.";
        } else {
            $response["message"] = "Sorry, there was an error.";
        }
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    if ($lang == "ar") {
        $response["message"] = "هناك بيانات مفقوده برجاء مراجعة بياناتك";
    } else {
        $response["message"] = "Missing data Please review your data";
    }
    // echoing JSON response
    echo json_encode($response);
}
?>