<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>';

$price = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM pricing WHERE service_name='ration_to_uid_all' "));
$fee = $price['price'] ?? 150;

if (isset($_POST['rationNumber']) && !empty($_POST['rationNumber'])) {
    $rationNumber = mysqli_real_escape_string($ahk_conn, $_POST['rationNumber']);
    $userid = $udata['phone'];
    $current_balance = $udata['balance'];

    if ($current_balance < $fee) {
        echo '
        <script>
            $(function(){
                Swal.fire({
                    icon: "error",
                    title: "Low Balance",
                    text: "Wallet balance is low! Please recharge.",
                    timer: 4000,
                    timerProgressBar: true
                });
                setTimeout(() => { window.location = "wallet.php"; }, 1200);
            });
        </script>';
    } else {
        $check_pending = mysqli_query($ahk_conn, "SELECT * FROM ration_to_aadhar_requests WHERE userid='$userid' AND ration_no='$rationNumber' AND status='Pending'");
        if (mysqli_num_rows($check_pending) > 0) {
            echo '
            <script>
                $(function(){
                    Swal.fire({
                        icon: "warning",
                        title: "Pending",
                        text: "Application already submitted and is pending. Please wait before submitting again.",
                        timer: 4000,
                        timerProgressBar: true
                    });
                });
            </script>';
        } else {
            $submit_url = "$tng_apiurl/api/ration-to-uid-all/v1/ration-to-uid-all-verification?apikey=$tng_apikey&ration_no=$rationNumber";

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $submit_url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 60,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET'
            ]);
            $response = curl_exec($curl);
            curl_close($curl);

            $resdata = json_decode($response, true);

            if (isset($resdata['sampleCode']) && $resdata['sampleCode'] == "200" && $resdata['status'] == "Pending") {
                $new_balance = $current_balance - $fee;
                date_default_timezone_set('Asia/Kolkata');
                $timestamp = date("Y-m-d H:i:s");
                $parentPhone = $udata['parent'] ?? null;
        addCommission($ahk_conn, $appliedby, $fee, $parentPhone, "Ration to UID All State Verification");
                mysqli_query($ahk_conn, "UPDATE users SET balance='$new_balance' WHERE phone='$userid'");
                mysqli_query($ahk_conn, "INSERT INTO `wallethistory`(`userid`,`amount`,`balance`,`purpose`,`status`,`type`) 
                                         VALUES ('$userid','$fee','$new_balance','Ration to UID All State Verification','1','Debit')");

                $order_id = $resdata['order_id'];
               mysqli_query($ahk_conn, "INSERT INTO ration_to_aadhar_requests 
    (userid, ration_no, order_id, status, request_time) 
    VALUES ('$userid', '$rationNumber', '$order_id', 'Pending', '$timestamp')");

               echo '
<script>
    $(function(){
        Swal.fire({
            icon: "success",
            title: "Submitted",
            html: "Data submitted successfully.<br>Order ID: <b>'.$order_id.'</b>",
            timer: 3000,
            timerProgressBar: true,
            willClose: () => {
                window.location.href = "ration_2_uid_all_submit_list.php";
            }
        });
    });
</script>';

            } else {
                $error_msg = $resdata['error'] ?? "Error submitting request";
                echo '
                <script>
                    $(function(){
                        Swal.fire({
                            icon: "error",
                            title: "Failed",
                            text: "'.$error_msg.'",
                            timer: 4000,
                            timerProgressBar: true
                        });
                    });
                </script>';
            }
        }
    }
}
?>


<div class="content-wrap">
    <div class="main">
        <div class="col-md-12">
            <div class="main-content">
<div class="page-wrapper">
    <div class="page-content">
        <div class="mobile-menu-overlay"></div>
        <div class="main-container">
            <div class="col-lg-12">
                <div class="card" style="margin-left: 10px; padding-left: 30px; padding-top: 12px; box-shadow: 1px 5px 5px 5px;">
                    <div class="stat-widget-two">
                        <div class="stat-content">
                            <div class="stat-text">
                                <div class="container-fluid">
                                    <div class="row">
                                        <div class="col-lg-4 col-md-6 col-sm-6">
                                            <div class="card">
                                                <div class="card-body">
                                                    <div class="alert alert-danger" role="alert">
                                                        <a href="" class="alert-link">Ration to UID (All State) Find........</a>
                                                    </div>
                                                    <form action="" method="POST" class="row g-3">
                                                        <div class="card-body">
                                                            <div class="col-md-12">
                                                                <div class="form-group">
                                                                    <label for="rationNumber">Enter Ration Number</label>
                                                                    <input name="rationNumber" type="text" id="rationNumber"  placeholder="Enter Ration Number" class="form-control" required>
                                                                </div>
                                                                <hr>
                                                              
                                                                <div class="row mt-3">
                                                                  <div class="col-md-6">
                                                                       <input class="form-control" value="Fee ₹ <?php echo $fee; ?>" readonly>
                                                                   </div>
                                                                   <div class="col-md-6 text-end">
                                                                       <button class="btn btn-success" name="submit" id="submit"><i class="fa fa-check-circle"></i> Submit</button>
                                                                   </div>
                                                               </div>
                                                            </div>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<?php include('../template/ahkweb/footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>