<?php 
require 'db.php';
$data = json_decode(file_get_contents('php://input'), true);
if($data['order_id'] == '')
{
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");    
}
else
{
    $uid =  $data['uid'];
    $order_id =  $data['order_id'];
    $pay_status = $data['status'];
    $datesloat = $data['date'];
    $timesloat = $data['time'];
    $p_method = $data['p_method'];
    
    $user = $con->query("select * from user where id = '$uid'");
    if($row_user = $user->fetch_assoc()) {
        $u_coins = $row_user['coins'];
    }
    
    if($pay_status == 1 || $p_method == 'Pay on Delivery')
    {
        $status = 'pending';
        $o_status = '1';
        
        $sql_log = "insert into order_details(`uid`,`order_id`,`status`,`order_date`,`order_time`)values('$uid','$order_id','$status','$datesloat','$timesloat')";
        $con->query($sql_log);
        
        $sql_qu =$con->query("select * from orders where order_id = '$order_id'");
        if($row_order = $sql_qu->fetch_assoc())
        {
            $coins_use = $row_order['coins_use'];
            $coins_earn = $row_order['coins_earn'];
            $coins = $row_order['coins'];
        }
        
        if($u_coins != 0)
        {
            if($coins_use > 0)
            {
                $transaction_name = "Redeem for #".$order_id;
                $sql_coins = "insert into coin_transactions(`uid`,`name`,`coins`,`coin_type`,`c_date`,`c_time`)values('$uid','$transaction_name','$coins_use','0','$datesloat','$timesloat')";
                $con->query($sql_coins);
            }
            
            if($coins_earn > 0)
            {
                $transaction_name = "Earn from #".$order_id;
                $sql_coin = "insert into coin_transactions(`uid`,`name`,`coins`,`coin_type`,`c_date`,`c_time`)values('$uid','$transaction_name','$coins_earn','1','$datesloat','$timesloat')";
                $con->query($sql_coin);
            }
            $u_coins = ($u_coins - $coins_use) + $coins_earn;
            $con->query("update user set coins='$u_coins' where id = '$uid'");
        }
    }
    else if($pay_status == 0 && $p_method != 'Pay on Delivery')
    {
        $status = 'cancelled';
        $o_status = '0';
    }

    $con->query("update orders set o_status='$o_status',status='$status',pay_status='$pay_status' where order_id = '$order_id'");
    $returnArr = array("ResponseCode"=>$sql,"Result"=>"true","ResponseMsg"=>"Order Placed Successfully!","coins"=>$u_coins);
}
echo json_encode($returnArr);