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

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

// Fix Database Encoding Parameters
mysqli_set_charset($conn, "utf8mb4");
mysqli_query($conn, "SET NAMES 'utf8mb4'");
mysqli_query($conn, "SET CHARACTER SET 'utf8mb4'");

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

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

// Pricing Profile Data Fetch via Secure Prepared Statement
$stmt_price = $conn->prepare("SELECT price FROM pricing WHERE service_name = 'ration_pdf' LIMIT 1");
$stmt_price->execute();
$price_check = $stmt_price->get_result();
$service_price = ($price_check && $price_check->num_rows > 0) ? floatval($price_check->fetch_assoc()['price']) : 15.00;
$stmt_price->close();

// API Config Environment Module Fetch
$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: API Configuration missing.'); window.location.href='titanhome.php';</script>";
    exit();
}

// Handle Form Core Transaction Logic
if (isset($_POST['get_ration_btn'])) {
    $input_ration = trim($_POST['ration_number']);
    
    // Fetch Authenticated User Wallet Balance safely
    $stmt_wallet = $conn->prepare("SELECT wallet FROM users WHERE id = ? LIMIT 1");
    $stmt_wallet->bind_param("s", $uid);
    $stmt_wallet->execute();
    $user_wallet = floatval($stmt_wallet->get_result()->fetch_assoc()['wallet']);
    $stmt_wallet->close();
    
    if (empty($input_ration)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid Ration Number.', 'error');";
    } elseif ($user_wallet < $service_price) {
        $swal_msg = "Swal.fire('Low Balance!', 'You need ₹" . number_format($service_price, 2) . " in your wallet.', 'warning');";
    } else {
        // ================= MAXXAPI DIRECT ENDPOINT =================
        $endpoint = "https://www.maxxapi.site/S1ration?api_key=2311e32848008d9eabd5fdb2db10b19e0614e81e5fd206743357469c6ec1ebd2&ration_no=" . urlencode($input_ration);

        // cURL Interceptor Cluster Pipeline Setup
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        // CRITICAL FIX: Authentic User-Agent context configuration strings to clear OpenResty 403 blocks
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36');
        
        // Inject comprehensive HTTP layer payload validation variables
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json, text/html, */*',
            'Accept-Language: en-US,en;q=0.9',
            'Cache-Control: no-cache',
            'Connection: keep-alive'
        ]);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $api_response = curl_exec($ch);
        curl_close($ch);
        
        if ($api_response) {
            $data = json_decode($api_response, true);
            
            // Normalize cross-platform variations inside raw data object array bounds
            $resData    = $data['result'] ?? $data;
            $api_status = trim(strtolower($resData['status'] ?? $data['status'] ?? 'failed'));
            $api_msg    = $resData['message'] ?? $data['message'] ?? 'Failed to fetch target data from remote cluster.';
            
            // Evaluates both standardized plain response variables and status codes (200 / success)
            if ($api_status === 'success' || $api_status === '200') {
                
                // Calculate and partition local client accounting updates
                $new_wallet = $user_wallet - $service_price;
                
                // Deduct updated total balance value safely via Prepared Statement
                $stmt_deduct = $conn->prepare("UPDATE users SET wallet = ? WHERE id = ?");
                $stmt_deduct->bind_param("ds", $new_wallet, $uid);
                $stmt_deduct->execute();
                $stmt_deduct->close();
                
                // Insert transaction item block trace elements into core ledger tracking tables
                $wallet_purpose = "Ration PDF Print (" . $input_ration . ")";
                $wallet_status = "1";
                $wallet_type = "Debit";
                $stmt_wlog = $conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, ?, ?, ?)");
                $stmt_wlog->bind_param("sddsss", $uid, $service_price, $new_wallet, $wallet_purpose, $wallet_status, $wallet_type);
                $stmt_wlog->execute();
                $stmt_wlog->close();
                
                // Parse nested data nodes safely from meta properties index variables if defined
                $meta       = $data['meta'] ?? [];
                $head_name  = $meta['head_name'] ?? $resData['head_name'] ?? 'N/A';
                $homestate  = $meta['homestate'] ?? $resData['homestate'] ?? 'N/A';
                $district   = $meta['district'] ?? $resData['district'] ?? 'N/A';
                
                // Capture accurate output system path parameter strings
                $pdf_path   = $data['pdf'] ?? $resData['pdf_file'] ?? '';
                
                // Strip away structural duplicates or upstream tracking artifacts if present
                if (strpos($pdf_path, '../dashboard/') !== false) {
                    $pdf_path = str_replace('../dashboard/', '', $pdf_path);
                }
                
                // Save trace element variables inside operational system dashboard loggers
                $stmt_hist = $conn->prepare("INSERT INTO ration_pdf_history (user_id, ration_no, head_name, homestate, district, pdf_data, message) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt_hist->bind_param("sssssss", $uid, $input_ration, $head_name, $homestate, $district, $pdf_path, $api_msg);
                
                if ($stmt_hist->execute()) {
                    $swal_msg = "Swal.fire('Success!', 'Ration PDF Fetched Successfully!', 'success').then(() => { window.location.href='ration_pdf_list.php'; });";
                } else {
                    $swal_msg = "Swal.fire('Database Error!', 'Document data parsed, but internal tracing write tracking operation returned empty bounds.', 'error');";
                }
                $stmt_hist->close();
                
            } else {
                $swal_msg = "Swal.fire('Failed!', 'Reason: " . addslashes($api_msg) . "', 'error');";
            }
        } else {
            $swal_msg = "Swal.fire('Server Error!', 'Could not establish connection link parameters with endpoint engine module.', 'error');";
        }
    }
}
?>

<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-success-subtle shadow-none me-3">
                        <span class="fas fa-file-invoice text-success fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-success fs-10 mb-0">Food & Civil Supplies</h6>
                        <h4 class="text-primary fw-bold mb-0">Ration Card <span class="text-success fw-medium">PDF Print</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="ration_pdf_list.php" class="btn btn-sm btn-outline-primary shadow-none fw-bold"><i class="fas fa-list me-1"></i> View History</a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row justify-content-center">
    <div class="col-lg-6">
        <div class="card h-100 border-0 shadow-sm border-top border-4 border-success">
            <div class="card-header bg-light border-bottom">
                <h5 class="mb-0 text-primary fw-bold text-center"><i class="fas fa-download me-2 text-success"></i>Fetch Ration PDF</h5>
            </div>
            <div class="card-body bg-body-tertiary p-4">
                <div class="alert alert-success border-0 d-flex align-items-center mb-4">
                    <i class="fas fa-rupee-sign fs-3 me-3 text-success"></i>
                    <p class="mb-0 fs-11">Service charge: <strong>₹<?php echo number_format($service_price, 2); ?></strong> will be deducted upon successful fetch.</p>
                </div>
                
                <form method="POST" autocomplete="off" id="rationForm">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-900">Ration Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-barcode"></i></span>
                            <input type="text" class="form-control shadow-none text-uppercase" name="ration_number" id="ration_number" placeholder="Enter Ration Number" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-success w-100 fw-bold shadow-none py-2" type="button" onclick="confirmFetch()">
                        <i class="fas fa-search me-2"></i> Get Ration PDF
                    </button>
                    <button type="submit" name="get_ration_btn" id="realSubmit" class="d-none"></button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Fire SweetAlert dialog notification configurations evaluated out of the engine block context
    <?php echo $swal_msg; ?>

    // Form Event Handler Execution Engine Controller
    function confirmFetch() {
        let rationNo = document.getElementById('ration_number').value.trim();
        if(rationNo === '') {
            Swal.fire('Warning', 'Please enter a Ration Number.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Fetching Data...',
            html: 'Please wait while we connect to server.',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Pass programmatic click events to the structural document wrapper layer
        document.getElementById('realSubmit').click();
    }
</script>

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