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

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['rationNumber'])) {
    $rationNumber = trim(mysqli_real_escape_string($ahk_conn, $_POST['rationNumber']));

    // Fetch application fee
    $priceQuery = $ahk_conn->prepare("SELECT price FROM pricing WHERE service_name = ?");
    $serviceName = 'ration2_uid_findfee';
    $priceQuery->bind_param("s", $serviceName);
    $priceQuery->execute();
    $result = $priceQuery->get_result();
    $priceRow = $result->fetch_assoc();
    $fee = $priceRow['price'] ?? 0;

    $username = $udata['phone'];
    $wallet = $udata['balance'];

    if ($wallet >= $fee) {
        $apiKey = urlencode($flexsecure_key);
        $apiUrl = "https://" . htmlspecialchars($flexsecureapiurl) . "/api/v1/Ration2Uid-up.php?rationNumber=$rationNumber&apiKey=$apiKey";

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_FOLLOWLOCATION => true,
        ]);
        $response = curl_exec($curl);
        curl_close($curl);

        $resdata = json_decode($response, true);

        if (isset($resdata['error']) && $resdata['error']) {
            echo "<script>
                $(function(){
                    Swal.fire('{$resdata['error']}', 'Please try with correct details.', 'warning');
                });
            </script>";
        } elseif (isset($resdata['status']) && $resdata['status'] == "100") {
            // Deduct wallet balance
            $newBalance = $wallet - $fee;

            $updateUser = $ahk_conn->prepare("UPDATE users SET balance = ? WHERE phone = ?");
            $updateUser->bind_param("ds", $newBalance, $username);
            $updateUser->execute();

            // Insert transaction history
            date_default_timezone_set('Asia/Kolkata');
            $timestamp = date("Y-m-d H:i:s");
            $purpose = 'Ration 2 uid Find';
            $status = 1;
            $type = 'Debit';

            $insertHistory = $ahk_conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, ?, ?, ?)");
            $insertHistory->bind_param("sdssis", $username, $fee, $newBalance, $purpose, $status, $type);
            $insertHistory->execute();

            echo "<script>
                $(function(){
                    Swal.fire('Success!', 'Status: {$resdata['message']}', 'success');
                });
            </script>";
        } else {
            echo "<script>
                $(function(){
                    Swal.fire('Error', 'Unexpected response from server.', 'error');
                });
            </script>";
        }
    } else {
        echo "<script>
            $(function(){
                Swal.fire('Insufficient Balance', 'Wallet Balance Insufficient! Please Recharge.', 'error');
            });
            setTimeout(() => { window.location.href = 'wallet.php'; }, 10000);
        </script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ration to Aadhaar</title>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>

<!-- HTML UI -->
<div class="page-wrapper">
    <div class="page-content">
        <!-- Breadcrumb with Action Buttons -->
        <div class="page-breadcrumb d-flex align-items-center justify-content-between mb-4 p-3 bg-white rounded shadow-sm">
            <div class="d-flex align-items-center">
                <div class="breadcrumb-title pe-3">Services</div>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb mb-0 ps-2">
                        <li class="breadcrumb-item active text-muted" aria-current="page">Ration To Aadhaar Find Only UP</li>
                    </ol>
                </nav>
            </div>
            <div class="btn-group">
               
                <a href="javascript:history.back()" class="btn btn-outline-primary">
                    <i class="bi bi-arrow-left me-1"></i> Back
                </a>
            </div>
        </div>
      
        <!-- End breadcrumb -->

        <div class="container-fluid pt-4 px-4">
            <div class="row">
                <!-- Left Side: 35% Width -->
                <div class="col-lg-4 mb-4">
                    <div class="card">
                        <div class="card-body">
                            <h3 class="card-title text-dark text-center"><strong>Only Uttar Pradesh</strong></h3>
                            <a href="" class="btn btn-dark w-100 mb-3">Ration To Aadhaar Find Instant</a>
                            <form action="" method="post" id="rasan_print">
                                <div class="form-group">
                                    <label for="rationNumber">Ration Number <span style="color:red;">*</span></label>
                                    <input type="text" class="form-control" name="rationNumber" id="rationNumber" placeholder="Enter Ration Number" required>
                                </div>
                                <div class="text-warning mt-2">
                                    <h5>Application Fee:
                                        ₹<?php  
                                        $price = mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT price FROM pricing WHERE service_name='ration2_uid_findfee'")); 
                                        echo $price['price'];
                                        ?>
                                    </h5>
                                </div>
                                <div class="mt-3">
                                    <button type="submit" class="btn btn-primary w-100"><i class="fa fa-check-circle"></i> Submit</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Right Side: 65% Width -->
                <div class="col-lg-8">
                    <?php if (isset($resdata['status']) && $resdata['status'] == "100" && !empty($resdata['data'])): ?>
                        <div class="card">
                            <div class="card-body">
                                <h5 class="text-success text-center">Results Found: All Details</h5>
                                <div class="table-responsive mt-3">
    <table class="table table-bordered table-striped text-center">
        <thead class="thead-dark">
            <tr>
                <th>Sr No</th>
                <th>Ration Number</th>
                <th>UID No</th>
                <th>Name</th>
                <th>Father's Name</th>
                <th>Gender</th>
                <th>DOB</th>
                <th>Relation</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $srNo = 1; // Initialize serial number
            foreach ($resdata['data'] as $member): 
            ?>
                <tr>
                    <td><?= $srNo++ ?></td>
                    <td><?= htmlspecialchars($member['rationNumber']) ?></td>
                    <td><?= htmlspecialchars($member['uidNumber']) ?></td>
                    <td><?= htmlspecialchars($member['name']) ?></td>
                    <td><?= htmlspecialchars($member['fathername']) ?></td>
                    <td><?= htmlspecialchars($member['gender']) ?></td>
                    <td><?= htmlspecialchars($member['dob']) ?></td>
                    <td><?= htmlspecialchars($member['relation']) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
                            </div>
                        </div>
                    <?php elseif (isset($resdata) && empty($resdata['data'])): ?>
                        <div class="alert alert-danger text-center mt-4">
                            No data found for this Ration Number.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

	<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
	<!--plugins-->
	<!-- <script src="../template/ahkweb/assets/js/jquery.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>
	<!--app JS-->
	<script src="../template/ahkweb/assets/js/app.js"></script>
</body>
</html>


		<?php 
		include('../template/ahkweb/footer.php');
		?>