<?= $this->extend('admin/layout') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <!-- Header Section -->
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-4 border-bottom">
        <div>
            <h1 class="h2 mb-0">
                <i class="bi bi-unlock-fill text-primary me-2"></i>
                Tips Unlock Records
            </h1>
            <p class="text-muted small mb-0">Monitor and manage tip unlock transactions</p>
        </div>
        <div class="btn-toolbar mb-2 mb-md-0">
            <div class="btn-group me-2">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="exportData()">
                    <i class="bi bi-download"></i> Export
                </button>
                <button type="button" class="btn btn-outline-secondary btn-sm" onclick="refreshTable()">
                    <i class="bi bi-arrow-clockwise"></i> Refresh
                </button>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title mb-0">Total Unlocked</h6>
                            <h4 class="mb-0" id="totalUnlocked">
                                <?= array_sum(array_column(array_filter($unlocks, function($u) { return $u['unlock_status'] == 1; }), 'unlock_status')) ?>
                            </h4>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-unlock fs-2 opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-warning text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title mb-0">Still Locked</h6>
                            <h4 class="mb-0" id="totalLocked">
                                <?= count(array_filter($unlocks, function($u) { return $u['unlock_status'] == 0; })) ?>
                            </h4>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-lock fs-2 opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-info text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title mb-0">Total Records</h6>
                            <h4 class="mb-0" id="totalRecords"><?= count($unlocks) ?></h4>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-list-ul fs-2 opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h6 class="card-title mb-0">Today's Unlocks</h6>
                            <h4 class="mb-0" id="todayUnlocks">
                                <?= count(array_filter($unlocks, function($u) { 
                                    return date('Y-m-d', strtotime($u['created_at'])) == date('Y-m-d'); 
                                })) ?>
                            </h4>
                        </div>
                        <div class="align-self-center">
                            <i class="bi bi-calendar-day fs-2 opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters Section -->
    <div class="card mb-4">
        <div class="card-header">
            <h6 class="card-title mb-0">
                <i class="bi bi-funnel"></i> Filters
            </h6>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-md-3">
                    <label for="statusFilter" class="form-label">Status</label>
                    <select class="form-select" id="statusFilter">
                        <option value="">All Status</option>
                        <option value="1">Unlocked</option>
                        <option value="0">Locked</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="dateFromFilter" class="form-label">Date From</label>
                    <input type="date" class="form-control" id="dateFromFilter">
                </div>
                <div class="col-md-3">
                    <label for="dateToFilter" class="form-label">Date To</label>
                    <input type="date" class="form-control" id="dateToFilter">
                </div>
                <div class="col-md-3">
                    <label for="msisdnFilter" class="form-label">MSISDN</label>
                    <input type="text" class="form-control" id="msisdnFilter" placeholder="Search by phone number">
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-12">
                    <button type="button" class="btn btn-primary" onclick="applyFilters()">
                        <i class="bi bi-search"></i> Apply Filters
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="clearFilters()">
                        <i class="bi bi-x-circle"></i> Clear Filters
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Tips Unlock Table -->
    <div class="card shadow-sm">
        <div class="card-header bg-white">
            <h6 class="card-title mb-0">
                <i class="bi bi-table"></i> Unlock Records
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="unlockTable" class="table table-striped table-hover mb-0">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>MSISDN</th>
                            <th>Tip Details</th>
                            <th>Transaction ID</th>
                            <th>Status</th>
                            <th>Created At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($unlocks)): ?>
                            <tr>
                                <td colspan="7" class="text-center py-5">
                                    <div class="text-muted">
                                        <i class="bi bi-info-circle-fill fs-1 text-muted mb-3"></i>
                                        <h5>No unlock records found</h5>
                                        <p class="mb-0">There are no tip unlock records to display at this time.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($unlocks as $unlock): ?>
                                <tr>
                                    <td>
                                        <span class="fw-bold">#<?= $unlock['id'] ?></span>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="bi bi-phone text-muted me-2"></i>
                                            <span class="font-monospace"><?= $unlock['msisdn'] ?></span>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <a href="<?= base_url('admin/tips/view/' . $unlock['tip_id']) ?>" 
                                               class="text-decoration-none fw-semibold">
                                                <?= $unlock['tip_title'] ?? 'Tip #' . $unlock['tip_id'] ?>
                                            </a>
                                            <br>
                                            <small class="text-muted">ID: <?= $unlock['tip_id'] ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <code class="text-primary"><?= $unlock['transaction_id'] ?></code>
                                    </td>
                                    <td>
                                        <?php if ($unlock['unlock_status'] == 1): ?>
                                            <span class="badge bg-success rounded-pill">
                                                <i class="bi bi-unlock-fill"></i> Unlocked
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-warning rounded-pill">
                                                <i class="bi bi-lock-fill"></i> Locked
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div>
                                            <span class="fw-semibold"><?= date('M d, Y', strtotime($unlock['created_at'])) ?></span>
                                            <br>
                                            <small class="text-muted"><?= date('H:i:s', strtotime($unlock['created_at'])) ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="viewDetails(<?= $unlock['id'] ?>)" 
                                                    title="View Details">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" 
                                                    onclick="copyTransactionId('<?= $unlock['transaction_id'] ?>')" 
                                                    title="Copy Transaction ID">
                                                <i class="bi bi-clipboard"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Details Modal -->
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="detailsModalLabel">
                    <i class="bi bi-info-circle"></i> Unlock Details
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="detailsModalBody">
                <!-- Details will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable
    const table = $('#unlockTable').DataTable({
        order: [[5, 'desc']], // Sort by created_at by default
        pageLength: 25,
        responsive: true,
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                className: 'btn btn-success btn-sm',
                text: '<i class="bi bi-file-excel"></i> Excel'
            },
            {
                extend: 'pdf',
                className: 'btn btn-danger btn-sm',
                text: '<i class="bi bi-file-pdf"></i> PDF'
            },
            {
                extend: 'print',
                className: 'btn btn-secondary btn-sm',
                text: '<i class="bi bi-printer"></i> Print'
            }
        ],
        language: {
            search: "Search records:",
            lengthMenu: "Show _MENU_ records per page",
            info: "Showing _START_ to _END_ of _TOTAL_ records",
            infoEmpty: "No records available",
            infoFiltered: "(filtered from _MAX_ total records)",
            zeroRecords: "No matching records found",
            emptyTable: "No data available in table"
        },
        columnDefs: [
            {
                targets: [6], // Actions column
                orderable: false
            }
        ]
    });

    // Custom filtering functions
    $('#statusFilter').on('change', function() {
        const value = $(this).val();
        if (value === '') {
            table.column(4).search('').draw();
        } else {
            const searchTerm = value === '1' ? 'Unlocked' : 'Locked';
            table.column(4).search(searchTerm).draw();
        }
    });

    $('#msisdnFilter').on('keyup', function() {
        table.column(1).search(this.value).draw();
    });

    // Date range filtering
    $('#dateFromFilter, #dateToFilter').on('change', function() {
        table.draw();
    });

    // Custom date range filter
    $.fn.dataTable.ext.search.push(
        function(settings, data, dataIndex) {
            const dateFrom = $('#dateFromFilter').val();
            const dateTo = $('#dateToFilter').val();
            
            if (!dateFrom && !dateTo) {
                return true;
            }
            
            const dateStr = data[5]; // Created At column
            const rowDate = new Date(dateStr.split('<br>')[0]);
            const fromDate = dateFrom ? new Date(dateFrom) : null;
            const toDate = dateTo ? new Date(dateTo) : null;
            
            if (fromDate && rowDate < fromDate) {
                return false;
            }
            if (toDate && rowDate > toDate) {
                return false;
            }
            
            return true;
        }
    );
});

