<?php
$title = 'ICT Assets Management';
$active = 'ict';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// Ensure variables are defined with defaults
$assets = isset($assets) ? $assets : [];
$statistics = isset($statistics) ? $statistics : [
    'total' => 0,
    'by_category' => [],
    'total_value' => 0
];

// Get zones for filter dropdown from controller
$zones = isset($zones) ? $zones : [];
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-server"></i>
                ICT Assets Management
            </h1>
            <p>Manage all ICT equipment, hardware, and software assets</p>
        </div>
        <div class="header-actions">
            <?php if (Auth::can('ict.create')): ?>
            <a href="<?php echo BASE_URL; ?>/ict/create" class="btn btn-success">
                <i class="fas fa-plus-circle"></i> Add New ICT Asset
            </a>
            <?php endif; ?>
            <?php if (Auth::can('reports.export')): ?>
            <a href="<?php echo BASE_URL; ?>/ict/export" class="btn btn-outline">
                <i class="fas fa-download"></i> Export
            </a>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Success Message Display -->
<?php
$successMessage = Session::get('success', '');
if (!empty($successMessage)):
?>
<div class="alert alert-success alert-dismissible fade show" role="alert" id="successAlert">
    <i class="fas fa-check-circle"></i>
    <?php echo Security::escape($successMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('success');
endif; 
?>

<?php
$errorMessage = Session::get('error', '');
if (!empty($errorMessage)):
?>
<div class="alert alert-danger alert-dismissible fade show" role="alert" id="errorAlert">
    <i class="fas fa-exclamation-circle"></i>
    <?php echo Security::escape($errorMessage); ?>
    <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'">&times;</button>
</div>
<?php 
    Session::remove('error');
endif; 
?>

   <!-- Statistics Cards -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon total">
            <i class="fas fa-server"></i>
        </div>
        <div class="stat-details">
            <h4>Total Assets</h4>
            <p class="stat-number"><?php echo number_format($statistics['total'] ?? 0); ?></p>
        </div>
    </div>
    <?php
    // Define all possible categories with their icons and colors
    $allCategories = [
        'Hardware' => ['icon' => 'fa-microchip', 'color' => 'hardware'],
        'Software' => ['icon' => 'fa-code', 'color' => 'software'],
        'Network' => ['icon' => 'fa-network-wired', 'color' => 'network'],
        'Server' => ['icon' => 'fa-server', 'color' => 'server'],
        'Peripheral' => ['icon' => 'fa-keyboard', 'color' => 'peripheral']
    ];
    
    // Display all categories from the array
    foreach ($allCategories as $categoryName => $categoryInfo):
        $count = $statistics['by_category'][$categoryName] ?? 0;
    ?>
    <div class="stat-card">
        <div class="stat-icon <?php echo $categoryInfo['color']; ?>">
            <i class="fas <?php echo $categoryInfo['icon']; ?>"></i>
        </div>
        <div class="stat-details">
            <h4><?php echo $categoryName; ?></h4>
            <p class="stat-number"><?php echo number_format($count); ?></p>
        </div>
    </div>
    <?php endforeach; ?>
    
    <div class="stat-card">
        <div class="stat-icon value">
            <i class="fas fa-money-bill-wave"></i>
        </div>
        <div class="stat-details">
            <h4>Total Value</h4>
            <p class="stat-number total-value" id="totalValue">₦<?php echo number_format($statistics['total_value'] ?? 0, 2); ?></p>
        </div>
    </div>
</div>

    <!-- Filters -->
    <div class="filter-section">
        <div class="filter-header" onclick="toggleFilters()">
            <h3><i class="fas fa-filter"></i> Filter ICT Assets</h3>
            <i class="fas fa-chevron-down" id="filterToggleIcon"></i>
        </div>
        <div class="filter-body" id="filterBody" style="display: block;">
            <div class="filter-grid">
                <div class="filter-group">
                    <label>Search</label>
                    <input type="text" id="searchAssets" class="form-control" placeholder="Search by name, serial, IP...">
                </div>
                <div class="filter-group">
                    <label>Category</label>
                    <select id="filterCategory" class="form-control">
                        <option value="">All Categories</option>
                        <option value="Hardware">Hardware</option>
                        <option value="Software">Software</option>
                        <option value="Network">Network</option>
                        <option value="Server">Server</option>
                        <option value="Peripheral">Peripheral</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Status</label>
                    <select id="filterStatus" class="form-control">
                        <option value="">All Status</option>
                        <option value="Under Maintenance">Under Maintenance</option>
                        <option value="Decommissioned">Decommissioned</option>
                        <option value="Operational">Operational</option>
                        <option value="Faulty">Faulty</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label>Zone</label>
                    <select id="filterZone" class="form-control">
                        <option value="">All Zones</option>
                        <?php if (!empty($zones) && is_array($zones)): ?>
                            <?php foreach ($zones as $zone): ?>
                                <option value="<?php echo $zone['id'] ?? ''; ?>">
                                    <?php echo Security::escape($zone['zone_name'] ?? ''); ?>
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>
            </div>
            <div class="filter-actions">
                <button class="btn btn-primary" onclick="applyFilters()">
                    <i class="fas fa-filter"></i> Apply Filters
                </button>
                <button class="btn btn-outline" onclick="resetFilters()">
                    <i class="fas fa-times"></i> Clear Filters
                </button>
            </div>
        </div>
    </div>

    <!-- ICT Assets Table -->
    <div class="content-card">
        <div class="section-title">
            <h2><i class="fas fa-list"></i> ICT Assets Register</h2>
            <div class="card-actions">
                <span class="record-count">Showing <span id="recordCount"><?php echo count($assets); ?></span> records</span>
            </div>
        </div>

        <div class="table-responsive">
            <?php if (empty($assets)): ?>
                <div class="empty-state">
                    <i class="fas fa-server"></i>
                    <p>No ICT assets found</p>
                    <?php if (Auth::can('ict.create')): ?>
                    <a href="<?php echo BASE_URL; ?>/ict/create" class="btn btn-primary">
                        <i class="fas fa-plus"></i> Add First Asset
                    </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
            <table class="asset-table" id="ictTable">
                <thead>
                    <tr>
                        <th data-sort="text">S/N</th>
                        <th data-sort="text">Asset Code</th>
                        <th data-sort="text">Description</th>
                        <th data-sort="text">Category</th>
                        <th data-sort="text">Manufacturer</th>
                        <th data-sort="text">Model</th>
                        <th data-sort="text">Serial Number</th>
                        <th data-sort="text">Location</th>
                        <th data-sort="text">Status</th>
                        <th data-sort="text">IP Address</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assets as $index => $asset): ?>
                    <tr data-category="<?php echo $asset['asset_category'] ?? ''; ?>" 
                        data-status="<?php echo strtolower($asset['current_status'] ?? ''); ?>"
                        data-zone="<?php echo $asset['zone_id'] ?? ''; ?>">
                        <td><?php echo $index + 1; ?></td>
                        <td>
                            <span class="asset-code"><?php echo Security::escape($asset['asset_code'] ?? ''); ?></span>
                        </td>
                        <td><?php echo Security::escape($asset['asset_description'] ?? ''); ?></td>
                        <td>
                            <?php 
                            $category = $asset['asset_category'] ?? '';
                            $categoryClass = '';
                            if ($category == 'Hardware') $categoryClass = 'badge-hardware';
                            elseif ($category == 'Software') $categoryClass = 'badge-software';
                            elseif ($category == 'Network') $categoryClass = 'badge-network';
                            elseif ($category == 'Server') $categoryClass = 'badge-server';
                            else $categoryClass = 'badge-peripheral';
                            ?>
                            <span class="badge <?php echo $categoryClass; ?>">
                                <?php echo Security::escape($category); ?>
                            </span>
                        </td>
                        <td><?php echo Security::escape($asset['manufacturer'] ?? '-'); ?></td>
                        <td><?php echo Security::escape($asset['model_version'] ?? '-'); ?></td>
                        <td>
                            <?php if (!empty($asset['serial_number'])): ?>
                                <span class="serial-number"><?php echo Security::escape($asset['serial_number']); ?></span>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php 
                            $location = [];
                            if (!empty($asset['location'])) $location[] = $asset['location'];
                            if (!empty($asset['lga_name'])) $location[] = $asset['lga_name'];
                            if (!empty($asset['state_name'])) $location[] = $asset['state_name'];
                            echo Security::escape(implode(', ', $location));
                            ?>
                        </td>
                        <td>
                            <?php 
                            $status = $asset['current_status'] ?? '';
                            $statusClass = '';
                            if ($status == 'In Use') $statusClass = 'status-active';
                            elseif ($status == 'Available') $statusClass = 'status-available';
                            elseif ($status == 'Under Repair') $statusClass = 'status-warning';
                            elseif ($status == 'Decommissioned') $statusClass = 'status-rejected';
                            ?>
                            <span class="status-badge <?php echo $statusClass; ?>">
                                <?php echo Security::escape($status ?: 'Not Set'); ?>
                            </span>
                        </td>
                        <td>
                            <?php if (!empty($asset['ip_address'])): ?>
                                <code><?php echo Security::escape($asset['ip_address']); ?></code>
                            <?php else: ?>
                                -
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="<?php echo BASE_URL; ?>/ict/show/<?php echo $asset['id'] ?? ''; ?>" 
                                   class="btn-icon" title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <?php if (Auth::can('ict.edit')): ?>
                                <a href="<?php echo BASE_URL; ?>/ict/edit/<?php echo $asset['id'] ?? ''; ?>" 
                                   class="btn-icon" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <?php endif; ?>
                                <?php if (Auth::can('ict.delete')): ?>
                                <a href="<?php echo BASE_URL; ?>/ict/delete/<?php echo $asset['id'] ?? ''; ?>" 
                                   class="btn-icon delete" title="Delete"
                                   onclick="return confirm('Are you sure you want to delete this ICT asset?')">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
        
        <!-- Pagination -->
        <div class="pagination" id="pagination"></div>
    </div>
