<?php
if (!defined('ABSPATH')) {
    exit;
}

global $wpdb;
$user_id = get_current_user_id();
// $currency_symbol = '₦'; // Assuming default or available globally

// Pagination
$per_page = 20;
$page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
$offset = ($page - 1) * $per_page;

// Fetch Verifications
$table_name = $wpdb->prefix . 'vtupress_verifications';
$total_query = "SELECT COUNT(*) FROM $table_name WHERE user_id = %d";
$total_items = $wpdb->get_var($wpdb->prepare($total_query, $user_id));
$total_pages = ceil($total_items / $per_page);

$transactions = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM $table_name WHERE user_id = %d ORDER BY id DESC LIMIT %d OFFSET %d",
        $user_id,
        $per_page,
        $offset
    ),
    ARRAY_A
);

?>

<div class="container-fluid history-container mt-4">
    <style>
        .history-container * { font-family: 'Roboto', sans-serif; }
        .vtupress-glass { background: rgba(255,255,255,0.7); backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.3); border-radius: 15px; padding: 20px; box-shadow: 0 8px 32px 0 rgba(31,38,135,0.07); transition: all 0.3s ease; }
        
        @media print {
            @page { size: auto; margin: 0mm; }
            body * { visibility: hidden; }
            #printableModal { position: fixed; left: 0; top: 0; width: 100%; height: 100%; margin: 0; padding: 0; overflow: visible; display: block !important; visibility: visible; background: white; z-index: 9999; }
            #printableModal .modal-dialog { margin: 0; width: 100%; max-width: 100%; }
            #printableModal .modal-content { border: none; box-shadow: none; }
            #printableModal .modal-header, #printableModal .modal-footer, #printableModal .btn-close { display: none; }
            #printableModal .modal-body { padding: 0; visibility: visible; }
            #printableArea { visibility: visible; width: 100%; }
            #printableArea * { visibility: visible; }
        }
    </style>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-uppercase">Verification History</h3>
    </div>

    <div class="card vtupress-glass border-0" style="display: block;">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="verification-history-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Type</th>
                            <th>Number</th>
                            <th>Charge</th>
                            <th>Card Type</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $txn): ?>
                        <tr>
                            <td><?= $txn['id'] ?></td>
                            <td><span class="badge bg-secondary"><?= strtoupper($txn['type']) ?></span></td>
                            <td><?= $txn['value'] ?></td>
                            <td><?= $currency_symbol ?? '₦' ?><?= number_format($txn['fund_amount'], 2) ?></td>
                            <td><?= ucfirst(str_replace('_', ' ', $txn['card_type'])) ?></td>
                            <td><span class="badge bg-<?= ($txn['status'] == 'approved' || $txn['status'] == 'success') ? 'success' : 'warning' ?>"><?= ucfirst($txn['status']) ?></span></td>
                            <td><?= $txn['the_time'] ?></td>
                            <td>
                                <button class="btn btn-sm btn-primary view-verification" data-id="<?= $txn['id'] ?>">
                                    <i class="fas fa-eye"></i> View
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($transactions)): ?>
                            <tr><td colspan="8" class="text-center">No verifications found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                            <a class="page-link" href="?vend=history&page2=ng_verification&paged=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Full Screen Modal for Print -->
<div class="modal fade" id="printableModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen"> 
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">ID Card Preview</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body bg-white d-flex justify-content-center align-items-center">
                <div id="printableArea" style="width: 100%; height: 100%; overflow: auto; display:flex; justify-content: center; align-items: start; padding-top: 20px;">
                    <!-- Content populated via AJAX -->
                    <div class="spinner-border text-primary" role="status" style="display:none;">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <!-- <button type="button" class="btn btn-success" onclick="window.print()">Print</button> -->
                <button class="btn btn-primary me-2 download" print="no" did="page-content" name="premium">Download</button>

            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    $('.view-verification').on('click', function(e) {
        e.preventDefault();
        let id = $(this).data('id');
        let container = $('#printableArea');
        let spinner = container.find('.spinner-border');
        
        container.contents().not(spinner).remove(); // Clear previous content except spinner
        spinner.show();
        $('#printableModal').modal('show');

        $.ajax({
            url: vtupressobj.ajax_url,
            method: 'POST',
            data: {
                action: 'vtupress_view_verification',
                id: id
            },
            success: function(response) {
                spinner.hide();
                container.html(response);
            },
            error: function() {
                spinner.hide();
                container.html('<div class="alert alert-danger">Failed to load verification data.</div>');
            }
        });
    });
});
</script>
