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

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-0">
            <i class="bi bi-people text-primary"></i> User Points
        </h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0">
                <li class="breadcrumb-item"><a href="<?= base_url('admin') ?>" class="text-decoration-none">Dashboard</a></li>
                <li class="breadcrumb-item active" aria-current="page">User Points</li>
            </ol>
        </nav>
    </div>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-primary" onclick="refreshData()">
            <i class="bi bi-arrow-clockwise"></i> Refresh
        </button>
        <button class="btn btn-info" onclick="exportPoints()">
            <i class="bi bi-download"></i> Export
        </button>
        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#bulkAwardModal">
            <i class="bi bi-gift"></i> Bulk Award
        </button>
    </div>
</div>

<!-- Statistics Cards -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-people-fill text-primary fs-2"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="card-title text-muted mb-0">Total Users</h6>
                        <h4 class="mb-0"><?= count($users) ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-coin text-warning fs-2"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="card-title text-muted mb-0">Total Points</h6>
                        <h4 class="mb-0"><?= number_format(array_sum(array_column($users, 'points'))) ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-graph-up text-success fs-2"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="card-title text-muted mb-0">Average Points</h6>
                        <h4 class="mb-0"><?= count($users) > 0 ? number_format(array_sum(array_column($users, 'points')) / count($users)) : '0' ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0">
                        <i class="bi bi-trophy-fill text-danger fs-2"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="card-title text-muted mb-0">Highest Points</h6>
                        <h4 class="mb-0"><?= count($users) > 0 ? number_format(max(array_column($users, 'points'))) : '0' ?></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filters and Search -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label">Search by Phone</label>
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-search"></i></span>
                    <input type="text" class="form-control" id="searchPhone" placeholder="Enter phone number...">
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Points Range</label>
                <select class="form-select" id="pointsRange">
                    <option value="">All Users</option>
                    <option value="0-100">0 - 100 Points</option>
                    <option value="101-500">101 - 500 Points</option>
                    <option value="501-1000">501 - 1,000 Points</option>
                    <option value="1001-5000">1,001 - 5,000 Points</option>
                    <option value="5001+">5,000+ Points</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Sort By</label>
                <select class="form-select" id="sortBy">
                    <option value="points-desc">Points (High to Low)</option>
                    <option value="points-asc">Points (Low to High)</option>
                    <option value="phone-asc">Phone Number (A-Z)</option>
                    <option value="updated-desc">Last Updated (Recent)</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">&nbsp;</label>
                <button class="btn btn-outline-secondary d-block w-100" onclick="clearFilters()">
                    <i class="bi bi-x-circle"></i> Clear
                </button>
            </div>
        </div>
    </div>
</div>

