<?php
ob_start();
// 1. Session & Auth Control
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

$swal_msg = "";
$successData = null;

// 2. Pricing Fetch from standard pricing architecture
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'aadhaar_to_ration'");
$service_price = ($price_check && $price_check->num_rows > 0) ? $price_check->fetch_assoc()['price'] : 4.00;

// 3. API Config Fetch from TitanPayment System
$api_settings = $conn->query("SELECT titanurl, titan_api_key FROM TitanPayment WHERE id = 1")->fetch_assoc();
$TitanApi_Url = $api_settings['titanurl'] ?? '';
$api_key = $api_settings['titan_api_key'] ?? '';

if (empty($TitanApi_Url) || empty($api_key)) {
    echo "<script>alert('System Error: TitanPayment API URL or Key is not configured. Contact Admin.'); window.location.href='titanhome.php';</script>";
    exit();
}

// 4. Handle Verification Logic
if (isset($_POST['find_ration'])) {
    $uidNumber = preg_replace('/[^0-9]/', '', $_POST['uidNumber']);
    
    // Wallet Check
    $user_wallet = $conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc()['wallet'];
    
    if (strlen($uidNumber) !== 12 || !is_numeric($uidNumber)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid 12-digit Aadhaar number.', 'error');";
    } elseif ($user_wallet < $service_price) {
        $swal_msg = "Swal.fire('Low Balance!', 'You need ₹$service_price in your wallet to use this service.', 'warning');";
    } else {
        // Build API URL dynamic matching vendor endpoint requirements 
        $endpoint = "https://www.maxxapi.site/S1aadhar2ration?api_key=2311e32848008d9eabd5fdb2db10b19e0614e81e5fd206743357469c6ec1ebd2&uidNumber=" . urlencode($uidNumber);
        
        // Dynamic alternate layout structure backup:
        // $endpoint = rtrim($TitanApi_Url, '/') . "/aadhar2ration?api_key=" . urlencode($api_key) . "&uidNumber=" . urlencode($uidNumber);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $api_response = curl_exec($ch);
        curl_close($ch);
        
        if ($api_response) {
            $data = json_decode($api_response, true);
            
            // Flexible layout structural normalization checks
            $status = $data['status'] ?? ($data['result']['status'] ?? '');
            
            if ($status == '200' || $status == '100' || strtolower($status) === 'success') {
                $source = (isset($data['ration_number']) || isset($data['ration_no'])) ? $data : ($data['result'] ?? []);
                
                $aadhaar_number = mysqli_real_escape_string($conn, $source['aadhaar_number'] ?? $source['aadhaar_no'] ?? $uidNumber);
                $ration_number  = mysqli_real_escape_string($conn, $source['ration_number'] ?? $source['ration_no'] ?? '');
                $tracking_id    = mysqli_real_escape_string($conn, $source['tracking_id'] ?? 'N/A');
                $response_time  = mysqli_real_escape_string($conn, $source['response_time'] ?? date('H:i:s'));
                $data_source    = mysqli_real_escape_string($conn, $source['data_source'] ?? 'api');
                $date_time      = date('Y-m-d H:i:s');
                
                // Deduct Balance Securely
                $new_balance = $user_wallet - $service_price;
                $conn->query("UPDATE users SET wallet = '$new_balance' WHERE id = '$uid'");
                
                // Save Transaction Logs to Database (ration_history)
                $db_response_string = mysqli_real_escape_string($conn, json_encode($data));
                $insert_history = "INSERT INTO ration_history (aadhaar_no, ration_no, username, response, date) 
                                   VALUES ('$aadhaar_number', '$ration_number', '$u_name', '$db_response_string', '$date_time')";
                
                // Save Audit Footprints (wallethistory)
                $insert_log = "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                               VALUES ('$u_name', '$service_price', '$new_balance', 'Aadhaar To Ration', '1', 'Debit')";
                
                if ($conn->query($insert_history) && $conn->query($insert_log)) {
                    $successData = [
                        "aadhaar_number" => $aadhaar_number,
                        "ration_number" => $ration_number,
                        "tracking_id" => $tracking_id,
                        "response_time" => $response_time,
                        "data_source" => $data_source
                    ];
                } else {
                    $swal_msg = "Swal.fire('Database Error!', 'Search completed successfully but history logging failed.', 'error');";
                }
            } else {
                $err = $data['message'] ?? ($data['result']['message'] ?? 'Verification failed or invalid API response.');
                $swal_msg = "Swal.fire('Failed!', '" . addslashes($err) . "', 'error');";
            }
        } else {
            $swal_msg = "Swal.fire('Server Error!', 'Could not connect to the Master API Server.', 'error');";
        }
    }
}