</div>

<style>
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 25px;
}

.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    min-width: 0; /* Allow flex items to shrink */
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    flex-shrink: 0;
}

.stat-icon.total {
    background: #e3f2fd;
    color: #1976d2;
}

.stat-icon.hardware {
    background: #e8f5e9;
    color: #388e3c;
}

.stat-icon.software {
    background: #fff3e0;
    color: #f57c00;
}

.stat-icon.network {
    background: #e0f2f1;
    color: #00796b;
}

.stat-icon.server {
    background: #d1c4e9;
    color: #512da8;
}

.stat-icon.peripheral {
    background: #e1f5fe;
    color: #0277bd;
}

.stat-icon.value {
    background: #d1c4e9;
    color: #512da8;
}

.stat-details {
    flex: 1;
    min-width: 0; /* Allow text truncation */
}

.stat-details h4 {
    margin: 0 0 5px 0;
    font-size: 0.9rem;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.stat-number {
    font-weight: bold;
    margin: 0;
    color: var(--text-primary);
    line-height: 1.3;
    word-wrap: break-word;
    word-break: break-word;
    white-space: normal;
}

/* Responsive font sizes for numbers */
.stat-number {
    font-size: 1.8rem;
}

/* Adjust font size based on number length */
.stat-number[data-length="long"] {
    font-size: 1.4rem;
}

.stat-number[data-length="very-long"] {
    font-size: 1.2rem;
}

.stat-number[data-length="extreme"] {
    font-size: 1rem;
}

.stat-number.total-value {
    letter-spacing: -0.5px;
}

/* For very large numbers, allow wrapping */
.stat-number.total-value {
    word-break: break-all;
    white-space: normal;
}

/* Tablet devices */
@media (max-width: 992px) {
    .stat-number {
        font-size: 1.5rem;
    }
    
    .stat-number[data-length="long"] {
        font-size: 1.2rem;
    }
    
    .stat-number[data-length="very-long"] {
        font-size: 1rem;
    }
    
    .stat-number[data-length="extreme"] {
        font-size: 0.9rem;
    }
}

/* Mobile devices */
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
    }
    
    .stat-card {
        padding: 15px;
        gap: 10px;
    }
    
    .stat-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }
    
    .stat-number {
        font-size: 1.2rem;
    }
    
    .stat-number[data-length="long"] {
        font-size: 1rem;
    }
    
    .stat-number[data-length="very-long"] {
        font-size: 0.9rem;
    }
    
    .stat-number[data-length="extreme"] {
        font-size: 0.8rem;
    }
    
    .stat-details h4 {
        font-size: 0.8rem;
    }
}

