<?php
require_once 'config/connection.php';

// Function untuk generate asset number otomatis
function generateAssetNumber($pdo) {
    // Cari asset number terakhir dengan format T000xxx atau AST000
    $stmt = $pdo->query("
        SELECT MAX(
            CASE 
                WHEN asset_number LIKE 'T%' THEN CAST(SUBSTRING(asset_number, 2) AS UNSIGNED)
                WHEN asset_number LIKE 'AST%' THEN CAST(SUBSTRING(asset_number, 4) AS UNSIGNED)
                ELSE 0 
            END
        ) as max_num FROM assets
    ");
    $result = $stmt->fetch();
    $nextNum = ($result['max_num'] ?? 159) + 1; // Start from T000160 format
    return 'T' . str_pad($nextNum, 6, '0', STR_PAD_LEFT);
}

// Function untuk generate barcode number otomatis
function generateBarcodeNumber($pdo) {
    $stmt = $pdo->query("SELECT MAX(CAST(SUBSTRING(barcode_number, 3) AS UNSIGNED)) as max_num FROM assets WHERE barcode_number LIKE 'BC%'");
    $result = $stmt->fetch();
    $nextNum = ($result['max_num'] ?? 159) + 1; // Start from BC160
    return 'BC' . $nextNum;
}

// Function untuk generate SAP code otomatis
function generateSAPCode($pdo) {
    $stmt = $pdo->query("SELECT MAX(CAST(SUBSTRING(kode_material_sap, 4) AS UNSIGNED)) as max_num FROM assets WHERE kode_material_sap LIKE 'SAP%'");
    $result = $stmt->fetch();
    $nextNum = ($result['max_num'] ?? 159) + 1; // Start from SAP160
    return 'SAP' . $nextNum;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['excel_file'])) {
    $uploadedFile = $_FILES['excel_file'];
    $uploadSuccess = false;
    $message = '';
    $importedCount = 0;
    $skippedCount = 0;
    $errorCount = 0;
    $duplicateCount = 0;
    $errors = [];
    $importResults = [];

    if ($uploadedFile['error'] == UPLOAD_ERR_OK) {
        $fileExtension = strtolower(pathinfo($uploadedFile['name'], PATHINFO_EXTENSION));
        
        if (in_array($fileExtension, ['xlsx', 'xls'])) {
            try {
                require_once 'vendor/autoload.php'; // Pastikan PhpSpreadsheet terinstall via Composer
                
                $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader(ucfirst($fileExtension));
                $spreadsheet = $reader->load($uploadedFile['tmp_name']);
                $worksheet = $spreadsheet->getActiveSheet();
                $highestRow = $worksheet->getHighestRow();
                
                if ($highestRow < 2) {
                    throw new Exception('File Excel tidak memiliki data yang valid');
                }
                
                // Start transaction
                $pdo->beginTransaction();
                
                // Process each row (skip header row)
                for ($row = 2; $row <= $highestRow; $row++) {
                    try {
                        // Read data from Excel columns sesuai format baru
                        $assetNumber = trim($worksheet->getCell('A' . $row)->getValue());
                        $barcodeNumber = trim($worksheet->getCell('B' . $row)->getValue());
                        $kodeMaterialSap = trim($worksheet->getCell('C' . $row)->getValue());
                        $assetName = trim($worksheet->getCell('D' . $row)->getValue());
                        $assetCategory = trim($worksheet->getCell('E' . $row)->getValue());
                        $description = trim($worksheet->getCell('F' . $row)->getValue());
                        $kondisi = trim($worksheet->getCell('G' . $row)->getValue());
                        $statusBorrower = trim($worksheet->getCell('H' . $row)->getValue());
                        
                        // Skip empty rows
                        if (empty($assetName) && empty($assetNumber)) {
                            $skippedCount++;
                            continue;
                        }
                        
                        // Validate required fields
                        if (empty($assetName)) {
                            $importResults[] = [
                                'row' => $row,
                                'asset_number' => $assetNumber,
                                'asset_name' => $assetName,
                                'status' => 'error',
                                'message' => 'Nama asset tidak boleh kosong'
                            ];
                            $errorCount++;
                            continue;
                        }
                        
                        // Auto-generate jika kosong
                        if (empty($assetNumber)) {
                            $assetNumber = generateAssetNumber($pdo);
                        }
                        if (empty($barcodeNumber)) {
                            $barcodeNumber = generateBarcodeNumber($pdo);
                        }
                        if (empty($kodeMaterialSap)) {
                            $kodeMaterialSap = generateSAPCode($pdo);
                        }
                        
                        // Set default values
                        if (empty($assetCategory)) {
                            $assetCategory = 'Tools';
                        }
                        if (empty($kondisi) || !in_array($kondisi, ['baik', 'rusak', 'hilang'])) {
                            $kondisi = 'baik';
                        }
                        if (empty($statusBorrower) || !in_array($statusBorrower, ['available', 'borrowed', 'maintenance'])) {
                            $statusBorrower = 'available';
                        }
                        
                        // Check if asset number already exists
                        $stmt = $pdo->prepare("SELECT id FROM assets WHERE asset_number = ?");
                        $stmt->execute([$assetNumber]);
                        
                        if ($stmt->fetch()) {
                            $importResults[] = [
                                'row' => $row,
                                'asset_number' => $assetNumber,
                                'asset_name' => $assetName,
                                'status' => 'duplicate',
                                'message' => 'Asset number sudah ada dalam database'
                            ];
                            $duplicateCount++;
                            continue;
                        }
                        
                        // Prepare insert statement dengan semua field yang sesuai database
                        $stmt = $pdo->prepare("
                            INSERT INTO assets (
                                asset_number, barcode_number, kode_material_sap, 
                                asset_name, asset_category, description, 
                                assigned_employee, assign_date, status, 
                                status_borrower, kondisi, created_at, updated_at
                            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                        ");
                        
                        // Execute insert
                        $stmt->execute([
                            $assetNumber,
                            $barcodeNumber,
                            $kodeMaterialSap,
                            $assetName,
                            $assetCategory,
                            $description ?: null,
                            null, // assigned_employee
                            null, // assign_date
                            'none', // status default
                            $statusBorrower,
                            $kondisi
                        ]);
                        
                        $importResults[] = [
                            'row' => $row,
                            'asset_number' => $assetNumber,
                            'asset_name' => $assetName,
                            'status' => 'success',
                            'message' => 'Berhasil diimport'
                        ];
                        $importedCount++;
                        
                    } catch (PDOException $e) {
                        if ($e->getCode() == 23000) { // Duplicate entry
                            $importResults[] = [
                                'row' => $row,
                                'asset_number' => $assetNumber ?? '',
                                'asset_name' => $assetName ?? '',
                                'status' => 'duplicate',
                                'message' => 'Asset number atau barcode sudah ada'
                            ];
                            $duplicateCount++;
                        } else {
                            $importResults[] = [
                                'row' => $row,
                                'asset_number' => $assetNumber ?? '',
                                'asset_name' => $assetName ?? '',
                                'status' => 'error',
                                'message' => 'Database error: ' . $e->getMessage()
                            ];
                            $errorCount++;
                        }
                    } catch (Exception $e) {
                        $importResults[] = [
                            'row' => $row,
                            'asset_number' => $assetNumber ?? '',
                            'asset_name' => $assetName ?? '',
                            'status' => 'error',
                            'message' => 'Error: ' . $e->getMessage()
                        ];
                        $errorCount++;
                    }
                }
                
                // Commit transaction if there are successful imports
                if ($importedCount > 0) {
                    $pdo->commit();
                    $uploadSuccess = true;
                    $message = "Import selesai! Berhasil: {$importedCount}, Duplikat: {$duplicateCount}, Error: {$errorCount}, Dilewati: {$skippedCount}";
                } else {
                    $pdo->rollback();
                    $uploadSuccess = false;
                    $message = "Import gagal! Tidak ada data yang berhasil diimport. Duplikat: {$duplicateCount}, Error: {$errorCount}, Dilewati: {$skippedCount}";
                }
                
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollback();
                }
                $message = "Error membaca file: " . $e->getMessage();
                $uploadSuccess = false;
            }
        } else {
            $message = "Format file harus .xlsx atau .xls";
            $uploadSuccess = false;
        }
    } else {
        $message = "Error upload file";
        $uploadSuccess = false;
    }
}

// Get existing assets for display dengan informasi lebih lengkap
$stmt = $pdo->prepare("
    SELECT a.*, 
           bh.borrower_employee_id,
           b.full_name as borrower_name,
           DATEDIFF(CURDATE(), a.assign_date) as days_borrowed
    FROM assets a 
    LEFT JOIN borrow_history bh ON a.id = bh.asset_id AND bh.status = 'borrowed'
    LEFT JOIN borrowers b ON bh.borrower_employee_id = b.employee_id
    ORDER BY a.created_at DESC
    LIMIT 100
");
$stmt->execute();
$assets = $stmt->fetchAll();

// Get statistics
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) as count FROM assets")->fetch()['count'],
    'available' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE status_borrower = 'available'")->fetch()['count'],
    'borrowed' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE status_borrower = 'borrowed'")->fetch()['count'],
    'maintenance' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE status_borrower = 'maintenance'")->fetch()['count'],
    'condition_baik' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE kondisi = 'baik'")->fetch()['count'],
    'condition_rusak' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE kondisi = 'rusak'")->fetch()['count'],
    'condition_hilang' => $pdo->query("SELECT COUNT(*) as count FROM assets WHERE kondisi = 'hilang'")->fetch()['count']
];
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Asset Management - Import Excel</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        h1, h2, h3 {
            color: #333;
            margin-bottom: 20px;
        }
        
        h1 {
            border-bottom: 2px solid #4CAF50;
            padding-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .stats-card h3 {
            font-size: 1.8em;
            margin-bottom: 5px;
        }
        
        .stats-card.warning {
            background: linear-gradient(135deg, #ff9800, #f57c00);
        }
        
        .stats-card.danger {
            background: linear-gradient(135deg, #f44336, #d32f2f);
        }
        
        .stats-card.info {
            background: linear-gradient(135deg, #2196F3, #1976D2);
        }
        
        .upload-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 30px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        
        input[type="file"] {
            padding: 12px;
            border: 2px dashed #ddd;
            border-radius: 4px;
            width: 100%;
            background: white;
            font-size: 14px;
        }
        
        input[type="file"]:hover {
            border-color: #4CAF50;
            background: #f0f8f0;
        }
        
        button {
            background: #4CAF50;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        
        button:hover {
            background: #45a049;
        }
        
        .btn-secondary {
            background: #6c757d;
        }
        
        .btn-secondary:hover {
            background: #545b62;
        }
        
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
            font-weight: bold;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 10px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            font-size: 13px;
        }
        
        th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
            position: sticky;
            top: 0;
        }
        
        tr:hover {
            background-color: #f5f5f5;
        }
        
        .status-badge {
            padding: 3px 6px;
            border-radius: 3px;
            font-size: 11px;
            font-weight: bold;
            display: inline-block;
        }
        
        .status-available {
            background: #d4edda;
            color: #155724;
        }
        
        .status-borrowed {
            background: #f8d7da;
            color: #721c24;
        }
        
        .status-maintenance {
            background: #fff3cd;
            color: #856404;
        }
        
        .condition-badge {
            padding: 2px 5px;
            border-radius: 3px;
            font-size: 10px;
            font-weight: bold;
        }
        
        .condition-baik {
            background: #d4edda;
            color: #155724;
        }
        
        .condition-rusak {
            background: #fff3cd;
            color: #856404;
        }
        
        .condition-hilang {
            background: #f8d7da;
            color: #721c24;
        }
        
        .template-info {
            background: #e7f3ff;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border-left: 4px solid #2196F3;
        }
        
        .template-info h3 {
            margin-bottom: 10px;
            color: #1976D2;
        }
        
        .template-info ul {
            margin-left: 20px;
        }
        
        .template-info li {
            margin-bottom: 5px;
        }
        
        .results-container {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-top: 20px;
        }
        
        .import-status-success {
            background: #d4edda;
            color: #155724;
        }
        
        .import-status-error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .import-status-duplicate {
            background: #fff3cd;
            color: #856404;
        }
        
        .overdue-highlight {
            background-color: #ffebee !important;
            border-left: 4px solid #f44336;
        }
        
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            
            table {
                font-size: 11px;
            }
            
            th, td {
                padding: 6px 4px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>
            Asset Management - Import dari Excel
            <div style="font-size: 0.6em; color: #666;">
                <?php echo date('d/m/Y H:i:s'); ?> WIB
            </div>
        </h1>
        
        <!-- Statistics Dashboard -->
        <div class="stats-grid">
            <div class="stats-card">
                <h3><?php echo $stats['total']; ?></h3>
                <p>Total Asset</p>
            </div>
            <div class="stats-card">
                <h3><?php echo $stats['available']; ?></h3>
                <p>Tersedia</p>
            </div>
            <div class="stats-card warning">
                <h3><?php echo $stats['borrowed']; ?></h3>
                <p>Dipinjam</p>
            </div>
            <div class="stats-card info">
                <h3><?php echo $stats['maintenance']; ?></h3>
                <p>Maintenance</p>
            </div>
            <div class="stats-card">
                <h3><?php echo $stats['condition_baik']; ?></h3>
                <p>Kondisi Baik</p>
            </div>
            <div class="stats-card warning">
                <h3><?php echo $stats['condition_rusak']; ?></h3>
                <p>Kondisi Rusak</p>
            </div>
            <div class="stats-card danger">
                <h3><?php echo $stats['condition_hilang']; ?></h3>
                <p>Hilang</p>
            </div>
        </div>
        
        <?php if (isset($message)): ?>
            <div class="alert <?php echo $uploadSuccess ? 'alert-success' : 'alert-error'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <div class="template-info">
            <h3>📋 Format Excel yang Diterima:</h3>
            <ul>
                <li><strong>Kolom A:</strong> Asset Number (opsional - auto-generate format T000xxx)</li>
                <li><strong>Kolom B:</strong> Barcode Number (opsional - auto-generate format BCxxx)</li>
                <li><strong>Kolom C:</strong> Kode Material SAP (opsional - auto-generate format SAPxxx)</li>
                <li><strong>Kolom D:</strong> Asset Name (wajib diisi)</li>
                <li><strong>Kolom E:</strong> Asset Category (default: Tools)</li>
                <li><strong>Kolom F:</strong> Description (opsional)</li>
                <li><strong>Kolom G:</strong> Kondisi (baik/rusak/hilang - default: baik)</li>
                <li><strong>Kolom H:</strong> Status Borrower (available/borrowed/maintenance - default: available)</li>
            </ul>
            <p><strong>Catatan:</strong> Baris pertama dianggap sebagai header dan akan dilewati saat import.</p>
        </div>
        
        <div class="upload-section">
            <h2>Upload File Excel</h2>
            <form method="POST" enctype="multipart/form-data" onsubmit="return validateUpload()">
                <div class="form-group">
                    <label for="excel_file">Pilih File Excel (.xlsx atau .xls):</label>
                    <input type="file" name="excel_file" id="excel_file" accept=".xlsx,.xls" required>
                </div>
                <button type="submit">📤 Import Data</button>
                <button type="button" onclick="downloadTemplate()" class="btn-secondary">📥 Download Template</button>
            </form>
        </div>
        
        <!-- Import Results -->
        <?php if (!empty($importResults)): ?>
        <div class="upload-section">
            <h2>Hasil Import (<?php echo count($importResults); ?> data diproses)</h2>
            
            <div class="results-container">
                <table>
                    <thead>
                        <tr>
                            <th>Baris</th>
                            <th>Asset Number</th>
                            <th>Asset Name</th>
                            <th>Status</th>
                            <th>Keterangan</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($importResults as $result): ?>
                        <tr class="import-status-<?php echo $result['status']; ?>">
                            <td><?php echo $result['row']; ?></td>
                            <td><?php echo htmlspecialchars($result['asset_number']); ?></td>
                            <td><?php echo htmlspecialchars($result['asset_name']); ?></td>
                            <td>
                                <span class="status-badge">
                                    <?php 
                                    switch($result['status']) {
                                        case 'success': echo '✅ Berhasil'; break;
                                        case 'error': echo '❌ Error'; break;
                                        case 'duplicate': echo '⚠️ Duplikat'; break;
                                        default: echo ucfirst($result['status']);
                                    }
                                    ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($result['message']); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
        
        <h2>Data Asset Saat Ini (<?php echo count($assets); ?> terakhir)</h2>
        <div class="results-container">
            <table>
                <thead>
                    <tr>
                        <th>Asset Number</th>
                        <th>Barcode</th>
                        <th>Kode SAP</th>
                        <th>Nama Asset</th>
                        <th>Kategori</th>
                        <th>Kondisi</th>
                        <th>Status</th>
                        <th>Peminjam</th>
                        <th>Tanggal Input</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($assets as $asset): ?>
                    <tr <?php echo ($asset['status_borrower'] == 'borrowed' && $asset['days_borrowed'] > 7) ? 'class="overdue-highlight"' : ''; ?>>
                        <td><strong><?php echo htmlspecialchars($asset['asset_number']); ?></strong></td>
                        <td><?php echo htmlspecialchars($asset['barcode_number']); ?></td>
                        <td><?php echo htmlspecialchars($asset['kode_material_sap'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($asset['asset_name']); ?></td>
                        <td><?php echo htmlspecialchars($asset['asset_category']); ?></td>
                        <td>
                            <span class="condition-badge condition-<?php echo $asset['kondisi']; ?>">
                                <?php echo ucfirst($asset['kondisi']); ?>
                            </span>
                        </td>
                        <td>
                            <span class="status-badge status-<?php echo $asset['status_borrower']; ?>">
                                <?php echo ucfirst($asset['status_borrower']); ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($asset['status_borrower'] == 'borrowed' && $asset['borrower_name']): ?>
                                <strong><?php echo htmlspecialchars($asset['borrower_name']); ?></strong><br>
                                <small><?php echo htmlspecialchars($asset['borrower_employee_id']); ?></small>
                                <?php if ($asset['days_borrowed'] > 7): ?>
                                <br><span style="color: #f44336; font-weight: bold;">⚠️ <?php echo $asset['days_borrowed']; ?> hari</span>
                                <?php endif; ?>
                            <?php else: ?>
                                <span style="color: #666;">-</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo date('d/m/Y H:i', strtotime($asset['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        function validateUpload() {
            const fileInput = document.getElementById('excel_file');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('Pilih file Excel terlebih dahulu!');
                return false;
            }
            
            const allowedExtensions = ['.xlsx', '.xls'];
            const fileName = file.name.toLowerCase();
            const isValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
            
            if (!isValidExtension) {
                alert('File harus berformat .xlsx atau .xls!');
                return false;
            }
            
            const maxSize = 10 * 1024 * 1024; // 10MB
            if (file.size > maxSize) {
                alert('Ukuran file maksimal 10MB!');
                return false;
            }
            
            // Show loading
            const submitButton = document.querySelector('button[type="submit"]');
            submitButton.textContent = '⏳ Mengimport...';
            submitButton.disabled = true;
            
            return confirm('Yakin ingin mengimport data dari file "' + file.name + '"?\n\nPastikan format file sudah sesuai dengan template.');
        }
        
        function downloadTemplate() {
            // Create Excel template content
            const template = `Asset Number,Barcode Number,Kode Material SAP,Asset Name,Asset Category,Description,Kondisi,Status Borrower
T000001,BC001,SAP001,Laptop Dell Inspiron 15,Electronics,Laptop untuk keperluan kerja,baik,available
T000002,BC002,SAP002,Projector Epson EB-X41,Electronics,Projector untuk presentasi,baik,available
T000003,BC003,SAP003,Hammer Tool Set,Tools,Set palu untuk maintenance,baik,available
,,,Drill Set Makita,Tools,Set bor lengkap untuk maintenance,baik,available
,,,Safety Helmet,Safety,Helm pengaman kerja,rusak,maintenance`;
            
            const blob = new Blob([template], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', 'template_assets.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } else {
                alert('Browser Anda tidak mendukung download otomatis. Silakan copy data template secara manual.');
            }
        }
        
        // File input enhancement
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('excel_file');
            const originalLabel = fileInput.parentElement.querySelector('label').textContent;
            
            fileInput.addEventListener('change', function() {
                const fileName = this.files[0] ? this.files[0].name : '';
                const label = this.parentElement.querySelector('label');
                
                if (fileName) {
                    label.textContent = originalLabel + ' - ' + fileName;
                    label.style.color = '#4CAF50';
                } else {
                    label.textContent = originalLabel;
                    label.style.color = '#555';
                }
            });
            
            // Drag and drop functionality
            fileInput.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.style.borderColor = '#4CAF50';
                this.style.backgroundColor = '#f0f8f0';
            });
            
            fileInput.addEventListener('dragleave', function(e) {
                e.preventDefault();
                this.style.borderColor = '#ddd';
                this.style.backgroundColor = 'white';
            });
            
            fileInput.addEventListener('drop', function(e) {
                e.preventDefault();
                this.style.borderColor = '#ddd';
                this.style.backgroundColor = 'white';
                
                if (e.dataTransfer.files.length > 0) {
                    this.files = e.dataTransfer.files;
                    this.dispatchEvent(new Event('change'));
                }
            });
        });
        
        // Auto-refresh after successful import
        <?php if (isset($uploadSuccess) && $uploadSuccess): ?>
        setTimeout(() => {
            if (confirm('Import berhasil! Refresh halaman untuk melihat data terbaru?')) {
                location.reload();
            }
        }, 3000);
        <?php endif; ?>
        
        // Search functionality
        function searchAssets() {
            const searchValue = document.getElementById('searchAssets').value.toLowerCase();
            const table = document.querySelector('.results-container table');
            const rows = table.getElementsByTagName('tr');
            
            for (let i = 1; i < rows.length; i++) {
                const row = rows[i];
                const text = row.textContent.toLowerCase();
                
                if (text.includes(searchValue)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            }
        }
        
        // Add search box
        document.addEventListener('DOMContentLoaded', function() {
            const h2 = document.querySelector('h2');
            if (h2 && h2.textContent.includes('Data Asset Saat Ini')) {
                const searchDiv = document.createElement('div');
                searchDiv.style.marginBottom = '15px';
                searchDiv.innerHTML = `
                    <input type="text" id="searchAssets" placeholder="Cari asset berdasarkan nama, nomor, atau kategori..." 
                           style="width: 300px; padding: 8px; border: 1px solid #ddd; border-radius: 4px;" 
                           onkeyup="searchAssets()">
                `;
                h2.parentNode.insertBefore(searchDiv, h2.nextSibling);
            }
        });
        
        // Show progress bar for large files
        function showProgress() {
            const progressBar = document.createElement('div');
            progressBar.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 4px;
                background: #e0e0e0;
                z-index: 9999;
            `;
            
            const progress = document.createElement('div');
            progress.style.cssText = `
                height: 100%;
                background: #4CAF50;
                width: 0%;
                transition: width 0.3s ease;
            `;
            
            progressBar.appendChild(progress);
            document.body.appendChild(progressBar);
            
            let width = 0;
            const interval = setInterval(() => {
                width += Math.random() * 15;
                if (width >= 90) {
                    clearInterval(interval);
                }
                progress.style.width = Math.min(width, 90) + '%';
            }, 100);
            
            return () => {
                progress.style.width = '100%';
                setTimeout(() => {
                    if (progressBar.parentNode) {
                        progressBar.parentNode.removeChild(progressBar);
                    }
                }, 200);
            };
        }
        
        // Enhanced form submission with progress
        document.querySelector('form').addEventListener('submit', function(e) {
            const finishProgress = showProgress();
            
            // Finish progress when page reloads or after 15 seconds
            setTimeout(finishProgress, 15000);
        });
        
        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl + F to focus search
            if (e.ctrlKey && e.keyCode === 70) {
                const searchBox = document.getElementById('searchAssets');
                if (searchBox) {
                    searchBox.focus();
                    e.preventDefault();
                }
            }
            
            // Ctrl + U to focus file upload
            if (e.ctrlKey && e.keyCode === 85) {
                const fileInput = document.getElementById('excel_file');
                if (fileInput) {
                    fileInput.click();
                    e.preventDefault();
                }
            }
        });
        
        // Export functionality
        function exportAssets() {
            const table = document.querySelector('.results-container table');
            const rows = table.querySelectorAll('tr');
            let csvContent = '';
            
            rows.forEach(row => {
                const cells = row.querySelectorAll('th, td');
                const rowData = [];
                
                cells.forEach(cell => {
                    let cellText = cell.textContent.trim();
                    cellText = cellText.replace(/\n+/g, ' ');
                    cellText = cellText.replace(/"/g, '""');
                    rowData.push(`"${cellText}"`);
                });
                
                csvContent += rowData.join(',') + '\n';
            });
            
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            
            if (link.download !== undefined) {
                const url = URL.createObjectURL(blob);
                link.setAttribute('href', url);
                link.setAttribute('download', `assets_export_${new Date().toISOString().split('T')[0]}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
        
        // Add export button
        document.addEventListener('DOMContentLoaded', function() {
            const searchDiv = document.querySelector('div input[id="searchAssets"]');
            if (searchDiv && searchDiv.parentElement) {
                const exportButton = document.createElement('button');
                exportButton.textContent = '📊 Export CSV';
                exportButton.type = 'button';
                exportButton.className = 'btn-secondary';
                exportButton.style.marginLeft = '10px';
                exportButton.onclick = exportAssets;
                
                searchDiv.parentElement.appendChild(exportButton);
            }
        });
        
        // Tooltip for overdue items
        document.addEventListener('DOMContentLoaded', function() {
            const overdueRows = document.querySelectorAll('.overdue-highlight');
            overdueRows.forEach(row => {
                row.title = 'Asset ini sudah dipinjam lebih dari 7 hari (terlambat)';
                row.style.cursor = 'help';
            });
        });
        
        // Auto-update timestamps
        setInterval(function() {
            const timestampElements = document.querySelectorAll('td:last-child');
            // Update relative time display if needed
        }, 60000); // Update every minute
        
        // Performance optimization for large tables
        document.addEventListener('DOMContentLoaded', function() {
            const table = document.querySelector('.results-container table');
            if (table) {
                const rows = table.querySelectorAll('tbody tr');
                if (rows.length > 100) {
                    // Implement virtual scrolling or pagination for very large datasets
                    console.log(`Large dataset detected: ${rows.length} rows`);
                }
            }
        });
    </script>
</body>
</html>