<!-- User Points Table -->
<div class="card border-0 shadow-sm">
    <div class="card-header bg-white">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="bi bi-people me-2"></i>Users with Points
            </h5>
            <small class="text-muted">Showing <span id="showingCount"><?= count($users) ?></span> of <?= count($users) ?> users</small>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0" id="userPointsTable">
                <thead class="table-light">
                    <tr>
                        <th style="width: 40px;">
                            <input type="checkbox" class="form-check-input" id="selectAll">
                        </th>
                        <th>Phone Number</th>
                        <th>Points Balance</th>
                        <th>Points Level</th>
                        <th>Last Updated</th>
                        <th>Status</th>
                        <th style="width: 200px;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($users)): ?>
                    <tr id="noDataRow">
                        <td colspan="7" class="text-center py-5">
                            <i class="bi bi-inbox text-muted fs-1"></i>
                            <p class="text-muted mt-2">No users with points found.</p>
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($users as $user): ?>
                        <?php 
                        $points = $user['points'];
                        $level = '';
                        $levelClass = '';
                        
                        if ($points >= 5000) {
                            $level = 'Platinum';
                            $levelClass = 'warning';
                        } elseif ($points >= 1000) {
                            $level = 'Gold';
                            $levelClass = 'warning';
                        } elseif ($points >= 500) {
                            $level = 'Silver';
                            $levelClass = 'secondary';
                        } elseif ($points >= 100) {
                            $level = 'Bronze';
                            $levelClass = 'success';
                        } else {
                            $level = 'Starter';
                            $levelClass = 'primary';
                        }
                        
                        $lastUpdated = strtotime($user['updated_at']);
                        $daysSinceUpdate = floor((time() - $lastUpdated) / (24 * 60 * 60));
                        ?>
                        <tr class="user-row" 
                            data-phone="<?= esc($user['msisdn']) ?>" 
                            data-points="<?= $points ?>"
                            data-updated="<?= $lastUpdated ?>">
                            <td>
                                <input type="checkbox" class="form-check-input row-checkbox" value="<?= esc($user['msisdn']) ?>">
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar-sm bg-light rounded-circle d-flex align-items-center justify-content-center me-2">
                                        <i class="bi bi-person text-muted"></i>
                                    </div>
                                    <div>
                                        <span class="fw-medium"><?= esc($user['msisdn']) ?></span>
                                        <br>
                                        <small class="text-muted">ID: <?= $user['id'] ?? 'N/A' ?></small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <i class="bi bi-coin text-warning me-2"></i>
                                    <span class="fw-bold text-primary fs-5"><?= number_format($points) ?></span>
                                </div>
                            </td>
                            <td>
                                <span class="badge bg-<?= $levelClass ?> px-2 py-1">
                                    <i class="bi bi-award me-1"></i><?= $level ?>
                                </span>
                            </td>
                            <td>
                                <div>
                                    <small class="text-muted">
                                        <?= date('M j, Y', $lastUpdated) ?>
                                    </small>
                                    <br>
                                    <small class="text-muted">
                                        <?= date('g:i A', $lastUpdated) ?>
                                    </small>
                                </div>
                            </td>
                            <td>
                                <?php if ($daysSinceUpdate <= 7): ?>
                                    <span class="badge bg-success">Active</span>
                                <?php elseif ($daysSinceUpdate <= 30): ?>
                                    <span class="badge bg-warning">Inactive</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Dormant</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="<?= base_url('admin/award-points?msisdn=' . $user['msisdn']) ?>" 
                                       class="btn btn-success" title="Award Points">
                                        <i class="bi bi-gift"></i>
                                    </a>
                                    <button class="btn btn-outline-primary" onclick="viewHistory('<?= esc($user['msisdn']) ?>')" title="View History">
                                        <i class="bi bi-clock-history"></i>
                                    </button>
                                    <button class="btn btn-outline-info" onclick="viewProfile('<?= esc($user['msisdn']) ?>')" title="View Profile">
                                        <i class="bi bi-person-circle"></i>
                                    </button>
                                    <button class="btn btn-outline-warning" onclick="adjustPoints('<?= esc($user['msisdn']) ?>', <?= $points ?>)" title="Adjust Points">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Bulk Award Modal -->
<div class="modal fade" id="bulkAwardModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Bulk Award Points</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    <span id="selectedCount">0</span> users selected for bulk award.
                </div>
                <form id="bulkAwardForm">
                    <div class="mb-3">
                        <label class="form-label">Points to Award</label>
                        <input type="number" class="form-control" name="points" min="1" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reason</label>
                        <textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for awarding points..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" onclick="submitBulkAward()">
                    <i class="bi bi-gift"></i> Award Points
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Adjust Points Modal -->
<div class="modal fade" id="adjustPointsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Adjust Points</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="adjustPointsForm">
                    <input type="hidden" name="msisdn" id="adjustMsisdn">
                    <div class="mb-3">
                        <label class="form-label">Phone Number</label>
                        <input type="text" class="form-control" id="adjustPhoneDisplay" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Current Points</label>
                        <input type="text" class="form-control" id="currentPoints" readonly>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Adjustment Type</label>
                        <select class="form-select" name="type" id="adjustmentType">
                            <option value="add">Add Points</option>
                            <option value="subtract">Subtract Points</option>
                            <option value="set">Set Points</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Points</label>
                        <input type="number" class="form-control" name="points" min="0" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reason</label>
                        <textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for adjustment..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" onclick="submitAdjustment()">
                    <i class="bi bi-pencil-square"></i> Adjust Points
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Search and Filter functionality
document.getElementById('searchPhone').addEventListener('input', filterTable);
document.getElementById('pointsRange').addEventListener('change', filterTable);
document.getElementById('sortBy').addEventListener('change', sortTable);

// Select all functionality
document.getElementById('selectAll').addEventListener('change', function() {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    checkboxes.forEach(cb => cb.checked = this.checked);
    updateSelectedCount();
});

// Update selected count when individual checkboxes change
document.addEventListener('change', function(e) {
    if (e.target.classList.contains('row-checkbox')) {
        updateSelectedCount();
    }
});

