<?php
include("../serive/samparka.php");

header("Content-Type: application/json");

date_default_timezone_set('Asia/Kolkata');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // =========================
    // GET DATA
    // =========================
    $order_id = mysqli_real_escape_string($conn, $_POST['order_id']);
    $txn_id   = mysqli_real_escape_string($conn, $_POST['txn_id']);
    $status   = mysqli_real_escape_string($conn, $_POST['status']);
    $amount   = mysqli_real_escape_string($conn, $_POST['amount']);

    // =========================
    // CHECK ORDER EXISTS
    // =========================
    $check = mysqli_query($conn, "
        SELECT * FROM thevani 
        WHERE dharavahi='$order_id'
        LIMIT 1
    ");

    if(mysqli_num_rows($check) == 0){

        echo json_encode([
            "status" => false,
            "msg" => "Order Not Found"
        ]);
        exit;

    }

    $data = mysqli_fetch_array($check);

    $uid = $data['balakedara'];

    // =========================
    // ALREADY SUCCESS CHECK
    // =========================
    if($data['sthiti'] == 1){

        echo json_encode([
            "status" => false,
            "msg" => "Already Credited"
        ]);
        exit;

    }

    // =========================
    // PAYMENT SUCCESS
    // =========================
    if(strtolower($status) == "success"){

        // UPDATE DEPOSIT STATUS
        mysqli_query($conn, "
            UPDATE thevani 
            SET 
                sthiti='1',
                ullekha='$txn_id'
            WHERE dharavahi='$order_id'
        ");

        // =========================
        // GET OLD BALANCE
        // =========================
        $userQ = mysqli_query($conn, "
            SELECT money 
            FROM shonu_subjects 
            WHERE id='$uid'
        ");

        $userA = mysqli_fetch_array($userQ);

        $old_balance = $userA['money'];

        // =========================
        // NEW BALANCE
        // =========================
        $new_balance = $old_balance + $amount;

        // =========================
        // UPDATE USER BALANCE
        // =========================
        mysqli_query($conn, "
            UPDATE shonu_subjects 
            SET money='$new_balance'
            WHERE id='$uid'
        ");

        echo json_encode([
            "status" => true,
            "msg" => "Deposit Successful"
        ]);

    } else {

        // FAILED
        mysqli_query($conn, "
            UPDATE thevani 
            SET sthiti='2'
            WHERE dharavahi='$order_id'
        ");

        echo json_encode([
            "status" => false,
            "msg" => "Payment Failed"
        ]);

    }

} else {

    echo json_encode([
        "status" => false,
        "msg" => "Invalid Request"
    ]);

}
?>