<!-- borrower/return.php -->
<?php
require_once '../config/connection.php';
checkUserType(['borrower']);

$borrower_id = $_SESSION['employee_id'];
$message = '';
$messageType = '';

// Handle return submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['return_asset'])) {
    $borrow_id = $_POST['borrow_id'];
    $return_notes = $_POST['return_notes'] ?? '';
    $kondisi_kembali = $_POST['kondisi_kembali'];
    $foto_kembali = null;
    
    // Handle photo upload
    if (isset($_POST['photo_data']) && !empty($_POST['photo_data'])) {
        // Remove data:image/jpeg;base64, prefix
        $photo_data = $_POST['photo_data'];
        $photo_data = str_replace('data:image/jpeg;base64,', '', $photo_data);
        $photo_data = str_replace(' ', '+', $photo_data);
        $foto_kembali = base64_decode($photo_data);
    }
    
    if (empty($kondisi_kembali)) {
        $message = "Kondisi asset harus dipilih!";
        $messageType = "error";
    } elseif (empty($foto_kembali)) {
        $message = "Foto asset harus diambil!";
        $messageType = "error";
    } else {
        try {
            // Verify this borrow belongs to the current user and is still borrowed
            $stmt = $pdo->prepare("
                SELECT bh.*, a.id as asset_id 
                FROM borrow_history bh 
                JOIN assets a ON bh.asset_id = a.id 
                WHERE bh.id = ? AND bh.borrower_employee_id = ? AND bh.status = 'borrowed'
            ");
            $stmt->execute([$borrow_id, $borrower_id]);
            $borrow = $stmt->fetch();
            
            if ($borrow) {
                // Begin transaction
                $pdo->beginTransaction();
                
                $current_timestamp = date('Y-m-d H:i:s');
                
                // Update borrow history
                $stmt = $pdo->prepare("
                    UPDATE borrow_history 
                    SET status = 'returned', 
                        return_date = CURDATE(),
                        tanggal_kembali = ?,
                        kondisi_kembali = ?,
                        foto_kembali = ?,
                        notes = CASE 
                            WHEN notes IS NULL OR notes = '' THEN ?
                            ELSE CONCAT(notes, '\n--- Return Notes ---\n', ?)
                        END,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([
                    $current_timestamp, 
                    $kondisi_kembali, 
                    $foto_kembali, 
                    $return_notes,
                    $return_notes,
                    $borrow_id
                ]);
                
                // Update asset status and condition
                $new_asset_status = 'available';
                if ($kondisi_kembali === 'rusak') {
                    // Asset rusak masih bisa dipinjam tapi dengan kondisi rusak
                    $new_asset_status = 'available';
                } elseif ($kondisi_kembali === 'hilang') {
                    // Asset hilang tidak bisa dipinjam
                    $new_asset_status = 'maintenance'; // Set to maintenance so it can't be borrowed
                }
                
                $stmt = $pdo->prepare("
                    UPDATE assets 
                    SET status_borrower = ?,
                        kondisi = ?,
                        assigned_employee = NULL,
                        assign_date = NULL,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$new_asset_status, $kondisi_kembali, $borrow['asset_id']]);
                
                // Commit transaction
                $pdo->commit();
                
                $message = "Asset berhasil dikembalikan dengan kondisi: " . ucfirst($kondisi_kembali);
                $messageType = "success";
                
                if ($kondisi_kembali === 'hilang') {
                    $message .= ". Asset akan diset ke status maintenance karena hilang.";
                }
                
            } else {
                $message = "Data peminjaman tidak ditemukan atau sudah dikembalikan.";
                $messageType = "error";
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $message = "Error: " . $e->getMessage();
            $messageType = "error";
        }
    }
}

// Get active borrows for this user
$stmt = $pdo->prepare("
    SELECT bh.*, a.asset_name, a.asset_number, a.barcode_number, a.asset_category,
           DATEDIFF(CURDATE(), bh.borrow_date) as days_borrowed,
           DATE_FORMAT(bh.tanggal_peminjam, '%d/%m/%Y %H:%i') as formatted_borrow_time
    FROM borrow_history bh 
    JOIN assets a ON bh.asset_id = a.id 
    WHERE bh.borrower_employee_id = ? AND bh.status = 'borrowed'
    ORDER BY bh.borrow_date DESC
");
$stmt->execute([$borrower_id]);
$active_borrows = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pengembalian Asset - Tools Room</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <a href="dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
                        </svg>
                    </a>
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">Pengembalian Asset</h1>
                        <p class="text-sm text-medium-gray">Foto dan kembalikan asset yang Anda pinjam</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-sm text-gray-600">Halo, <?php echo $_SESSION['user_name']; ?></span>
                    <a href="../logout.php" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200">
                        Logout
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Message Alert -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $messageType == 'success' ? 'bg-green-100 text-green-700 border border-green-400' : 'bg-red-100 text-red-700 border border-red-400'; ?>">
            <div class="flex items-center">
                <?php if ($messageType == 'success'): ?>
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path>
                </svg>
                <?php else: ?>
                <svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                </svg>
                <?php endif; ?>
                <?php echo htmlspecialchars($message); ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Instructions -->
        <div class="bg-blue-50 rounded-xl p-6 mb-8 border border-blue-200">
            <h3 class="text-lg font-semibold text-blue-800 mb-3">Petunjuk Pengembalian</h3>
            <div class="space-y-2 text-blue-700">
                <p>• Ambil foto asset yang akan dikembalikan menggunakan kamera</p>
                <p>• Pilih kondisi asset saat dikembalikan (baik/rusak/hilang)</p>
                <p>• Tambahkan catatan jika diperlukan</p>
                <p>• Klik "Kembalikan" untuk menyelesaikan proses</p>
            </div>
        </div>

        <!-- Active Borrows -->
        <?php if (empty($active_borrows)): ?>
        <div class="bg-white rounded-xl shadow-lg p-8 text-center">
            <svg class="w-16 h-16 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
            </svg>
            <h3 class="text-lg font-medium text-gray-900 mb-2">Tidak Ada Asset yang Dipinjam</h3>
            <p class="text-gray-500 mb-4">Anda tidak memiliki asset yang sedang dipinjam saat ini.</p>
            <a href="borrow.php" class="inline-flex items-center px-4 py-2 bg-dark-leaf text-white rounded-lg hover:bg-green-600 transition duration-200">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                </svg>
                Ajukan Peminjaman
            </a>
        </div>
        <?php else: ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach ($active_borrows as $borrow): ?>
            <div class="bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-xl transition duration-300">
                <div class="p-6">
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <h3 class="text-lg font-semibold text-gray-800"><?php echo htmlspecialchars($borrow['asset_name']); ?></h3>
                            <p class="text-sm text-medium-gray"><?php echo htmlspecialchars($borrow['asset_number']); ?></p>
                        </div>
                        <span class="px-2 py-1 bg-blue-100 text-blue-800 text-xs font-medium rounded-full">
                            <?php echo htmlspecialchars($borrow['asset_category']); ?>
                        </span>
                    </div>
                    
                    <div class="space-y-2 mb-4">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">Tanggal Pinjam:</span>
                            <span class="font-medium">
                                <?php echo $borrow['formatted_borrow_time'] ?: date('d/m/Y', strtotime($borrow['borrow_date'])); ?>
                            </span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">Lama Pinjam:</span>
                            <span class="font-medium <?php echo $borrow['days_borrowed'] > 7 ? 'text-red-600' : 'text-gray-800'; ?>">
                                <?php echo $borrow['days_borrowed']; ?> hari
                                <?php if ($borrow['days_borrowed'] > 7): ?>
                                <span class="text-xs">(Terlambat)</span>
                                <?php endif; ?>
                            </span>
                        </div>
                        <?php if ($borrow['barcode_number']): ?>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">Barcode:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($borrow['barcode_number']); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($borrow['workcenter']): ?>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">workcenter:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($borrow['workcenter']); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if ($borrow['preference_pro']): ?>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">Preference Pro:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($borrow['preference_pro']); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($borrow['days_borrowed'] > 7): ?>
                    <div class="mb-4 p-3 bg-red-50 rounded-lg border border-red-200">
                        <p class="text-sm text-red-800">
                            <svg class="w-4 h-4 inline mr-1" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"></path>
                            </svg>
                            Asset terlambat dikembalikan!
                        </p>
                    </div>
                    <?php endif; ?>
                    
                    <button onclick="showReturnModal(<?php echo $borrow['id']; ?>, '<?php echo htmlspecialchars($borrow['asset_name'], ENT_QUOTES); ?>')" 
                            class="w-full bg-dark-leaf hover:bg-green-600 text-white font-medium py-2 px-4 rounded-lg transition duration-200">
                        Kembalikan Asset
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- Return Modal -->
    <div id="returnModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full z-50">
        <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-lg bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">Pengembalian Asset</h3>
                <p class="text-sm text-gray-600 mb-4">Asset: <span id="assetName" class="font-medium"></span></p>
                
                <form method="POST" action="" id="returnForm">
                    <input type="hidden" name="borrow_id" id="borrowId">
                    <input type="hidden" name="photo_data" id="photoData">
                    
                    <!-- Camera Section -->
                    <div class="mb-6">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Foto Asset <span class="text-red-500">*</span>
                        </label>
                        
                        <div id="camera-section" class="space-y-4">
                            <div class="flex space-x-2">
                                <button type="button" id="startCameraBtn" onclick="startCamera()" 
                                        class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition duration-200">
                                    <svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z"></path>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    </svg>
                                    Buka Kamera
                                </button>
                                <button type="button" id="captureBtn" onclick="capturePhoto()" 
                                        class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg transition duration-200 hidden">
                                    <svg class="w-5 h-5 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                    </svg>
                                    Ambil Foto
                                </button>
                                <button type="button" id="retakeBtn" onclick="retakePhoto()" 
                                        class="bg-yellow-500 hover:bg-yellow-600 text-white px-4 py-2 rounded-lg transition duration-200 hidden">
                                    Foto Ulang
                                </button>
                            </div>
                            
                            <div class="relative">
                                <video id="camera" class="w-full max-w-md rounded-lg hidden" autoplay playsinline></video>
                                <canvas id="canvas" class="hidden"></canvas>
                                <img id="capturedPhoto" class="w-full max-w-md rounded-lg shadow-md hidden" alt="Captured Photo">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Condition Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Kondisi Asset <span class="text-red-500">*</span>
                        </label>
                        <div class="space-y-2">
                            <label class="flex items-center">
                                <input type="radio" name="kondisi_kembali" value="baik" class="mr-2" required>
                                <span class="text-green-600 font-medium">Baik</span>
                                <span class="text-sm text-gray-500 ml-2">- Asset dalam kondisi normal</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="kondisi_kembali" value="rusak" class="mr-2" required>
                                <span class="text-yellow-600 font-medium">Rusak</span>
                                <span class="text-sm text-gray-500 ml-2">- Asset mengalami kerusakan</span>
                            </label>
                            <label class="flex items-center">
                                <input type="radio" name="kondisi_kembali" value="hilang" class="mr-2" required>
                                <span class="text-red-600 font-medium">Hilang</span>
                                <span class="text-sm text-gray-500 ml-2">- Asset tidak dapat ditemukan</span>
                            </label>
                        </div>
                    </div>
                    
                    <!-- Notes -->
                    <div class="mb-6">
                        <label for="return_notes" class="block text-sm font-medium text-gray-700 mb-2">
                            Catatan Pengembalian (Opsional)
                        </label>
                        <textarea name="return_notes" id="return_notes" rows="3" 
                                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-leaf-green focus:border-transparent"
                                  placeholder="Kondisi asset, catatan kerusakan, dll..."></textarea>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="closeReturnModal()" 
                                class="px-4 py-2 bg-gray-300 text-gray-800 rounded-lg hover:bg-gray-400 transition duration-200">
                            Batal
                        </button>
                        <button type="submit" name="return_asset" id="submitReturnBtn"
                                class="px-4 py-2 bg-dark-leaf text-white rounded-lg hover:bg-green-600 transition duration-200">
                            Kembalikan Asset
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    let stream = null;
    let currentBorrowId = null;

    function showReturnModal(borrowId, assetName) {
        currentBorrowId = borrowId;
        document.getElementById('borrowId').value = borrowId;
        document.getElementById('assetName').textContent = assetName;
        document.getElementById('returnModal').classList.remove('hidden');
        
        // Reset form
        resetCameraState();
        document.getElementById('returnForm').reset();
    }
    
    function closeReturnModal() {
        document.getElementById('returnModal').classList.add('hidden');
        stopCamera();
        resetCameraState();
    }

    function resetCameraState() {
        document.getElementById('camera').classList.add('hidden');
        document.getElementById('capturedPhoto').classList.add('hidden');
        document.getElementById('startCameraBtn').classList.remove('hidden');
        document.getElementById('captureBtn').classList.add('hidden');
        document.getElementById('retakeBtn').classList.add('hidden');
        document.getElementById('photoData').value = '';
    }

    async function startCamera() {
        try {
            // Stop any existing stream first
            stopCamera();
            
            // Request camera with optimal settings
            const constraints = {
                video: {
                    facingMode: { ideal: 'environment' }, // Prefer back camera
                    width: { ideal: 1280, max: 1920 },
                    height: { ideal: 720, max: 1080 }
                },
                audio: false
            };
            
            stream = await navigator.mediaDevices.getUserMedia(constraints);
            
            const camera = document.getElementById('camera');
            camera.srcObject = stream;
            
            // Wait for video to be ready
            camera.onloadedmetadata = () => {
                camera.play().then(() => {
                    console.log('Camera started successfully');
                    camera.classList.remove('hidden');
                    document.getElementById('startCameraBtn').classList.add('hidden');
                    document.getElementById('captureBtn').classList.remove('hidden');
                }).catch(err => {
                    console.error('Error playing video:', err);
                    alert('Error memulai video kamera');
                    stopCamera();
                });
            };
            
        } catch (err) {
            console.error('Camera error:', err);
            let errorMessage = 'Error mengakses kamera: ';
            
            if (err.name === 'NotAllowedError') {
                errorMessage += 'Izin kamera ditolak. Silakan izinkan akses kamera.';
            } else if (err.name === 'NotFoundError') {
                errorMessage += 'Kamera tidak ditemukan.';
            } else if (err.name === 'NotReadableError') {
                errorMessage += 'Kamera sedang digunakan aplikasi lain.';
            } else {
                errorMessage += err.message;
            }
            
            alert(errorMessage);
            resetCameraState();
        }
    }

    function stopCamera() {
        if (stream) {
            stream.getTracks().forEach(track => {
                track.stop();
                console.log('Camera track stopped:', track.kind);
            });
            stream = null;
            
            const camera = document.getElementById('camera');
            camera.srcObject = null;
        }
    }

    function capturePhoto() {
        const camera = document.getElementById('camera');
        const canvas = document.getElementById('canvas');
        const capturedPhoto = document.getElementById('capturedPhoto');
        
        if (!camera.videoWidth || !camera.videoHeight) {
            alert('Kamera belum siap. Silakan tunggu sebentar dan coba lagi.');
            return;
        }
        
        // Set canvas dimensions to match video
        canvas.width = camera.videoWidth;
        canvas.height = camera.videoHeight;
        
        // Draw the video frame to canvas
        const ctx = canvas.getContext('2d');
        ctx.drawImage(camera, 0, 0, canvas.width, canvas.height);
        
        // Convert to base64 with good quality
        const dataURL = canvas.toDataURL('image/jpeg', 0.85);
        document.getElementById('photoData').value = dataURL;
        
        // Show captured photo
        capturedPhoto.src = dataURL;
        capturedPhoto.classList.remove('hidden');
        
        // Hide camera and show retake button
        camera.classList.add('hidden');
        document.getElementById('captureBtn').classList.add('hidden');
        document.getElementById('retakeBtn').classList.remove('hidden');
        
        // Stop camera stream
        stopCamera();
    }

    function retakePhoto() {
        resetCameraState();
        startCamera();
    }

    // Form validation
    document.getElementById('returnForm').addEventListener('submit', function(e) {
        const photoData = document.getElementById('photoData').value;
        const kondisi = document.querySelector('input[name="kondisi_kembali"]:checked');
        
        if (!photoData) {
            e.preventDefault();
            alert('Silakan ambil foto asset terlebih dahulu!');
            return false;
        }
        
        if (!kondisi) {
            e.preventDefault();
            alert('Silakan pilih kondisi asset!');
            return false;
        }
        
        // Confirm submission
        const kondisiText = kondisi.value;
        let confirmMessage = `Apakah Anda yakin akan mengembalikan asset dengan kondisi "${kondisiText}"?`;
        
        if (kondisiText === 'hilang') {
            confirmMessage += '\n\nPerhatian: Asset yang hilang akan diset ke status maintenance dan tidak dapat dipinjam lagi.';
        }
        
        if (!confirm(confirmMessage)) {
            e.preventDefault();
            return false;
        }
    });

    // Close modal when clicking outside
    window.onclick = function(event) {
        const modal = document.getElementById('returnModal');
        if (event.target == modal) {
            closeReturnModal();
        }
    }

    // Cleanup on page unload
    window.addEventListener('beforeunload', function() {
        stopCamera();
    });

    // Check camera permissions on page load
    document.addEventListener('DOMContentLoaded', function() {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            console.log('Camera API is supported');
        } else {
            console.error('Camera API is not supported');
            alert('Browser Anda tidak mendukung akses kamera. Gunakan browser modern seperti Chrome atau Firefox.');
        }
    });
</script>
</body>
</html>