<?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
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 Fetch (Ensure 'rtps_pdf' exists in your pricing table)
$price_check = $conn->query("SELECT price FROM pricing WHERE service_name = 'rtps_pdf'");
$service_price = ($price_check && $price_check->num_rows > 0) ? floatval($price_check->fetch_assoc()['price']) : 2.00;

// API Config 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 Logic
if (isset($_POST['get_rtps_btn'])) {
    $input_reference = mysqli_real_escape_string($conn, trim($_POST['reference']));
    $input_name = mysqli_real_escape_string($conn, trim($_POST['name']));
    
    // Wallet Check
    $user_wallet = floatval($conn->query("SELECT wallet FROM users WHERE id = '$uid'")->fetch_assoc()['wallet']);
    
    if (empty($input_reference)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter a valid RTPS Reference Number.', 'error');";
    } elseif (empty($input_name)) {
        $swal_msg = "Swal.fire('Invalid Input!', 'Please enter the Applicant Name.', 'error');";
    } elseif ($user_wallet < $service_price) {
        $swal_msg = "Swal.fire('Low Balance!', 'You need ₹$service_price in your wallet.', 'warning');";
    } else {
        // Build Endpoint Dynamically
        $endpoint = rtrim($TitanApi_Url, '/') . "/api/v1/Rtps.php?api_key=" . urlencode($api_key) . "&reference=" . urlencode($input_reference) . "&name=" . urlencode($input_name);
        
        // cURL Request
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        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);
            
            // Flexible Status Check
            $api_status = $data['status'] ?? 'failed';
            $api_msg = $data['message'] ?? 'Failed to fetch Details.';
            
            // Check Success
            if (strtolower($api_status) === 'success') {
                
                if(isset($data['result']['download_url']) && !empty($data['result']['download_url'])) {
                    
                    // Calculate new balance
                    $new_wallet = $user_wallet - $service_price;
                    
                    // Deduct Wallet
                    $conn->query("UPDATE users SET wallet = '$new_wallet' WHERE id = '$uid'");
                    
                    // History log update
                    $conn->query("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES ('$uid', '$service_price', '$new_wallet', 'RTPS PDF ($input_reference)', '1', 'Debit')");
                    
                    // Get the PDF link
                    $pdf_link = mysqli_real_escape_string($conn, $data['result']['download_url']);
                    $provider = mysqli_real_escape_string($conn, $data['result']['Provider'] ?? 'TitanApi');
                    $captcha_used = mysqli_real_escape_string($conn, $data['result']['captcha_used'] ?? 'N/A');
                    $transaction_id = mysqli_real_escape_string($conn, $data['transaction']['transaction_id'] ?? 'N/A');
                    $deducted_amount = floatval($data['transaction']['deducted_amount'] ?? $service_price);
                    
                    // Save to History
                    $insert = "INSERT INTO rtps_history (user_id, reference_no, applicant_name, pdf_link, provider, captcha_used, transaction_id, deducted_amount, full_response) 
                               VALUES ('$uid', '$input_reference', '$input_name', '$pdf_link', '$provider', '$captcha_used', '$transaction_id', '$deducted_amount', '" . mysqli_real_escape_string($conn, json_encode($data)) . "')";
                    
                    if ($conn->query($insert)) {
                        // Open PDF in a new tab, then redirect to the list page
                        $swal_msg = "Swal.fire('Success!', 'RTPS PDF Fetched Successfully!', 'success').then(() => { window.open('$pdf_link', '_blank'); window.location.href='rtps_list.php'; });";
                    } else {
                        $swal_msg = "Swal.fire('Database Error!', 'Generated but failed to save history.', 'error');";
                    }
                } else {
                    $swal_msg = "Swal.fire('No Records!', 'No PDF link generated for this Reference Number.', 'info');";
                }
                
            } else {
                $swal_msg = "Swal.fire('Failed!', 'Reason: " . addslashes($api_msg) . "', 'error');";
            }
        } else {
            $swal_msg = "Swal.fire('Server Error!', 'Could not connect to the Master API Server.', '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-pdf text-success fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-success fs-10 mb-0">Identity & Document Services</h6>
                        <h4 class="text-primary fw-bold mb-0">Bihar RTPS <span class="fw-medium">PDF Download</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="rtps_list.php" class="btn btn-sm btn-outline-success shadow-none fw-bold"><i class="fas fa-list me-1"></i> View RTPS 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-body-tertiary border-bottom">
                <h5 class="mb-0 text-success fw-bold text-center"><i class="fas fa-search me-2"></i>Find RTPS PDF by Reference Number</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="rtpsForm">
                    <div class="mb-3">
                        <label class="form-label fw-bold">RTPS Reference Number <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-hashtag"></i></span>
                            <input type="text" class="form-control shadow-none" name="reference" id="reference" placeholder="e.g., BICCO/2024/10436394" required>
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold">Applicant Name <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-user"></i></span>
                            <input type="text" class="form-control shadow-none" name="name" id="name" placeholder="Enter Applicant Full Name" required>
                        </div>
                    </div>
                    
                    <button class="btn btn-success w-100 fw-bold shadow-none py-2" type="button" onclick="confirmFetch()">
                        <i class="fas fa-download me-2"></i> Fetch RTPS PDF
                    </button>
                    <button type="submit" name="get_rtps_btn" id="realSubmit" class="d-none"></button>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    <?php echo $swal_msg; ?>

    function confirmFetch() {
        let reference = document.getElementById('reference').value.trim();
        let name = document.getElementById('name').value.trim();
        
        if(reference === '') {
            Swal.fire('Warning', 'Please enter the RTPS Reference Number.', 'warning');
            return;
        }
        if(name === '') {
            Swal.fire('Warning', 'Please enter the Applicant Name.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Fetching Document...',
            html: 'Please wait while we connect to server and generate your PDF.',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        document.getElementById('realSubmit').click();
    }
</script>

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