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

global $wpdb;
$user_id = get_current_user_id();
$users = new Users();
$vp_id = $users->getUser($user_id, true, true)["id"];
// $currency_symbol = '₦'; // Assuming default

// Service Information
$current_service = $service_key ?? 'recharge_card';
// Access the service object if available relative to the parent scope, or re-fetch
$service_obj = Vtupress_Service_Container::get($current_service); 
$service_name = $service_obj ? $service_obj->name : $current_service;

// Fetch Transactions for THIS service only
$transactions = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}vtupress_transactions WHERE user_id = %d AND service = %s ORDER BY id DESC LIMIT 1000",
        $vp_id,
        $current_service
    ),
    ARRAY_A
);

// Calculate Summary
$summary = [
    'pending' => 0,
    'successful' => 0,
    'failed' => 0,
    'success_amount' => 0.00,
];

foreach ($transactions as $txn) {
    $status = strtolower($txn['status'] ?? '');
    if ($status === 'pending' || $status === 'processing')
        $summary['pending']++;
    if ($status === 'success' || $status === 'successful') {
        $summary['successful']++;
        $summary['success_amount'] += (float) ($txn['amount'] ?? 0);
    }
    if (in_array($status, ['failed', 'cancled', 'reversed']))
        $summary['failed']++;
}
?>

