<?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 chassis_rc_pdf_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-danger-subtle shadow-none me-3">
                        <span class="fas fa-file-pdf text-danger fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-danger fs-10 mb-0">History Log</h6>
                        <h4 class="text-primary fw-bold mb-0">Chassis to RC PDF <span class="fw-medium">Records</span></h4>
                    </div>
                </div>
                <div class="col-md-auto mt-3 mt-md-0">
                    <a href="Chassis_Rc_Pdf.php" class="btn btn-sm btn-danger shadow-none fw-bold">
                        <i class="fas fa-search me-1"></i> Search New Chassis
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card mb-3 border-0 shadow-sm border-top border-4 border-danger">
    <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>Chassis No.</th>
                        <th>Registration No.</th>
                        <th>Owner Name</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()): 
                            // Format amount
                            $amount = !empty($row['deducted_amount']) ? '₹' . number_format($row['deducted_amount'], 2) : '₹3.00';
                        ?>
                            <tr>
                                <td class="py-3 fw-bold">#<?php echo $row['id']; ?></td>
                                <td>
                                    <span class="badge badge-subtle-warning fs-11 px-3 py-2 font-monospace border border-warning">
                                        <i class="fas fa-barcode me-1"></i> <?php echo htmlspecialchars($row['chassis_no']); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-primary fs-11 px-3 py-2 border border-primary">
                                        <i class="fas fa-id-card me-1"></i> <?php echo htmlspecialchars($row['registration_no'] ?? 'N/A'); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge badge-subtle-secondary fs-11 px-3 py-2 border border-secondary">
                                        <i class="fas fa-user me-1"></i> <?php echo htmlspecialchars($row['full_name'] ?? '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">
                                    <!-- Hidden Textarea to store Base64 safely -->
                                    <textarea id="pdf_base64_<?php echo $row['id']; ?>" class="d-none"><?php echo htmlspecialchars($row['base64_pdf']); ?></textarea>
                                    
                                    <!-- Direct Download Button -->
                                    <button class="btn btn-sm btn-falcon-danger fw-bold px-3 shadow-none" 
                                            onclick="downloadPDF('<?php echo $row['id']; ?>', '<?php echo htmlspecialchars($row['chassis_no']); ?>')">
                                        <i class="fas fa-download me-1"></i> Download PDF
                                    </button>
                                </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 chassis number first.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    // Pure JS function to force download a Base64 PDF directly
    function downloadPDF(rowId, chassisNo) {
        let base64Str = document.getElementById('pdf_base64_' + rowId).value;
        
        // Check if PDF data exists
        if(!base64Str || base64Str.trim() === '') {
            Swal.fire('Error', 'PDF Data is missing or corrupted for this record.', 'error');
            return;
        }

        try {
            // Remove any potential header if it was included in base64 (Optional safeguard)
            let base64Data = base64Str.replace(/^data:application\/pdf;base64,/, "");

            // Decode base64 string to binary data
            const byteCharacters = atob(base64Data);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            
            // Create a Blob (Binary Large Object) for robust cross-browser download
            const blob = new Blob([byteArray], {type: 'application/pdf'});
            const blobUrl = URL.createObjectURL(blob);
            
            // Create a temporary hidden link element to trigger the download
            const link = document.createElement('a');
            link.href = blobUrl;
            link.download = 'RC_Details_' + chassisNo + '.pdf'; // File Name Set Here
            
            document.body.appendChild(link);
            link.click(); // Trigger direct download
            
            // Cleanup and remove the element
            document.body.removeChild(link);
            URL.revokeObjectURL(blobUrl);

            // Optional: Small success notification
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 2500,
                timerProgressBar: true
            });
            Toast.fire({
                icon: 'success',
                title: 'PDF Downloaded Successfully!'
            });

        } catch (error) {
            console.error("PDF Download Error: ", error);
            Swal.fire('Error', 'Failed to generate PDF. The data might be corrupted.', 'error');
        }
    }
</script>

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