// Utility functions
function refreshTable() {
    $('#unlockTable').DataTable().ajax.reload();
    showToast('Table refreshed successfully!', 'success');
}

function exportData() {
    const table = $('#unlockTable').DataTable();
    table.buttons('.buttons-excel').trigger();
}

function applyFilters() {
    $('#unlockTable').DataTable().draw();
    showToast('Filters applied successfully!', 'info');
}

function clearFilters() {
    $('#statusFilter').val('');
    $('#dateFromFilter').val('');
    $('#dateToFilter').val('');
    $('#msisdnFilter').val('');
    $('#unlockTable').DataTable().search('').columns().search('').draw();
    showToast('Filters cleared successfully!', 'info');
}

function viewDetails(unlockId) {
    // This would typically fetch details via AJAX
    const modalBody = `
        <div class="row">
            <div class="col-md-6">
                <strong>Unlock ID:</strong> #${unlockId}
            </div>
            <div class="col-md-6">
                <strong>Status:</strong> <span class="badge bg-success">Unlocked</span>
            </div>
        </div>
        <hr>
        <p><strong>Note:</strong> This is a placeholder for detailed view. In a real implementation, this would fetch and display complete unlock details via AJAX.</p>
    `;
    
    $('#detailsModalBody').html(modalBody);
    $('#detailsModal').modal('show');
}

function copyTransactionId(transactionId) {
    navigator.clipboard.writeText(transactionId).then(function() {
        showToast('Transaction ID copied to clipboard!', 'success');
    }, function(err) {
        showToast('Failed to copy transaction ID', 'error');
    });
}

function showToast(message, type = 'info') {
    const toastHtml = `
        <div class="toast align-items-center text-white bg-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'info'} border-0" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="bi bi-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-triangle' : 'info-circle'}"></i>
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;
    
    // Create toast container if it doesn't exist
    if (!$('#toastContainer').length) {
        $('body').append('<div id="toastContainer" class="toast-container position-fixed top-0 end-0 p-3"></div>');
    }
    
    $('#toastContainer').append(toastHtml);
    $('.toast').last().toast('show');
}
</script>

<!-- Include DataTables CSS and JS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
<script type="text/javascript" src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>

<?= $this->endSection() ?>