/* Small mobile devices */
@media (max-width: 480px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .stat-card {
        max-width: 100%;
    }
}

/* Filter Section */
.filter-section {
    background: white;
    border-radius: 10px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    overflow: hidden;
}

.filter-header {
    padding: 15px 20px;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
    color: white;
    cursor: pointer;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.filter-header h3 {
    margin: 0;
    font-size: 1rem;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-header i {
    transition: transform 0.3s ease;
}

.filter-body {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 15px;
}

.filter-group {
    display: flex;
    flex-direction: column;
}

.filter-group label {
    font-size: 0.85rem;
    color: var(--text-secondary);
    margin-bottom: 5px;
    font-weight: 600;
}

.filter-group input,
.filter-group select {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 0.9rem;
}

.filter-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
}

/* Category Badges */
.badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
}

.badge-hardware {
    background: #e8f5e9;
    color: #2e7d32;
}

.badge-software {
    background: #fff3e0;
    color: #ef6c00;
}

.badge-network {
    background: #e0f2f1;
    color: #00695c;
}

.badge-server {
    background: #d1c4e9;
    color: #512da8;
}

.badge-peripheral {
    background: #e1f5fe;
    color: #0277bd;
}

.serial-number {
    font-family: 'Courier New', monospace;
    font-size: 0.85rem;
    background: var(--light-bg);
    padding: 2px 6px;
    border-radius: 4px;
}