<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; display: flex; align-items: center; height: 100%; }
        .vtupress-glass:hover { transform: translateY(-5px); box-shadow: 0 12px 40px 0 rgba(31,38,135,0.12); background: rgba(255, 255, 255, 0.85); }
        .glass-icon { width: 50px; height: 50px; border-radius: 12px; display: flex; align-items: center; justify-content: center; margin-right: 15px; font-size: 1.6rem; }
        .glass-content h6 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; margin-bottom: 5px; color: #6c757d; }
        .glass-content h3 { margin: 0; font-weight: 700; color: #2d3436; }
        
        .glass-pending .glass-icon { background: rgba(255, 193, 7, 0.15); color: #ffc107; }
        .glass-success .glass-icon { background: rgba(40, 167, 69, 0.15); color: #28a745; }
        .glass-failed .glass-icon { background: rgba(220, 53, 69, 0.15); color: #dc3545; }
        .glass-amount .glass-icon { background: rgba(0, 123, 255, 0.15); color: #007bff; }

        /* Printable Card Styles - Grid Layout */
        #printableArea {
            display: grid;
            grid-template-columns: repeat(4, 1fr); /* 4 Columns Fixed */
            gap: 5mm; /* Space between cards */
            width: 100%;
        }
        
        .pin-card-wrapper {
            page-break-inside: avoid;
            break-inside: avoid;
        }

        .pin-card { 
            border: 1px dashed #000; 
            padding: 8px; 
            background: #fff; 
            text-align: left; /* User requested left align */
            font-size: 11px;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            box-sizing: border-box;
            position: relative;
        }

        .pin-card .header-row {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            border-bottom: 1px dotted #ccc;
            padding-bottom: 3px;
        }

        .pin-card .logo-img {
            max-height: 25px;
            max-width: 25px;
            margin-right: 5px;
            object-fit: contain;
        }

        .pin-card h5 { font-size: 12px; font-weight: bold; margin: 0; color: #000; text-transform: uppercase; }
        .pin-card .plan-name { font-size: 11px; margin-bottom: 2px; font-weight: 600; color: #333; }
        .pin-card .pin-code { 
            font-size: 1rem; 
            font-weight: 900; 
            margin: 5px 0; 
            font-family: 'Courier New', Courier, monospace; 
            word-break: break-all;
            color: #000;
            text-align: center; /* keep pin centered for readability? User said "provider check be to the left... then pin more bigger". Usually PIN is centered, but let's align header left */
        }
        .pin-card .meta { font-size: 9px; color: #555; display: flex; justify-content: space-between; margin-top: auto; }
        
        @media print {
            @page { size: A4; margin: 5mm; }
            body * { visibility: hidden; }
            #printableModal { position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; 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%; height: auto; }
            #printableModal .modal-content { border: none; box-shadow: none; width: 100%; min-height: 100%; }
            #printableModal .modal-header, #printableModal .modal-footer, #printableModal .btn-close { display: none; }
            #printableModal .modal-body { padding: 0; visibility: visible; width: 100%; }
            #printableArea { visibility: visible; width: 100%; display: grid; grid-template-columns: repeat(4, 1fr); gap: 5mm; }
            #printableArea * { visibility: visible; }
            .pin-card { border: 1px solid #000 !important; }
        }
    </style>

    <div class="row mb-4 vtupress-summary">
        <!-- Pending Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="vtupress-glass glass-pending">
                <div class="glass-icon"><i class="mdi mdi-clock-outline"></i></div>
                <div class="glass-content">
                    <h6>Pending</h6>
                    <h3><?= number_format($summary['pending']) ?></h3>
                </div>
            </div>
        </div>
        <!-- Success Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="vtupress-glass glass-success">
                <div class="glass-icon"><i class="mdi mdi-check-decagram-outline"></i></div>
                <div class="glass-content">
                    <h6>Successful</h6>
                    <h3><?= number_format($summary['successful']) ?></h3>
                </div>
            </div>
        </div>
        <!-- Failed Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="vtupress-glass glass-failed">
                <div class="glass-icon"><i class="mdi mdi-close-octagon-outline"></i></div>
                <div class="glass-content">
                    <h6>Failed</h6>
                    <h3><?= number_format($summary['failed']) ?></h3>
                </div>
            </div>
        </div>
        <!-- Amount Card -->
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="vtupress-glass glass-amount">
                <div class="glass-icon"><i class="mdi mdi-currency-ngn"></i></div>
                <div class="glass-content">
                    <h6>Total Success</h6>
                    <h3><?= $currency_symbol . number_format($summary['success_amount'], 2) ?></h3>
                </div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="text-uppercase"><?php echo isset($service_name) ? strtoupper($service_name) : 'PIN HISTORY'; //str_replace('_', ' ', $current_service) ?></h3>
    </div>

    <!-- Bulk Actions -->
    <div class="mb-3">
        <button class="btn btn-primary" id="view-selected-pins" disabled>
            <i class="mdi mdi-printer"></i> View / Print Selected
        </button>
    </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="pin-history-table">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="select-all"></th>
                            <th>ID</th>
                            <th>Provider</th>
                            <th>Plan</th>
                            <th>Qty</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($transactions as $txn): 
                            $details = json_decode($txn['details'], true) ?? [];
                            $pin_raw = (string)($details['pin'] ?? '');
                            $serial_raw = (string)($details['serial'] ?? '');
                            
                            $provider = $details['network'] ?? $details['provider'] ?? $txn['description']; 
                            $plan = $details['plan'] ?? $txn['name']; 
                            
                            $pins = explode(',', $pin_raw);
                            $qty = count(array_filter($pins, function($p) { return trim($p) !== ''; }));
                            $qty = $qty > 0 ? $qty : 1; 
                        ?>
                        <tr data-id="<?= $txn['id'] ?>" 
                            data-pin="<?= esc_attr($pin_raw) ?>" 
                            data-serial="<?= esc_attr($serial_raw) ?>"
                            data-provider="<?= esc_attr($provider) ?>"
                            data-plan="<?= esc_attr($plan) ?>"
                            data-date="<?= esc_attr($txn['created_at']) ?>">
                            
                            <td><input type="checkbox" class="pin-checkbox" value="<?= $txn['id'] ?>"></td>
                            <td><?= $txn['id'] ?></td>
                            <td><span class="fw-bold"><?= strtoupper($provider) ?></span></td>
                            <td><?= $plan ?></td>
                            <td><?= $qty ?></td>
                            <td><?= $currency_symbol . number_format($txn['amount'], 2) ?></td>
                            <td><span class="badge bg-<?= ($txn['status'] == 'success' || $txn['status'] == 'successful') ? 'success' : 'warning' ?>"><?= ucfirst($txn['status']) ?></span></td>
                            <td><?= $txn['created_at'] ?></td>
                            <td>
                                <button class="btn btn-sm btn-info text-white view-single-pin">View</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($transactions)): ?>
                            <tr><td colspan="9" class="text-center">No transactions found for <?= str_replace('_', ' ', $current_service) ?>.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </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">Print Preview</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body bg-white">
                <div class="container-fluid">
                     <div id="printableArea">
                        <!-- Content populated via JS -->
                    </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-primary" onclick="window.print()">Print</button>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(function($) {
    // Select All Logic
    $('#select-all').on('change', function() {
        $('.pin-checkbox').prop('checked', this.checked).trigger('change');
    });

    // Enable/Disable Print Button
    $(document).on('change', '.pin-checkbox', function() {
        let count = $('.pin-checkbox:checked').length;
        $('#view-selected-pins').prop('disabled', count === 0);
        $('#view-selected-pins').text(count > 0 ? `View / Print Selected (${count})` : 'View / Print Selected');
    });

    // View Selected Pins Logic
    $('#view-selected-pins, .view-single-pin').on('click', function(e) {
        e.preventDefault();
        let selectedRows = [];
        
        if ($(this).hasClass('view-single-pin')) {
            selectedRows.push($(this).closest('tr'));
        } else {
            $('.pin-checkbox:checked').each(function() {
                selectedRows.push($(this).closest('tr'));
            });
        }

        if (selectedRows.length === 0) return;

        let container = $('#printableArea');
        container.empty();
        
        // Base URL for images - utilizing PHP injected variable or relative path
        let vtupressUrl = '<?= VTUPRESS_URL; ?>'; 

        selectedRows.forEach(row => {
            let r = $(row);
            let provider = r.data('provider');
            let providerDisplay = provider.toUpperCase();
            let plan = r.data('plan');
            let date = r.data('date');
            
            // Image Logic
            let logoUrl = vtupressUrl + "/images/network/" + provider.toLowerCase() + ".jpeg";
            let fallbackUrl = vtupressUrl + "/images/others.jpeg";

            // Handle multiple pins/serials
            let pinStr = String(r.data('pin'));
            let serialStr = String(r.data('serial'));
            
            let pins = pinStr.split(',');
            let serials = serialStr.split(',');
            
            // Loop through pins
            for (let i = 0; i < pins.length; i++) {
                let currentPin = pins[i].trim();
                if (!currentPin) continue;
                
                let currentSerial = serials[i] ? serials[i].trim() : (serials[0] ? serials[0].trim() : '-'); 

                let cardHtml = `
                    <div class="pin-card-wrapper">
                        <div class="pin-card">
                             <div class="header-row">
                                 <img src="${logoUrl}" class="logo-img" onerror="this.onerror=null;this.src='${fallbackUrl}';">
                                 <h5 class="m-0">${providerDisplay}</h5>
                             </div>
                             <div class="plan-name"><?= $service_key == 'recharge_card'? $currency_symbol : '';?>${plan}</div>
                             <div class="pin-code text-center">${currentPin}</div>
                             <div class="meta">
                                 <span>S/N: ${currentSerial}</span>
                                 <span>${date.split(' ')[0]}</span>
                             </div>
                        </div>
                    </div>
                `;
                container.append(cardHtml);
            }
        });

        $('#printableModal').modal('show');
    });
});
</script>
