<?php
if (isset($_POST['check_approved_order_id'])) {
    include("../connection.php");
    $order_id = $_POST['check_approved_order_id'];
    $query_select = $con->query("SELECT * FROM `orders` WHERE `order_id`='" . $order_id . "' ORDER BY `order_id` limit 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $order_status = $row_select['order_status'];
    echo $order_status;
}

function check_client_exists_in_orders($client_id, $order_id)
{

    global $con;

    $query = $con->query("SELECT * FROM `orders` WHERE `client_id`='$client_id' AND `order_id`<'$order_id'");

    return mysqli_num_rows($query);
}

if (isset($_POST['send_client_id'])) {

    include("../connection.php");

    $client_id = $_POST['send_client_id'];
    $content = $_POST['send_content'];
    $message_type_id = $_POST['send_message_type_id'];
    $complaint_id = $_POST['send_complaint_id'];
    $query = $con->query("INSERT INTO `messages` VALUES (null,'$message_type_id','$content','$client_id','$complaint_id','0','0','" . date("Y-m-d H:i:s") . "')");
    if ($query) {
        $message_id = mysqli_insert_id($con);

//ارسال اشعار للعميل
        $devicesArray = " SELECT device_token.*,devices.* from `device_token` left join devices on devices.device_token_id =device_token.id  WHERE devices.client_id='{$client_id}' and devices.login =1";
        $query_devicesArray = $con->query($devicesArray);
        $devicesArray_count = mysqli_num_rows($query_devicesArray);
        if ($devicesArray_count > 0) {
            while ($v = mysqli_fetch_assoc($query_devicesArray)) {
                if ($v['device_token_id']) {
                    $data = array();
                    $data['title'] = 'تم الرد علي الشكوى أو الإقتراح';
                    $data['client_id'] = $client_id;
                    $data['type'] = 'message';

                    $addNotSend['client_id'] = $client_id;
                    $addNotSend['text'] = 'تم الرد علي الشكوى أو الإقتراح';
                    $addNotSend['type'] = 'reply';
                    $addNotSend['text_id'] = $message_id;

                    $params = array("pushtype" => $v['type'], "registration_id" => $v['device_token'], "data" => $data);
                    $rtn = sendMessage($params, $addNotSend);
                }
            }
        } else {
            $params = array("client_id" => $client_id, "type" => 'reply', "text_id" => $message_id, 'text' => 'تم الرد علي الشكوي أو الإقتراح');
            $sendnotify = insertIntoNotSend($params);
        }
        echo get_success("sent succesfully");
    }
}
if (isset($_POST['last'])) {
    include("../connection.php");
    $last = $_POST['last'];
    $branch_id = $_POST['branch_id'];
    $user_type = $_POST['user_type'];
    if ($user_type == 1) {
        $query_select = $con->query("SELECT * FROM `orders` where `order_id`>'$last'  ORDER BY `order_id` desc ");
    } else {
        $query_select = $con->query("SELECT * FROM `orders` where `order_id`>'$last' and `branch_id`='$branch_id' ORDER BY `order_id` desc ");
    }
    $order_count = mysqli_num_rows($query_select);
    echo $order_count;
    exit();
}

function lastOrder($branch_id, $user_type)
{
    global $con;
    if ($user_type == 1) {
        $query_select = $con->query("SELECT * FROM `orders`  ORDER BY `order_id` desc LIMIT 1 ");
    } else {
        $query_select = $con->query("SELECT * FROM `orders` where `branch_id`='$branch_id' ORDER BY `order_id` desc LIMIT 1 ");
    }
    $row_select = mysqli_fetch_array($query_select);
    $order_id = $row_select['order_id'];
    return $order_id;
}

function get_deliver_name($deliver_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `delivered_way` where `id`='$deliver_id' ORDER BY `id` desc LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $name_en = $row_select['name_en'];
    return $name_en;
}

function order_count()
{

    global $con;

    $query = $con->query("SELECT * FROM `orders`  ORDER BY `order_id` ASC");

    $order_count = mysqli_num_rows($query);

    return $order_count;
}

function new_order_count()
{

    global $con;

    $query = $con->query("SELECT * FROM `orders` where `order_status`=0  ORDER BY `order_id` ASC");

    $order_count = mysqli_num_rows($query);

    return $order_count;
}

function getPrice($size_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `sub_categories_size_prices` WHERE `sub_category_size_price_id`='" . $size_id . "' ORDER BY `sub_category_size_price_id` LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $sub_category_size_price = $row_select['sub_category_size_price'];
    return $sub_category_size_price;
}

function getAdditionPrice($addition_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `sub_categories_addition_prices` WHERE `sub_category_addition_price_id`='" . $addition_id . "' ORDER BY `sub_category_addition_price_id` LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $sub_category_addition_price = $row_select['sub_category_addition_price'];
    return $sub_category_addition_price;
}

function add_order($temp)
{
    global $con;
    $address_id = $temp['client_address_id'];
    $region_id = get_region_by_client_address($temp['client_id'], $address_id);
    $getChargeRegionId = getChargeRegionId($region_id);

    $getorderprice = getPrice($temp['size_id']);
    $addition_itr = $temp['addition_itr'];
    $remove_itr = $temp['remove_itr'];

    $getadditionprice_all = 0;
    $all_additions;
    $all_removes;
    for ($x = 0; $x <= $addition_itr; $x++) {
        if ($temp['addition_id_' . $x] != '') {
            $getadditionprice = getAdditionPrice($temp['addition_id_' . $x]);
            $getadditionprice_all += $getadditionprice;
            $all_additions .= $temp['addition_id_' . $x] . ',';
        }
    }

    $all_additions = substr($all_additions, 0, -1);
    for ($y = 0; $y <= $remove_itr; $y++) {
        if ($temp['remove_id_' . $y] != '') {
            $all_removes .= $temp['remove_id_' . $y] . ',';
        }
    }
    $all_removes = substr($all_removes, 0, -1);

    $total = $getorderprice + $getadditionprice_all;
    $sum = $total * $temp['quantity'];
    $con->query("INSERT INTO `cart` VALUES (null,'" . $temp['sub_category_id'] . "','" . $temp['size_id'] . "','$all_additions','" . $temp['quantity'] . "','$sum','" . $temp['client_id'] . "','$all_removes','1')");

    $cart_id = mysqli_insert_id($con);
    if ($cart_id) {
        $con->query("INSERT INTO `orders` VALUES (null,'$cart_id','" . $temp['client_id'] . "','" . $temp['client_address_id'] . "','$getChargeRegionId','1','1','" . $temp['payment'] . "','" . date("Y-m-d H:i:s") . "')");
    }
    return mysqli_insert_id($con);
}

function last_orders($aStart = 0, $aLimit = 0, $get)
{

    global $con;
    $last_orders = array();
    if ($_SESSION['user_type'] == 1) {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id  where ((`orders`.`order_status`=1 and  `orders`.`order_follow`=3) or `orders`.`order_status`=2)  ";
    } else {
        $sql = " SELECT * FROM `orders` left join clients on clients.client_id=orders.client_id  where ((`orders`.`order_status`=1 and  `orders`.`order_follow`=3) or `orders`.`order_status`=2) and `orders`.`branch_id`='" . $_SESSION['branch_id'] . "' ";
    }
    if (!empty($get['order_id'])) {
        $sql .= " and `orders`.order_id='" . $get['order_id'] . "'";
    }
    if (!empty($get['client_phone'])) {
        $sql .= " and `clients`.client_phone='" . $get['client_phone'] . "'";
    }
    $sql .= " ORDER BY `order_id` DESC ";
    $sql .= $aLimit ? "LIMIT {$aStart},{$aLimit}" : "";
    $query_select = $con->query($sql);
    $x = 1;

    while ($row = mysqli_fetch_assoc($query_select)) {
        array_push($last_orders, $row);

        $x++;
    }
    return $last_orders;
}

function client_orders($aStart = 0, $aLimit = 0)
{

    global $con;
    $last_orders = array();
    if ($_SESSION['user_type'] == 1) {
        $sql = " SELECT * FROM `orders` where client_id='" . $_GET['client_id'] . "'  ";
    } else {
        $sql = " SELECT * FROM `orders` where  client_id='" . $_GET['client_id'] . "' and `branch_id`='" . $_SESSION['branch_id'] . "' ";
    }
    $sql .= " ORDER BY `order_id` DESC ";
    $sql .= $aLimit ? "LIMIT {$aStart},{$aLimit}" : "";
    $query_select = $con->query($sql);
    $x = 1;

    while ($row = mysqli_fetch_assoc($query_select)) {
        array_push($last_orders, $row);

        $x++;
    }
    return $last_orders;
}

function client_orders_count()
{

    global $con;

    if ($_SESSION['user_type'] == 1) {
        $query = $con->query("SELECT * FROM `orders` where  client_id='" . $_GET['client_id'] . "'  ORDER BY `order_id` ASC");
    } else {
        $query = $con->query("SELECT * FROM `orders` where client_id='" . $_GET['client_id'] . "' and  `branch_id`='" . $_SESSION['branch_id'] . "'  ORDER BY `order_id` ASC");
    }

    $order_count = mysqli_num_rows($query);

    return $order_count;
}

function last_orders_count($get)
{

    global $con;
    if ($_SESSION['user_type'] == 1) {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id where ((`orders`.`order_status`=1 and  `orders`.`order_follow`=3) or `orders`.`order_status`=2)  ";
    } else {
        $sql = " SELECT * FROM `orders` left join clients on clients.client_id=orders.client_id  where ((`orders`.`order_status`=1 and  `orders`.`order_follow`=3) or `orders`.`order_status`=2) and `orders`.`branch_id`='" . $_SESSION['branch_id'] . "' ";
    }
    if (!empty($get['order_id'])) {
        $sql .= " and `orders`.order_id='" . $get['order_id'] . "'";
    }
    if (!empty($get['client_phone'])) {
        $sql .= " and `clients`.client_phone='" . $get['client_phone'] . "'";
    }
    $query = $con->query($sql);
    $order_count = mysqli_num_rows($query);

    return $order_count;
}

function get_charge($region_id)
{
    global $con;

    $result = $con->query("SELECT * FROM `regions` WHERE `region_id`='$region_id'  ORDER BY `region_id` DESC limit 1");

    $row = mysqli_fetch_array($result);

    $charge = $row['charge'];

    return $charge;
}

function get_region($region_id)
{
    global $con;

    $result = $con->query("SELECT * FROM `regions` WHERE `region_id`='$region_id'  ORDER BY `region_id` DESC limit 1");

    $row = mysqli_fetch_array($result);

    $region_name_en = $row['region_name_en'];

    return $region_name_en;
}

function get_region_by_client_address($client_id, $client_address_id)
{
    global $con;

    $result = $con->query("SELECT * FROM `client_addresses` WHERE `client_address_id`='$client_address_id' and `client_id`='$client_id' ORDER BY `client_address_id` DESC limit 1");

    $row = mysqli_fetch_array($result);

    $region = $row['region'];

    return $region;
}

function get_sub_category_name($sub_category_id)
{
    global $con;

    $query_select_two = $con->query("SELECT * FROM `sub_categories` WHERE `sub_category_id`='" . $sub_category_id . "' ORDER BY `sub_category_id` DESC");
    $row_select_two = mysqli_fetch_assoc($query_select_two);
    $sub_category_name = $row_select_two['sub_category_name'];

    return $sub_category_name;
}

function current_order_count($get)
{

    global $con;
    if ($_SESSION['user_type'] == 1) {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id  where (`orders`.`order_follow`!=3 and `orders`.`order_follow`!=0 or `orders`.`order_status`=0  )  ";
    } else {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id  where ( (`orders`.`order_follow`!=3 and `orders`.`order_follow`!=0 ) or `orders`.`order_status`=0 ) and `orders`.`branch_id`='" . $_SESSION['branch_id'] . "' ";
    }

    if (!empty($get['order_id'])) {
        $sql .= "and `orders`.order_id='" . $get['order_id'] . "'";
    }
    if (!empty($get['client_phone'])) {
        $sql .= " and `clients`.client_phone='" . $get['client_phone'] . "'";
    }
    if (isset($_GET['client_id'])) {
        $sql .= " and `orders`.client_id='" . $get['client_id'] . "'";
    }
    $query = $con->query($sql);

    $order_count = mysqli_num_rows($query);

    return $order_count;
}

function view_client_order($aStart = 0, $aLimit = 0)
{
    global $con;
    $orders1 = array();
    if (isset($_GET['client_id'])) {

        $client_id = $_GET['client_id'];
        if ($_SESSION['user_type'] == 1) {
            $sql = " SELECT * FROM `orders` where `client_id` = '$client_id'";
        } else {
            $sql = " SELECT * FROM `orders` where `branch_id`='" . $_SESSION['branch_id'] . "') and `client_id` = '$client_id' ";
        }
    }
    $sql .= " ORDER BY `order_id` ";
    $sql .= $aLimit ? "LIMIT {$aStart},{$aLimit}" : "";
    $query_select = $con->query($sql);
    $x = 1;
    while ($row = mysqli_fetch_assoc($query_select)) {
        array_push($orders1, $row);

        $x++;
    }

    return $orders1;
}

function view_order($aStart = 0, $aLimit = 0, $get)
{

    global $con;
    $orders = array();
    if ($_SESSION['user_type'] == 1) {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id  where (`orders`.`order_follow`!=3 and `orders`.`order_follow`!=0 or `orders`.`order_status`=0 )  ";
    } else {
        $sql = " SELECT `clients`.`client_phone`, `orders`.* FROM `orders` left join clients on clients.client_id=orders.client_id  where ( (`orders`.`order_follow`!=3 and `orders`.`order_follow`!=0 ) or `orders`.`order_status`=0 ) and `orders`.`branch_id`='" . $_SESSION['branch_id'] . "' ";
    }

    if (!empty($get['order_id'])) {
        $sql .= "and `orders`.order_id='" . $get['order_id'] . "'";
    }


    if (!empty($get['client_phone'])) {
        $sql .= " and `clients`.client_phone='" . $get['client_phone'] . "'";
    }

    $sql .= " ORDER BY `order_id` DESC ";
    $sql .= $aLimit ? "LIMIT {$aStart},{$aLimit}" : "";
    $query_select = $con->query($sql);
    $x = 1;
    while ($row = mysqli_fetch_assoc($query_select)) {
        array_push($orders, $row);

        $x++;
    }
    return $orders;
}

function get_client_name_by_id($client_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `clients` WHERE `client_id`='" . $client_id . "' ORDER BY `client_id` LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $client_name = $row_select['client_name'];
    return $client_name;
}

function get_client_id($cart_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `cart` WHERE `cart_id`='" . $cart_id . "' ORDER BY `cart_id` LIMIT 1 ");

    $row_select = mysqli_fetch_array($query_select);
    $client_id = $row_select['client_id'];
    return $client_id;
}

function get_client_phone_by_id($client_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `clients` WHERE `client_id`='" . $client_id . "' ORDER BY `client_id` LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $client_phone = $row_select['client_phone'];
    return $client_phone;
}

function get_order_reason_deleted($order_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `order_delete_reason` WHERE `order_id`='$order_id' ");
    $row_select = mysqli_fetch_array($query_select);
    $delete_reason = $row_select['delete_reason'];
    return $delete_reason;
}

function get_order_reason_edited($order_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `order_edit_reason` WHERE `order_id`='$order_id' ");
    $row_select = mysqli_fetch_array($query_select);
    $edit_reason = $row_select['edit_reason'];
    return $edit_reason;
}

function get_client_address_by_id($client_address_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `client_addresses` WHERE `client_address_id`='" . $client_address_id . "'  LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    return $row_select;
}

function get_branche_Name($branche_id)
{

    global $con;

    $query_select = $con->query("SELECT * FROM `branches` WHERE `id`='$branche_id' ORDER BY `id` LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);
    $name = $row_select['name'];
    return $name;
}

function get_client_address($client_address_id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `client_addresses` WHERE `client_address_id`='" . $client_address_id . "'  LIMIT 1 ");
    $row_select = mysqli_fetch_array($query_select);

    return $row_select;

}

function getUserSessionDataById($id)
{
    global $con;
    $query_select = $con->query("SELECT * FROM `user_addresses_session` WHERE `user_id`='$id' ");
    $data = array();
    while ($row = mysqli_fetch_assoc($query_select)) {
        $region_id = $row['region'];
        $row['region'] = get_region($region_id);
        $data = $row;
    }
    return $data;
}


if (isset($_POST['get_order']) && $_POST['get_order'] != '') {
    include("../connection.php");
    $order_id = $_POST['get_order'];
    ?>
    <div class="getLogo" style="width:150px;height:150px; !important;">
        <img src="../uploads/logo.jpeg"/>
    </div>
    <?php
    $query = $con->query("SELECT * FROM `orders` WHERE `order_id`='" . $order_id . "' ORDER BY `order_id` DESC");
    $row_select = mysqli_fetch_assoc($query);
    $cart_id = $row_select['cart_id'];
    $order_id = $row_select['order_id'];
    $payment = $row_select['payment'];
    $client_id = $row_select['client_id'];
    $client_address_id = $row_select['client_address_id'];
    $charge_cost = $row_select['charge_cost'];
    $net_price = $row_select['net_price'];
    $order_date = $row_select['order_date'];
    $order_time = $row_select['order_time'];
    $web = ($row_select['mobile_type'] == 'Web') ? true : false;
    if ($web)
        $user_data = getUserSessionDataById($client_id);


    $order_now = $row_select['order_now'];

    $discount_percentage = $row_select['discount_percentage'];
    $get_client_address = get_client_address($client_address_id);
    $searchComma = ',';
    $vat = $row_select['vat'];
// echo date("Y-m-d H:i:s");

    $cart_id = explode(',', trim($cart_id, ','));
    $branch_id = $row_select['branch_id'];
    ?>

    <div class="getOrder">
        <p><?php echo get_branche_Name($branch_id); ?> Branch </p>

        <p>Order Details </p>

        <table class="table table-striped ">
            <thead>
            <tr>
                <th>Image</th>
                <th>Product</th>
                <th>Size</th>
                <th>Addition</th>
                <th>Removes</th>
                <th>Notes</th>
                <th>Product Price</th>
                <th>Addition Price</th>
                <th>Quantity</th>
                <th>Sum</th>
            </tr>
            </thead>
            <tbody>

            <?php
            $index = 1;

            foreach ($cart_id as $one) {
                //                echo $carts_array[$i];
                $query_select = $con->query("SELECT * FROM `cart` WHERE `cart_id`=$one  ORDER BY `cart_id` LIMIT 1");

                $row_select = mysqli_fetch_array($query_select);

                $sub_category_id = $row_select['sub_category_id'];
                $note = $row_select['note'];

                $size_id = $row_select['size_id'];
                $additions_id = $row_select['addition_id'];
                $quantity = $row_select['quantity'];
                $price = $row_select['price'];
                $removes_id = $row_select['remove_id'];
                $spicy_type = $row_select['spicy_type'];
                $potato_id = $row_select['potato_id'];
                $drink_id = $row_select['drink_id'];
                $type = $row_select['type'];

                $query_select_two = $con->query("SELECT * FROM `sub_categories` WHERE `sub_category_id`='" . $sub_category_id . "' ORDER BY `sub_category_id` DESC");
                $row_select_two = mysqli_fetch_assoc($query_select_two);
                $sub_category_name = $row_select_two['sub_category_name'];
                $sub_category_image = $row_select_two['sub_category_image'];

                $query_select_three = $con->query("SELECT * FROM `sub_categories_size_prices` WHERE `sub_category_size_price_id`='" . $size_id . "' ORDER BY `sub_category_size_price_id` DESC");
                $row_select_three = mysqli_fetch_assoc($query_select_three);
                $sub_category_size_name = $row_select_three['sub_category_size_name'];
                $sub_category_size_price = $row_select_three['sub_category_size_price'];
                ?>

                <tr>

                    <td>
                        <div style="margin-right: -77px!important;margin-top: -7px!important;"
                             class="gal-detail thumb getImage">
                            <a href="<?php echo $sub_category_image; ?>" class="image-popup-2" title="">
                                <img src="<?php echo $sub_category_image; ?>"
                                     style="width: 50px!important;height: 50px!important;" class="thumb-img" alt="">
                            </a>
                        </div>
                    </td>

                    <td><?php echo $sub_category_name; ?></td>
                    <td><?php echo $sub_category_size_name; ?></td>
                    <td><?php
                        if (empty($additions_id)) {
                            echo "No";
                        } else {
                            echo get_size_additions_names_by_id($additions_id);
                        }
                        ?></td>

                    <td><?php
                        if (empty($removes_id)) {
                            echo "No";
                        } else {
                            echo get_removes_names_by_id($removes_id);
                        }
                        ?></td>
                    <td><?php
                        if (empty($note)) {
                            echo "No Notes";
                        } else {
                            echo $note;
                        } ?>
                    </td>
                    <td style="direction:ltr;"><?php echo number_format((float)$sub_category_size_price, 3, '.', ''); ?>
                        BD
                    </td>
                    <td style="direction:ltr;"><?php echo number_format((float)get_size_additions_price_by_id($additions_id), 3, '.', ''); ?>
                        BD
                    </td>
                    <td><?php echo $quantity; ?></td>
                    <td style="direction:ltr;"><?php echo number_format((float)$price, 3, '.', ''); ?> BD</td>
                </tr>

                <?php
                $index++;
            }
            ?>
            </tbody>
        </table>
    </div>

    <div class="getAddress">
        <table class="table table-striped ">
            <thead>
            <tr>
                <th>Order Id</th>
                <th> Order <?= $order_now == 2 ? "Later" : "Now" ?> </th>
                <th>Client Name</th>
                <th>Client Phone</th>
                <th>Region Name</th>
                <th>Block</th>
                <th>Road</th>
                <th>Building</th>
                <th>Flat</th>
                <th>Notes</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td><?php echo $order_id; ?></td>
                <td><?= $order_now == 2 ? $order_date . ' ' . $order_time : $order_time ?></td>
                <?php if ($web) { ?>
                    <td><?php echo $user_data['name']; ?></td>
                    <td><?php echo $user_data['phone']; ?></td>
                    <td><?php echo $user_data['region']; ?></td>
                    <td><?php echo $user_data['block']; ?></td>
                    <td><?php echo $user_data['road']; ?></td>
                    <td><?php echo $user_data['building']; ?></td>
                    <td><?php echo $user_data['flat_number']; ?> </td>
                    <td><?php echo $user_data['note']; ?> </td>
                <?php } else { ?>
                    <td><?php echo get_client_name_by_id($client_id); ?></td>
                    <td><?php echo get_client_phone_by_id($client_id); ?></td>
                    <td><?php echo get_region($get_client_address['region']); ?></td>
                    <td><?php echo $get_client_address['block']; ?></td>
                    <td><?php echo $get_client_address['road']; ?></td>
                    <td><?php echo $get_client_address['building']; ?></td>
                    <td><?php echo $get_client_address['flat_number']; ?> </td>
                    <td><?php echo $get_client_address['note']; ?> </td>
                <?php } ?>
            </tr>
            </tbody>
        </table>
    </div>


    <div class="getTotal" style="float:left;width:90%">
        <table class="table table-striped ">
            <thead>
            <tr>
                <th>Price(BD)</th>
                <th> discount(%)</th>
                <th>Price(BD)</th>
                <th> Vat(BD)</th>
                <th> Price(BD)</th>

                <th>Charge(BD)</th>

                <th>Payment</th>
                <th>Total (BD)</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td style=""><?php echo number_format((float)totalPrice($order_id), 3, '.', ''); ?></td>
                <td style="direction:ltr;"><?php echo $discount_percentage; ?></td>
                <td style="direction:ltr;"><?php echo number_format((float)(($net_price - $charge_cost) - $vat), 3, '.', ''); ?></td>
                <td style="direction:ltr;"><?php echo $vat; ?></td>
                <td style="direction:ltr;"><?php echo $net_price - $charge_cost; ?></td>
                <td style="direction:ltr;"><?php echo number_format((float)$charge_cost, 3, '.', ''); ?></td>

                <td><?php
                    if ($payment == 'cash') {
                        echo $payment;
                    } elseif ($payment == "credit") {
                        echo "Online-Credit";
                    } elseif ($payment == "debit") {
                        echo "Online-Debit";
                    } else {
                        echo $payment;
                    }
                    ?></td>
                <td style="direction:ltr;"><?php echo number_format((float)$net_price, 3, '.', ''); ?></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="clearfix"></div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <!--<button id="btnPrint" type="button" class="btn btn-default btnPrint"> Print Details </button>-->
        <!--<button id=""  type="button" class="btnPrintNew btn btn-default" data-id="<?php echo $order_id; ?>" > Print Bill </button>-->

    </div>


    <script>

        document.getElementById("btnPrint").onclick = function () {
            printElement(document.getElementById("printThis"));
        }

        function printElement(elem) {
            var domClone = elem.cloneNode(true);
            var $printSection = document.getElementById("printSection");
            if (!$printSection) {
                var $printSection = document.createElement("div");
                $printSection.id = "printSection";
                document.body.appendChild($printSection);
            }

            $printSection.innerHTML = "";
            $printSection.appendChild(domClone);
            window.print();
        }


        $('body').on('click', '.btnPrintNew', function () {
            var order_id = $(this).attr("data-id");
            window.location = 'print_receipt.php?order_id=' + order_id;
        });

    </script>


    <script type="text/javascript">
        $(document).ready(function () {
            $('.image-popup-2').magnificPopup({
                type: 'image',
                closeOnContentClick: true,
                mainClass: 'mfp-fade',
                gallery: {
                    enabled: true,
                    navigateByImgClick: true,
                    preload: [0, 1] // Will preload 0 - before current, and 1 after the current image
                }
            });
        });
    </script>
    <?php
}

// Get Total Names Of Additions For Each Size
function get_size_additions_names_by_id($additions_id)
{

    global $con;

    $get_additions_id = explode(',', $additions_id);

    foreach ($get_additions_id AS $add_id) {

        $query_addition = $con->query("SELECT * FROM `sub_categories_addition_prices` WHERE `sub_category_addition_price_id`='$add_id' ORDER BY `sub_category_addition_price_id` DESC");

        $row_addition = mysqli_fetch_assoc($query_addition);

        echo $additions_name = $row_addition['sub_category_addition_name'] . " + ";
    }
}

function get_side_names_by_id($side_id)
{

    global $con;

    $get_side_id = explode(',', $side_id);

    foreach ($get_side_id AS $rem_id) {

        $query = $con->query("SELECT * FROM `sides` WHERE `id`='$rem_id' ORDER BY `id` DESC");

        $row = mysqli_fetch_assoc($query);

        echo $name = $row['title'] . " + ";
    }
}

// Get Total Names Of Additions For Each Size
function get_removes_names_by_id($removes_id)
{

    global $con;

    $get_removes_id = explode(',', $removes_id);

    foreach ($get_removes_id AS $rem_id) {

        $query_removes = $con->query("SELECT * FROM `removes` WHERE `id`='$rem_id' ORDER BY `id` DESC");

        $row_remove = mysqli_fetch_assoc($query_removes);

        echo $remove_name = $row_remove['title'] . " + ";
    }
}

function get_size_additions_price_by_id($additions_id)
{

    global $con;

    $get_additions_id = explode(',', $additions_id);
    $sum_all = 0;
    foreach ($get_additions_id AS $add_id) {

        $query_addition = $con->query("SELECT * FROM `sub_categories_addition_prices` WHERE `sub_category_addition_price_id`='$add_id' ORDER BY `sub_category_addition_price_id` DESC");

        $row_addition = mysqli_fetch_assoc($query_addition);
        $sub_category_addition_price = $row_addition['sub_category_addition_price'];
        $sum_all += $sub_category_addition_price;
    }
    return $sum_all;
}

// Get Total Amount Of Additions For Each Size
function get_size_additions_by_id_for_admin($additions_id)
{

    global $con;

    $get_additions_id = explode(',', $additions_id);

    $additions_name = array();

    $additions_price = array();

    foreach ($get_additions_id AS $add_id) {

        $query_addition = $con->query("SELECT * FROM `sub_categories_addition_prices` WHERE `sub_category_addition_price_id`='$add_id' ORDER BY `sub_category_addition_price_id` DESC");

        $row_addition = mysqli_fetch_assoc($query_addition);

        $additions_name[] = $row_addition['sub_category_addition_name'];

        $additions_price[] = $row_addition['sub_category_addition_price'];
    }

    $additions_total_name = array_sum($additions_name);

    $additions_total_amount = array_sum($additions_price);

    return array($additions_total_amount, $additions_total_name);
}

// Get Total Amount For Client Orders 
function get_order_total_price_by_id($order_id)
{

    global $con;

    $mos = array();

    $query_total = $con->query("SELECT * FROM `order_size_price` LEFT JOIN `sub_categories_size_prices` ON `order_size_price`.`sub_category_size_price_id` = `sub_categories_size_prices`.`sub_category_size_price_id` 
	WHERE `order_size_price`.`order_id`='" . $order_id . "' ORDER BY `order_size_price_id` DESC");

    while ($row_total = mysqli_fetch_assoc($query_total)) {

        $mos[] = $row_total['sub_category_size_price'];

        $additions_id = $row_total['additions_id'];

        $additions_total_amounts = get_size_additions_by_id_for_admin($additions_id);

        $additions_total_amount[] = $additions_total_amounts[0];
    }
    $total = array_sum($mos) + array_sum($additions_total_amount);
    echo $total;
}

function totalPrice($order_id)
{
    global $con;

    $query_select = $con->query("SELECT * FROM `orders` WHERE `order_id`='" . $order_id . "' ORDER BY `order_id` DESC");

    while ($row_select = mysqli_fetch_assoc($query_select)) {

        $cart_id = $row_select['cart_id'];


        $carts_array = explode(",", $cart_id);
        $result = count($carts_array);
        $price = 0;
        foreach ($carts_array as $one_cart) {
            $query_select = $con->query("SELECT * FROM `cart` WHERE `cart_id`='" . $one_cart . "' ORDER BY `cart_id` LIMIT 1");

            $row_select = mysqli_fetch_array($query_select);

            $price += $row_select['price'];
        }
        return $price;
    }
}

if (isset($_POST['verify'])) {

    include("../connection.php");

    $verify = $_POST['verify'];
    $client_id = $_POST['client_id'];

    $query = $con->query("UPDATE `orders` SET `order_status`=1 , `order_follow`=1 WHERE `order_id`='$verify'");

//ارسال اشعار للعميل
    $devicesArray = " SELECT device_token.*,devices.* from `device_token` left join devices on devices.device_token_id =device_token.id  WHERE devices.client_id='{$client_id}' and devices.login =1";
    $query_devicesArray = $con->query($devicesArray);
    $devicesArray_count = mysqli_num_rows($query_devicesArray);
    if ($devicesArray_count > 0) {
        while ($v = mysqli_fetch_assoc($query_devicesArray)) {
            if ($v['device_token_id']) {
                $data = array();
                $data['title'] = 'Your order Approved';
                $data['client_id'] = $client_id;
                $data['type'] = 'order';

                $addNotSend['client_id'] = $client_id;
                $addNotSend['text'] = 'Your order Approved';
                $addNotSend['type'] = 'order';
                $addNotSend['text_id'] = $verify;

                $params = array("pushtype" => $v['type'], "registration_id" => $v['device_token'], "data" => $data);
                $rtn = sendMessage($params, $addNotSend);
            }
        }
    } else {
        $params = array("client_id" => $client_id, "type" => 'order', "text_id" => $verify, 'text' => 'تم إعتماد طلبك ');
        $sendnotify = insertIntoNotSend($params);
    }
    if ($query) {
// echo get_success("تم التفعيل بنجاح");
    }
}

if (isset($_POST['cancel_verify'])) {

    include("../connection.php");

    $cancel_verify = $_POST['cancel_verify'];
    $client_id = $_POST['client_id'];

    $query = $con->query("UPDATE `orders` SET `order_status`=2,`order_follow`='0' WHERE `order_id`='$cancel_verify'");

//ارسال اشعار للعميل
    $devicesArray = " SELECT device_token.*,devices.* from `device_token` left join devices on devices.device_token_id =device_token.id  WHERE devices.client_id='{$client_id}' and devices.login =1";
    $query_devicesArray = $con->query($devicesArray);
    $devicesArray_count = mysqli_num_rows($query_devicesArray);
    if ($devicesArray_count > 0) {
        while ($v = mysqli_fetch_assoc($query_devicesArray)) {


            if ($v['device_token_id']) {
                $data = array();
                $data['title'] = 'Your order Cancelled';
                $data['client_id'] = $client_id;
                $data['type'] = 'order';

                $addNotSend['client_id'] = $client_id;
                $addNotSend['text'] = 'Your order Cancelled';
                $addNotSend['type'] = 'order';
                $addNotSend['text_id'] = $cancel_verify;

                $params = array("pushtype" => $v['type'], "registration_id" => $v['device_token'], "data" => $data);
                $rtn = sendMessage($params, $addNotSend);
            }
        }
    } else {
        $params = array("client_id" => $client_id, "type" => 'order', "text_id" => $cancel_verify, 'text' => 'Your order Cancelled');
        $sendnotify = insertIntoNotSend($params);
    }
    if ($query) {
//        echo get_success("تم إلغاء الإعتماد بنجاح");
    }
}


if (isset($_POST['edit_follow']) && isset($_POST['order_id'])) {

    include("../connection.php");

    $edit_follow = $_POST['edit_follow'];
    $order_id = $_POST['order_id'];
    $client_id = $_POST['client_id'];
    $deliver_type = $_POST['deliver_type'];

    $query = $con->query("UPDATE `orders` SET `order_follow`='$edit_follow' WHERE `order_id`='$order_id'");

//ارسال اشعار للعميل
    $devicesArray = " SELECT device_token.*,devices.* from `device_token` left join devices on devices.device_token_id =device_token.id  WHERE devices.client_id='{$client_id}' and devices.login =1";
    $query_devicesArray = $con->query($devicesArray);
    $devicesArray_count = mysqli_num_rows($query_devicesArray);
    if ($devicesArray_count > 0) {
        while ($v = mysqli_fetch_assoc($query_devicesArray)) {


            if ($v['device_token_id']) {
                $data = array();
                if ($edit_follow == '2') {
                    if ($deliver_type != 1) {
                        $data['title'] = 'Your order under processing';
                    } else {
                        $data['title'] = 'Your order with the delivery man';
                    }
                } elseif ($edit_follow == '3') {
                    $data['title'] = 'Your order has been Delivered';
                } elseif ($edit_follow == '1') {
                    $data['title'] = 'Your order under processing';
                }

                $data['msgcnt'] = '1';
                $data['client_id'] = $client_id;
                $data['type'] = 'order';

                $addNotSend['client_id'] = $client_id;
                if ($edit_follow == '2') {
                    if ($deliver_type != 1) {
                        $addNotSend['text'] = 'Your order under processing';
                    } else {
                        $addNotSend['text'] = 'Your order with the delivery man';
                    }
                } elseif ($edit_follow == '3') {
                    $addNotSend['text'] = 'Your order has been Delivered';
                } elseif ($edit_follow == '1') {
                    $addNotSend['text'] = 'Your order under processing';
                }
                $addNotSend['type'] = 'order';
                $addNotSend['text_id'] = $order_id;


                $params = array("pushtype" => $v['type'], "registration_id" => $v['device_token'], "data" => $data);
                $rtn = sendMessage($params, $addNotSend);
            }
        }
    } else {
        if ($edit_follow == '2') {
            if ($deliver_type != 1) {
                $text = 'Your order under processing';
            } else {
                $text = 'Your order with the delivery man';
            }
        } elseif ($edit_follow == '3') {
            $text = 'Your order has been Delivered';
        } elseif ($edit_follow == '1') {
            $text = 'Your order has been Delivered';
        }
        $params = array("client_id" => $client_id, 'text' => $text, 'type' => 'order', 'text_id' => $order_id);
        $sendnotify = insertIntoNotSend($params);
    }
}

function sendMessageAndroid($registration_id, $params)
{

    define('API_ACCESS_KEY', 'AAAArPiBeA4:APA91bEvXa_F5kCXdxKJ0ovo95nX4Whrh2Dzbb9bFdI2fGagKlQuxh-fBMdGkNhx7y3DIPWOYQbbsWpn3VpBWn9Zr6_lOGcL6bFMV9Dng6H7VJB-r7TFlrz8hcpwHkmSGqC2lN7AT3At');
    $registrationIds = array($registration_id);
    $msg = array
    (
        'message' => $params['data']['title'],
        'type' => $params['data']['type'],
        'title' => 'Alert',
        'subtitle' => 'Alert message!',
        'vibrate' => 1,
        'sound' => 'default',
        'largeIcon' => 'large_icon',
        'smallIcon' => 'small_icon'
    );

    $fields = array
    (
        'registration_ids' => $registrationIds,
        'data' => $msg
    );

    $headers = array
    (
        'Authorization: key=' . API_ACCESS_KEY,
        'Content-Type: application/json'
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send'); //For firebase, use https://fcm.googleapis.com/fcm/send

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function sendMessageIos($registration_id, $params)
{

    $url = "https://fcm.googleapis.com/fcm/send";

    $serverKey = 'AAAArPiBeA4:APA91bEvXa_F5kCXdxKJ0ovo95nX4Whrh2Dzbb9bFdI2fGagKlQuxh-fBMdGkNhx7y3DIPWOYQbbsWpn3VpBWn9Zr6_lOGcL6bFMV9Dng6H7VJB-r7TFlrz8hcpwHkmSGqC2lN7AT3At';
    $title = "";
    $body = $params['data']['title'];
    $type = $params['data']['type'];
    $notification = array('title' => $title, 'body' => $body, 'sound' => 'default', 'badge' => '1');
    $data = array('type' => $type);
    $arrayToSend = array('to' => $registration_id, 'notification' => $notification, 'priority' => 'high', "data" => $data);
    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key=' . $serverKey;
    $ch = curl_init();


    curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send'); //For firebase, use https://fcm.googleapis.com/fcm/send

    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

//Send the request
    $response = curl_exec($ch);
//Close request
    if ($response === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
// echo die(var_dump($response));
    return $response;
}

/**
 * Send message to SmartPhone
 * $params [pushtype, msg, registration_id]
 */
function sendMessage($params, $addNotSend)
{
    global $con;


    if ($params["registration_id"] && $params["data"]) {
        switch ($params["pushtype"]) {
            case "ios":
                $ress = sendMessageIos($params["registration_id"], $params);
                if ($addNotSend['type'] != 'message') {
                    insertIntoNotSend($addNotSend);
                }
                break;
            case "android":
                $ress = sendMessageAndroid($params["registration_id"], $params);
                $ress = json_decode($ress);
                if ($ress) {
                    if ($ress->success == 0) {
                        updateDevices($params['data']['client_id'], $params["registration_id"]);
                    }
                    if ($addNotSend['type'] != 'message') {
                        insertIntoNotSend($addNotSend);
                    }
                }
                break;
        }
    }
}

function updateDevices($client_id, $device_token)
{
//    echo 'osama';
    global $con;

    if ($device_token) {
        $sql = " SELECT * ";
        $sql .= " FROM `device_token` where `device_token`='{$device_token}' limit 1 ";
        $query = $con->query($sql);
        $row_select = mysqli_fetch_array($query);
        $id = $row_select['id'];
    }
    if (mysqli_num_rows($query) > 0) {
        $sql = "UPDATE  `devices` SET ";
        $sql .= "`login`='0',";
        $sql .= "`date_added`='" . date('Y-m-d H:i:s') . "'";
        $sql .= " WHERE `device_token_id`='{$id}' ";
        $sql .= " and `client_id`='{$client_id}'";
//        echo '5555' . $sql . "<hr>";
        return $con->query($sql);
    }
}

function insertIntoNotSend($temp)
{
    global $con;
    $sql = "SELECT * FROM `notifications` WHERE ";
    $sql .= " `client_id`='" . $temp['client_id'] . "' AND ";
    $sql .= " `text_id`='" . $temp['text_id'] . "' AND ";
    $sql .= " `text`='" . $temp['text'] . "' AND ";
    $sql .= " `type`='" . $temp['type'] . "'";
    $res = $con->query($sql);
    $notifications_count = mysqli_num_rows($res);
    if ($notifications_count == 0) {
        $sql = "INSERT INTO `notifications` SET  `client_id`='" . $temp['client_id'] . "' ,`text`='" . $temp['text'] . "',`type`='" . $temp['type'] . "',`text_id`='" . $temp['text_id'] . "',`date`='" . date('Y-m-d H:i:s') . "'";
        $res = $con->query($sql);
        return mysqli_insert_id($con);
    }
}

function potatos_name($potatos_id)
{

    global $con;

    $queryB = $con->query("SELECT * FROM `potatos` WHERE `id`='$potatos_id' ORDER BY `id` ASC limit 1");
    $row_select = mysqli_fetch_array($queryB);
    $title_en = $row_select['title_en'];
    return $title_en;
}

// Get Parent Categories Name And ID
function drinks_name($drinks_id)
{

    global $con;

    $queryB = $con->query("SELECT * FROM `drinks` WHERE `id`='$drinks_id' ORDER BY `id` ASC limit 1");
    $row_select = mysqli_fetch_array($queryB);
    $title_en = $row_select['title_en'];
    return $title_en;
}

function potatos_price($potatos_id)
{

    global $con;

    $queryB = $con->query("SELECT * FROM `potatos` WHERE `id`='$potatos_id' ORDER BY `id` ASC limit 1");
    $row_select = mysqli_fetch_array($queryB);
    $price = $row_select['price'];
    return $price;
}

// Get Parent Categories Name And ID
function drinks_price($drinks_id)
{

    global $con;

    $queryB = $con->query("SELECT * FROM `drinks` WHERE `id`='$drinks_id' ORDER BY `id` ASC limit 1");
    $row_select = mysqli_fetch_array($queryB);
    $price = $row_select['price'];
    return $price;
}

function get_device_type_by_client_id($client_id)
{

    global $con;

    $queryB = $con->query("SELECT * FROM `devices` WHERE `client_id`='$client_id' ORDER BY `id` DESC limit 1");
    $row_select = mysqli_fetch_array($queryB);
    $device_token_id = $row_select['device_token_id'];

    $queryc = $con->query("SELECT * FROM `device_token` WHERE `id`='$device_token_id' ORDER BY `id` DESC limit 1");
    $row_select_2 = mysqli_fetch_array($queryc);
    $type = $row_select_2['type'];

    return $type;
}

if (isset($_POST['remove_order_id'])) {

    include("../connection.php");

    $order_id = $_POST['remove_order_id'];
    $delete_reason = $_POST['delete_reason'];
    $query = $con->query("SELECT * FROM `orders` WHERE  `order_id`='$order_id' limit 1");
    $row_select = mysqli_fetch_array($query);
    $order_id = $row_select['order_id'];
    $client_id = $row_select['client_id'];
    $client_address_id = $row_select['client_address_id'];
    $charge_cost = $row_select['charge_cost'];
    $order_status = $row_select['order_status'];
    $discount_percentage = $row_select['discount_percentage'];
    $order_follow = $row_select['order_follow'];
    $payment = $row_select['payment'];
    $date = $row_select['date'];
    $reorder = $row_select['reorder'];
    $cart_id = $row_select['cart_id'];
    $con->query("INSERT INTO `order_delete_reason` VALUES (null,'$order_id','$delete_reason','" . date("Y-m-d H:i:s") . "')");
    $con->query("INSERT INTO `order_report` VALUES (null,'$order_id','$cart_id','$client_id','$client_address_id','$charge_cost','$discount_percentage','$order_status','$order_follow','$payment','1','$date','" . date("Y-m-d H:i:s") . "')");
    $cart_id_all = explode(',', $cart_id);

    foreach ($cart_id_all as $one) {
        $devicesArray = " SELECT * from `cart`  WHERE `cart_id`='{$one}' ";
        $query_devicesArray = $con->query($devicesArray);
        while ($v = mysqli_fetch_assoc($query_devicesArray)) {
            $cart_id = $v['cart_id'];
            $sub_category_id = $v['sub_category_id'];
            $size_id = $v['size_id'];
            $addition_id = $v['addition_id'];
            $quantity = $v['quantity'];
            $price = $v['price'];
            $client_id = $v['client_id'];
            $remove_id = $v['remove_id'];
            $status = $v['status'];
            $con->query("INSERT INTO `cart_report` VALUES (null,'$cart_id','$sub_category_id','$size_id','$addition_id','$quantity','$price','$client_id','$remove_id','$status')");
        }
        if ($reorder != 1) {
            $delete_cart = $con->query("DELETE FROM `cart` WHERE `cart_id`='$one'");
        }
    }
    $delete_order = $con->query("DELETE FROM `orders` WHERE `order_id`='$order_id' ");


    if ($delete_order) {
        echo get_success("Deleted Successfully");
    }
}
?>