function updateSelectedCount() {
    const selected = document.querySelectorAll('.row-checkbox:checked').length;
    document.getElementById('selectedCount').textContent = selected;
}

function filterTable() {
    const searchPhone = document.getElementById('searchPhone').value.toLowerCase();
    const pointsRange = document.getElementById('pointsRange').value;
    
    const rows = document.querySelectorAll('.user-row');
    let visibleCount = 0;
    
    rows.forEach(row => {
        const phone = row.dataset.phone.toLowerCase();
        const points = parseInt(row.dataset.points);
        
        const matchesPhone = phone.includes(searchPhone);
        const matchesRange = checkPointsRange(points, pointsRange);
        
        if (matchesPhone && matchesRange) {
            row.style.display = '';
            visibleCount++;
        } else {
            row.style.display = 'none';
        }
    });
    
    document.getElementById('showingCount').textContent = visibleCount;
}

function checkPointsRange(points, range) {
    if (!range) return true;
    
    switch(range) {
        case '0-100': return points >= 0 && points <= 100;
        case '101-500': return points >= 101 && points <= 500;
        case '501-1000': return points >= 501 && points <= 1000;
        case '1001-5000': return points >= 1001 && points <= 5000;
        case '5001+': return points >= 5001;
        default: return true;
    }
}

function sortTable() {
    const sortBy = document.getElementById('sortBy').value;
    const tbody = document.querySelector('#userPointsTable tbody');
    const rows = Array.from(tbody.querySelectorAll('.user-row'));
    
    rows.sort((a, b) => {
        switch(sortBy) {
            case 'points-desc':
                return parseInt(b.dataset.points) - parseInt(a.dataset.points);
            case 'points-asc':
                return parseInt(a.dataset.points) - parseInt(b.dataset.points);
            case 'phone-asc':
                return a.dataset.phone.localeCompare(b.dataset.phone);
            case 'updated-desc':
                return parseInt(b.dataset.updated) - parseInt(a.dataset.updated);
            default:
                return 0;
        }
    });
    
    rows.forEach(row => tbody.appendChild(row));
}

function clearFilters() {
    document.getElementById('searchPhone').value = '';
    document.getElementById('pointsRange').value = '';
    document.getElementById('sortBy').value = 'points-desc';
    filterTable();
    sortTable();
}

function refreshData() {
    location.reload();
}

function exportPoints() {
    // Implement export functionality
    console.log('Export points data');
}

function viewHistory(msisdn) {
    // Implement view history functionality
    console.log('View history for:', msisdn);
}

function viewProfile(msisdn) {
    // Implement view profile functionality
    console.log('View profile for:', msisdn);
}

function adjustPoints(msisdn, currentPoints) {
    document.getElementById('adjustMsisdn').value = msisdn;
    document.getElementById('adjustPhoneDisplay').value = msisdn;
    document.getElementById('currentPoints').value = currentPoints.toLocaleString();
    
    const modal = new bootstrap.Modal(document.getElementById('adjustPointsModal'));
    modal.show();
}

function submitBulkAward() {
    const selectedUsers = Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => cb.value);
    
    if (selectedUsers.length === 0) {
        alert('Please select at least one user.');
        return;
    }
    
    const formData = new FormData(document.getElementById('bulkAwardForm'));
    formData.append('users', JSON.stringify(selectedUsers));
    
    // Implement bulk award submission
    console.log('Bulk award:', Object.fromEntries(formData));
    
    // Close modal after successful submission
    bootstrap.Modal.getInstance(document.getElementById('bulkAwardModal')).hide();
}

function submitAdjustment() {
    const formData = new FormData(document.getElementById('adjustPointsForm'));
    
    // Implement adjustment submission
    console.log('Adjust points:', Object.fromEntries(formData));
    
    // Close modal after successful submission
    bootstrap.Modal.getInstance(document.getElementById('adjustPointsModal')).hide();
}
</script>

<style>
.avatar-sm {
    width: 32px;
    height: 32px;
}

.card {
    transition: box-shadow 0.15s ease-in-out;
}

.card:hover {
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(13, 110, 253, 0.04);
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
}

.badge {
    font-size: 0.75em;
}

.user-row {
    transition: background-color 0.2s ease;
}

.fs-2 {
    font-size: 2rem !important;
}

.fs-5 {
    font-size: 1.25rem !important;
}

.bg-light {
    background-color: #f8f9fa !important;
}
</style>
<?= $this->endSection() ?>