code {
    font-family: 'Courier New', monospace;
    background: #272822;
    color: #f8f8f2;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 0.85rem;
}

/* Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.85rem;
    font-weight: 600;
}

.status-active {
    background: #d4edda;
    color: #155724;
}

.status-available {
    background: #d1ecf1;
    color: #0c5460;
}

.status-warning {
    background: #fff3cd;
    color: #856404;
}

.status-rejected {
    background: #f8d7da;
    color: #721c24;
}

/* Pagination */
.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.page-link {
    padding: 8px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    color: var(--text-primary);
    text-decoration: none;
    transition: all 0.3s;
    cursor: pointer;
    background: white;
}

.page-link:hover {
    background: var(--light-bg);
    border-color: var(--success-color);
}

.page-link.active {
    background: var(--success-color);
    color: white;
    border-color: var(--success-color);
}

.page-link:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.page-info {
    color: var(--text-secondary);
    font-size: 0.9rem;
}

/* Empty State */
.empty-state {
    text-align: center;
    padding: 40px;
    color: var(--text-secondary);
}

.empty-state i {
    font-size: 3rem;
    margin-bottom: 15px;
    opacity: 0.5;
}

.empty-state p {
    font-size: 1rem;
    margin: 0 0 15px 0;
}

.record-count {
    font-size: 0.9rem;
    color: var(--text-secondary);
}

@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .filter-actions {
        flex-direction: column;
    }
}
/* Alert Styles */
.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d4edda;
    border: 1px solid #c3e6cb;
    color: #155724;
}

.alert-danger {
    background: #f8d7da;
    border: 1px solid #f5c6cb;
    color: #721c24;
}

.alert i {
    font-size: 1.2rem;
}

.btn-close {
    margin-left: auto;
    background: none;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    color: inherit;
    opacity: 0.7;
}

.btn-close:hover {
    opacity: 1;
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}
</style>

<script>
let currentPage = 1;
const rowsPerPage = 10;
let filteredRows = [];

function toggleFilters() {
    const filterBody = document.getElementById('filterBody');
    const toggleIcon = document.getElementById('filterToggleIcon');
    
    if (filterBody.style.display === 'none') {
        filterBody.style.display = 'block';
        toggleIcon.className = 'fas fa-chevron-up';
    } else {
        filterBody.style.display = 'none';
        toggleIcon.className = 'fas fa-chevron-down';
    }
}

function applyFilters() {
    const searchTerm = document.getElementById('searchAssets').value.toLowerCase().trim();
    const category = document.getElementById('filterCategory').value;
    const status = document.getElementById('filterStatus').value.toLowerCase();
    const zone = document.getElementById('filterZone').value;
    
    const rows = document.querySelectorAll('#ictTable tbody tr');
    filteredRows = [];
    
    rows.forEach(row => {
        let show = true;
        
        // Search filter
        if (searchTerm !== '') {
            const text = row.textContent.toLowerCase();
            show = show && text.includes(searchTerm);
        }
        
        // Category filter
        if (category !== '' && show) {
            const categoryCell = row.querySelector('.badge');
            if (categoryCell) {
                show = categoryCell.textContent.trim() === category;
            }
        }
        
        // Status filter
        if (status !== '' && show) {
            const statusCell = row.querySelector('.status-badge');
            if (statusCell) {
                show = statusCell.textContent.trim().toLowerCase() === status;
            }
        }
        
        // Zone filter
        if (zone !== '' && show) {
            show = row.dataset.zone === zone;
        }
        
        if (show) {
            filteredRows.push(row);
        }
    });
    
    updateDisplay();
}