// Fetch Account Transaction Tracking List records
$history = $conn->query("SELECT * FROM ration_history WHERE username='$u_name' ORDER BY id DESC");
?>

<link href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">

<div class="row mb-3">
    <div class="col">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-info-subtle shadow-none me-3">
                        <span class="fas fa-check-circle text-info fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-info fs-10 mb-0">Identity Services</h6>
                        <h4 class="text-primary fw-bold mb-0">Aadhaar To <span class="text-info fw-medium">Ration</span></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4 justify-content-center">
    <div class="col-lg-4">
        <div class="card h-100">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold text-center"><i class="fas fa-fingerprint me-2"></i>Verify Details</h5>
            </div>
            <div class="card-body bg-body-tertiary p-4">
                <div class="alert alert-info border-0 d-flex align-items-center mb-4">
                    <i class="fas fa-rupee-sign fs-3 me-3 text-info"></i>
                    <p class="mb-0 fs-11">Verification charge: <strong>₹<?php echo number_format($service_price, 2); ?></strong> will be deducted from your wallet upon success.</p>
                </div>
                
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">Aadhaar Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="fas fa-id-card"></i></span>
                            <input type="text" class="form-control shadow-none text-center" name="uidNumber" placeholder="Enter 12-digit number" maxlength="12" pattern="\d{12}" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-info w-100 fw-bold shadow-none py-2" type="submit" name="find_ration">
                        <i class="fas fa-search me-2"></i> Find Ration Number
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card h-100">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold"><i class="fas fa-list me-2"></i>Search History</h5>
            </div>
            <div class="card-body p-3">
                <div class="table-responsive">
                    <table id="rationTable" class="table table-bordered table-hover text-center align-middle m-0">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>Date</th>
                                <th>Aadhaar</th>
                                <th>Ration Number</th>
                                <th>Slip</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($r = $history->fetch_assoc()) { ?>
                            <tr>
                                <td>#<?= $r['id'] ?></td>
                                <td><?= date('d M Y h:i A', strtotime($r['date'])) ?></td>
                                <td class="fw-bold text-secondary">[Aadhaar Redacted]</td>
                                <td class="fw-bold text-primary"><?= htmlspecialchars($r['ration_no']) ?></td>
                                <td>
                                    <button class="btn btn-sm btn-outline-info shadow-none" onclick='viewSlip(<?= json_encode($r) ?>)'>
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        $('#rationTable').DataTable({
            "order": [[ 0, "desc" ]]
        });
    });

    <?php echo $swal_msg; ?>

    <?php if ($successData) { ?>
        Swal.fire({
            icon: 'success',
            title: 'Ration Number Found',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>Aadhaar :</b> [Aadhaar Redacted]</p>
                <p class="mb-1"><b>Ration Number :</b> <?= $successData['ration_number'] ?></p>
                <p class="mb-0"><b>Data Source :</b> <?= $successData['data_source'] ?></p>
            </div>`
        });
    <?php } ?>

    function viewSlip(d){
        Swal.fire({
            title: 'Aadhaar To Ration Slip',
            html: `
            <div class="text-start p-2" style="font-size: 14px;">
                <p class="mb-1"><b>Aadhaar :</b> [Aadhaar Redacted]</p>
                <p class="mb-1"><b>Ration Number :</b> ${d.ration_no}</p>
                <p class="mb-0"><b>Date :</b> ${d.date}</p>
            </div>`,
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-print me-1"></i> Print',
            cancelButtonText: 'Close'
        }).then((result)=>{
            if(result.isConfirmed){
                window.print();
            }
        });
    }
</script>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>