<?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'];
$utype = $_SESSION['utype'] ?? $_SESSION['user_type'] ?? 'Retailer';

$filter = ($utype == 'TitanAdmin') ? "" : "WHERE user_id = '$uid'";
$query = "SELECT * FROM rtps_history $filter ORDER BY id DESC";
$result = $conn->query($query);
?>

<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-list text-success fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-success fs-10 mb-0">History Log</h6>
                        <h4 class="text-primary fw-bold mb-0">Bihar RTPS <span class="fw-medium">Records</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="rtps_pdf.php" class="btn btn-sm btn-success shadow-none fw-bold">
                        <i class="fas fa-search me-1"></i> Search New RTPS
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-success">
    <div class="card-body p-0">
        <div class="table-responsive scrollbar">
            <table class="table table-sm table-striped fs-10 mb-0 text-center align-middle">
                <thead class="bg-200 text-900">
                    <tr>
                        <th class="py-2">#ID</th>
                        <th>Reference No.</th>
                        <th>Applicant Name</th>
                        <th>Provider</th>
                        <th>Amount</th>
                        <th>Date & Time</th>
                        <th class="text-end pe-4">Action</th>
                    </tr>
                </thead>
                <tbody class="list">
                    <?php if($result && $result->num_rows > 0): ?>
                        <?php while($row = $result->fetch_assoc()): 
                            // Secure JSON data pass kar rahe hain HTML attribute me
                            $secure_json_data = htmlspecialchars($row['full_response'], ENT_QUOTES, 'UTF-8');
                            
                            // Format amount
                            $amount = !empty($row['deducted_amount']) ? '₹' . number_format($row['deducted_amount'], 2) : '₹' . number_format($row['deducted_amount'] ?? 2.00, 2);
                        ?>
                            <tr>
                                <td class="py-3 fw-bold">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-11 px-3 py-2 font-monospace border border-primary">
                                        <i class="fas fa-hashtag me-1"></i> <?php echo htmlspecialchars($row['reference_no']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-info fs-11 px-3 py-2 border border-info">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($row['applicant_name']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-secondary fs-11 px-3 py-2 border border-secondary">
                                        <i class="fas fa-server me-1"></i> <?php echo htmlspecialchars($row['provider'] ?? 'N/A'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-success fs-11 px-3 py-2 border border-success">
                                        <i class="fas fa-rupee-sign me-1"></i> <?php echo $amount; ?>
                                    </span>
                                </td>
                                <td class="text-600">
                                    <?php echo date('d M Y, h:i A', strtotime($row['created_at'])); ?>
                                </td>
                                <td class="text-end pe-4">
                                    <button class="btn btn-sm btn-falcon-success fw-bold px-3 shadow-none" 
                                            data-json="<?php echo $secure_json_data; ?>" 
                                            data-reference="<?php echo htmlspecialchars($row['reference_no']); ?>" 
                                            data-name="<?php echo htmlspecialchars($row['applicant_name']); ?>"
                                            data-pdf="<?php echo htmlspecialchars($row['pdf_link']); ?>"
                                            onclick="viewDetails(this)">
                                        <i class="fas fa-eye me-1"></i> View Details
                                    </button>
                                    <a href="<?php echo htmlspecialchars($row['pdf_link']); ?>" target="_blank" class="btn btn-sm btn-success shadow-none px-3">
                                        <i class="fas fa-file-pdf me-1"></i> PDF
                                    </a>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="py-4 text-500 fst-italic">
                                <i class="fas fa-inbox me-2"></i>No records found. Search a RTPS certificate first.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    function viewDetails(btn) {
        let reference = btn.getAttribute('data-reference');
        let name = btn.getAttribute('data-name');
        let pdfLink = btn.getAttribute('data-pdf');
        
        // Direct JSON Parse - FULL DATA
        let rawData = btn.getAttribute('data-json');
        let data = JSON.parse(rawData);

        // Build HTML Table dynamically
        let htmlTable = `
            <div class="table-responsive mt-3" style="max-height: 400px; overflow-y: auto;">
                <table class="table table-bordered table-sm fs-10 text-start align-middle">
                    <tbody>
                        <tr>
                            <td class="fw-bold bg-200" style="width: 35%;"><i class="fas fa-hashtag me-2 text-primary"></i>Reference Number</td>
                            <td><strong>${data.reference || reference || 'N/A'}</strong></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-user me-2 text-info"></i>Applicant Name</td>
                            <td><strong>${data.name || name || 'N/A'}</strong></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-file-pdf me-2 text-danger"></i>PDF Download Link</td>
                            <td><a href="${pdfLink}" target="_blank" class="btn btn-sm btn-danger"><i class="fas fa-download me-1"></i> Download PDF</a></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-check-circle me-2 text-success"></i>Status</td>
                            <td><span class="badge bg-success">${data.status || 'Success'}</span></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-server me-2"></i>Provider</td>
                            <td>${data.result?.Provider || data.Provider || 'N/A'}</td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-shield-alt me-2 text-warning"></i>Captcha Used</td>
                            <td><span class="badge bg-warning text-dark">${data.result?.captcha_used || data.captcha_used || 'N/A'}</span></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-receipt me-2 text-info"></i>Transaction ID</td>
                            <td><span class="font-monospace small">${data.transaction?.transaction_id || 'N/A'}</span></td>
                        </tr>
                        <tr>
                            <td class="fw-bold bg-200"><i class="fas fa-rupee-sign me-2 text-success"></i>Deducted Amount</td>
                            <td><strong>₹${data.transaction?.deducted_amount || '2.00'}</strong></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        `;

        // Pop-up show karna
        Swal.fire({
            title: `<h5 class="mb-0 text-success"><i class="fas fa-file-pdf me-2"></i>RTPS Certificate Details</h5>
                    <div class="mt-1">
                        <span class="badge badge-subtle-primary fs-11">Ref: ${reference}</span>
                        <span class="badge badge-subtle-info fs-11 ms-2">Name: ${name}</span>
                    </div>`,
            html: htmlTable,
            width: '750px',
            confirmButtonText: 'Close',
            customClass: { 
                confirmButton: 'btn btn-success shadow-none px-4',
                title: 'text-success'
            },
            buttonsStyling: false
        });
    }
</script>

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