function resetFilters() {
    document.getElementById('searchAssets').value = '';
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterStatus').value = '';
    document.getElementById('filterZone').value = '';
    
    const rows = document.querySelectorAll('#ictTable tbody tr');
    filteredRows = Array.from(rows);
    
    updateDisplay();
}

function updateDisplay() {
    const totalRecords = filteredRows.length;
    document.getElementById('recordCount').textContent = totalRecords;
    
    // Hide all rows first
    document.querySelectorAll('#ictTable tbody tr').forEach(row => {
        row.style.display = 'none';
    });
    
    if (totalRecords === 0) {
        document.getElementById('pagination').innerHTML = '';
        return;
    }
    
    // Show only current page
    const start = (currentPage - 1) * rowsPerPage;
    const end = Math.min(start + rowsPerPage, totalRecords);
    
    for (let i = start; i < end; i++) {
        if (filteredRows[i]) {
            filteredRows[i].style.display = '';
        }
    }
    
    updatePagination(totalRecords);
}

function updatePagination(totalRecords) {
    const totalPages = Math.ceil(totalRecords / rowsPerPage);
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = `
        <button class="page-link" onclick="changePage(${currentPage - 1})" ${currentPage === 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i> Previous
        </button>
        <span class="page-info">Page ${currentPage} of ${totalPages}</span>
        <button class="page-link" onclick="changePage(${currentPage + 1})" ${currentPage === totalPages ? 'disabled' : ''}>
            Next <i class="fas fa-chevron-right"></i>
        </button>
    `;
    
    pagination.innerHTML = html;
}

function changePage(page) {
    currentPage = page;
    updateDisplay();
}

// Function to format and adjust font size for large numbers
function formatAndAdjustNumber(element) {
    if (!element) return;
    
    let valueText = element.textContent;
    let numericValue = parseFloat(valueText.replace(/[^0-9.-]+/g, ''));
    
    if (isNaN(numericValue)) return;
    
    // Store the full value as a data attribute for tooltip
    element.setAttribute('data-full-value', valueText);
    element.setAttribute('title', 'Full amount: ' + valueText);
    
    // Get the number of digits (excluding decimal and formatting)
    let digits = Math.floor(Math.abs(numericValue)).toString().length;
    
    // Remove any existing length attributes
    element.removeAttribute('data-length');
    
    // Add data-length attribute based on digit count
    if (digits >= 15) {
        element.setAttribute('data-length', 'extreme');
    } else if (digits >= 12) {
        element.setAttribute('data-length', 'very-long');
    } else if (digits >= 9) {
        element.setAttribute('data-length', 'long');
    }
    
    // Format with appropriate abbreviation for extreme numbers
    if (numericValue >= 1000000000000) { // Trillions
        let formattedTrillions = (numericValue / 1000000000000).toFixed(2);
        element.innerHTML = '₦' + formattedTrillions + 'T';
        element.setAttribute('title', 'Full amount: ' + valueText + ' (₦' + formattedTrillions + ' Trillion)');
    } 
    else if (numericValue >= 1000000000) { // Billions
        let formattedBillions = (numericValue / 1000000000).toFixed(2);
        element.innerHTML = '₦' + formattedBillions + 'B';
        element.setAttribute('title', 'Full amount: ' + valueText + ' (₦' + formattedBillions + ' Billion)');
    } 
    else if (numericValue >= 1000000) { // Millions
        let formattedMillions = (numericValue / 1000000).toFixed(2);
        element.innerHTML = '₦' + formattedMillions + 'M';
        element.setAttribute('title', 'Full amount: ' + valueText + ' (₦' + formattedMillions + ' Million)');
    }
    // For smaller numbers, keep as is but adjust font size if needed
    else {
        // Already formatted correctly
        // Check if text overflows and adjust font size dynamically
        adjustFontSizeToFit(element);
    }
}

// Function to dynamically adjust font size to fit container
function adjustFontSizeToFit(element) {
    if (!element || !element.parentElement) return;
    
    const container = element.parentElement;
    const maxWidth = container.clientWidth;
    let fontSize = parseFloat(window.getComputedStyle(element).fontSize);
    let originalFontSize = fontSize;
    
    // Create a temporary span to measure text width
    const tempSpan = document.createElement('span');
    tempSpan.style.visibility = 'hidden';
    tempSpan.style.position = 'absolute';
    tempSpan.style.whiteSpace = 'nowrap';
    tempSpan.style.fontSize = fontSize + 'px';
    tempSpan.style.fontWeight = window.getComputedStyle(element).fontWeight;
    tempSpan.textContent = element.textContent;
    document.body.appendChild(tempSpan);
    
    let textWidth = tempSpan.offsetWidth;
    
    // Reduce font size if text is wider than container
    while (textWidth > maxWidth && fontSize > 10) {
        fontSize = fontSize * 0.9;
        tempSpan.style.fontSize = fontSize + 'px';
        textWidth = tempSpan.offsetWidth;
    }
    
    // Apply new font size if changed
    if (fontSize !== originalFontSize) {
        element.style.fontSize = fontSize + 'px';
    }
    
    // Clean up
    document.body.removeChild(tempSpan);
}

// Initialize on page load with enhanced number handling
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#ictTable tbody tr');
    filteredRows = Array.from(rows);
    document.getElementById('recordCount').textContent = filteredRows.length;
    
    // Format and adjust total value
    const totalValueElement = document.getElementById('totalValue');
    if (totalValueElement) {
        formatAndAdjustNumber(totalValueElement);
    }
    
    // Also adjust all stat numbers
    document.querySelectorAll('.stat-number').forEach(element => {
        // For category counts, just adjust font size if needed
        const text = element.textContent;
        const numericValue = parseFloat(text.replace(/,/g, ''));
        
        if (!isNaN(numericValue) && numericValue >= 10000) {
            adjustFontSizeToFit(element);
        }
    });
    
    // Handle window resize to readjust font sizes
    let resizeTimeout;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            document.querySelectorAll('.stat-number').forEach(element => {
                if (element.id === 'totalValue') {
                    formatAndAdjustNumber(element);
                } else {
                    adjustFontSizeToFit(element);
                }
            });
        }, 250);
    });
});

// Debounced search
let searchTimeout;
if (document.getElementById('searchAssets')) {
    document.getElementById('searchAssets').addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentPage = 1;
            applyFilters();
        }, 300);
    });
}

if (document.getElementById('filterCategory')) {
    document.getElementById('filterCategory').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

if (document.getElementById('filterStatus')) {
    document.getElementById('filterStatus').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

if (document.getElementById('filterZone')) {
    document.getElementById('filterZone').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('#ictTable tbody tr');
    filteredRows = Array.from(rows);
    document.getElementById('recordCount').textContent = filteredRows.length;
    
    // Format total value
    const totalValueElement = document.getElementById('totalValue');
    if (totalValueElement) {
        formatLargeNumber(totalValueElement);
    }
    
    // Add scroll handling for all stat numbers
    document.querySelectorAll('.stat-number').forEach(element => {
        if (element.scrollWidth > element.clientWidth) {
            element.style.cursor = 'ew-resize';
            element.addEventListener('wheel', function(e) {
                if (e.deltaY !== 0) {
                    e.preventDefault();
                    this.scrollLeft += e.deltaY;
                }
            });
        }
    });
});

// Debounced search
let searchTimeout;
if (document.getElementById('searchAssets')) {
    document.getElementById('searchAssets').addEventListener('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentPage = 1;
            applyFilters();
        }, 300);
    });
}

if (document.getElementById('filterCategory')) {
    document.getElementById('filterCategory').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

if (document.getElementById('filterStatus')) {
    document.getElementById('filterStatus').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

if (document.getElementById('filterZone')) {
    document.getElementById('filterZone').addEventListener('change', function() {
        currentPage = 1;
        applyFilters();
    });
}

// Auto-hide success/error messages after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    const successAlert = document.getElementById('successAlert');
    if (successAlert) {
        setTimeout(function() {
            successAlert.style.display = 'none';
        }, 5000);
    }
    
    const errorAlert = document.getElementById('errorAlert');
    if (errorAlert) {
        setTimeout(function() {
            errorAlert.style.display = 'none';
        }, 5000);
    }
});
</script>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>