<?php
// view/scan_image.php
require_once '../config/config.php';
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

 $activePage = 'scan_image';
 $pageTitle = $lang[$current_lang]['visual_search'];
?>
<!DOCTYPE html>
<html lang="<?= $current_lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= APP_NAME ?> - <?= $pageTitle ?></title>
    
    <!-- CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@mdi/font@7.2.96/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="../assets/css/dinar.css" rel="stylesheet">

    <style>
        /* ==========================================
           THEMED STYLING
           ========================================== */
        .scan-tabs {
            display: flex; background: var(--input-bg); border-radius: 12px; padding: 4px; margin-bottom: 20px;
        }
        .scan-tab-btn {
            flex: 1; text-align: center; padding: 10px; border-radius: 8px; border: none; background: transparent;
            color: var(--text-muted); font-weight: 600; transition: var(--transition); cursor: pointer;
        }
        .scan-tab-btn.active {
            background: var(--accent); color: #fff; box-shadow: 0 2px 10px var(--glow);
        }

        .scanner-wrapper {
            border: 2px dashed var(--card-border); border-radius: 20px; padding: 20px; text-align: center;
            transition: all 0.3s ease; background: var(--input-bg); min-height: 400px; display: flex;
            flex-direction: column; align-items: center; justify-content: center; position: relative;
        }

        #barcode-reader { width: 100%; border-radius: 12px; overflow: hidden; }
        #barcode-reader video { border-radius: 12px; border: 1px solid var(--card-border); }
        
        .manual-input-group { background: var(--secondary); border: 1px solid var(--card-border); border-radius: 12px; padding: 15px; margin-top: 15px; }
        .manual-input-group input { background: var(--input-bg); border: 1px solid var(--input-border); color: var(--text); }

        .image-upload-zone { cursor: pointer; width: 100%; height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; }
        .image-upload-zone:hover .scanner-icon { transform: scale(1.1); }
        
        .scanner-icon { font-size: 64px; color: var(--accent); margin-bottom: 20px; transition: var(--transition); }

        .result-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; margin-top: 20px; }
        .result-card { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 16px; overflow: hidden; transition: var(--transition); cursor: pointer; position: relative; }
        .result-card:hover { transform: translateY(-5px); box-shadow: 0 10px 30px rgba(0,0,0,0.3); border-color: var(--accent); }
        .result-img { width: 100%; height: 180px; object-fit: cover; background: var(--secondary); }
        .result-body { padding: 16px; color: var(--text); }
        .result-meta { font-size: 12px; color: var(--text-muted); }
        .similarity-badge { position: absolute; top: 12px; right: 12px; background: var(--secondary); color: var(--accent); padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; border: 1px solid var(--card-border); }

        .loading-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.9); display: none; flex-direction: column; align-items: center; justify-content: center; z-index: 9999; }
        .loading-overlay.show { display: flex; }
        .loading-overlay i, .loading-overlay h5 { color: var(--text); }
        
        .viewer-container { position: relative; width: 100%; height: 400px; background: var(--secondary); overflow: hidden; display: flex; align-items: center; justify-content: center; border-radius: 12px; border: 1px solid var(--card-border); cursor: grab; }
        .viewer-container:active { cursor: grabbing; }
        .viewer-image { max-width: 100%; max-height: 100%; transition: transform 0.15s ease-out; pointer-events: none; }
        .viewer-controls { position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%); background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(5px); padding: 8px 15px; border-radius: 30px; display: flex; gap: 10px; z-index: 10; }
        .viewer-controls button { background: transparent; border: none; color: #fff; font-size: 20px; cursor: pointer; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%; }
        .viewer-controls button:hover { color: var(--accent); }
        .detail-info-table td { color: var(--text); border: none; }
        .detail-info-table td:first-child { color: var(--text-muted); font-weight: 500; width: 120px; }
    </style>
</head>

<body data-theme="<?= $current_theme ?>" 
      class="text-size-<?= $current_text_size ?> btn-size-<?= $current_btn_size ?> icon-size-<?= $current_icon_size ?>">

    <div class="app-wrapper">
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        <?php include 'includes/sidebar.php'; ?>
        
        <main class="main-content">
            <?php include 'includes/header.php'; ?>
            
            <div class="page-content">
                <div class="page-header fade-in">
                    <div>
                        <h1 class="page-title"><i class="mdi mdi-camera me-2"></i><?= $pageTitle ?></h1>
                        <p class="page-subtitle"><?= $lang[$current_lang]['find_parts_by_shape'] ?></p>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-lg-8 mb-4">
                        <div class="card fade-in h-100">
                            <div class="card-body d-flex flex-column">
                                
                                <div class="scan-tabs">
                                    <button class="scan-tab-btn active" id="tabImage" onclick="switchTab('image')">
                                        <i class="mdi mdi-image me-1"></i> <?= $lang[$current_lang]['scan_mode_image'] ?>
                                    </button>
                                    <button class="scan-tab-btn" id="tabBarcode" onclick="switchTab('barcode')">
                                        <i class="mdi mdi-barcode-scan me-1"></i> <?= $lang[$current_lang]['scan_mode_barcode'] ?>
                                    </button>
                                </div>

                                <div class="scanner-wrapper flex-grow-1">
                                    <div id="modeImage" class="image-upload-zone">
                                        <i class="mdi mdi-camera-plus scanner-icon"></i>
                                        <h4 style="color: var(--text)"><?= $lang[$current_lang]['drop_image_here'] ?></h4>
                                        <p class="text-muted"><?= $lang[$current_lang]['or_click_select'] ?></p>
                                        <input type="file" id="fileInput" style="display:none" accept="image/*" capture="environment">
                                        <button class="btn btn-primary mt-3" type="button" onclick="document.getElementById('fileInput').click()">
                                            <i class="mdi mdi-camera"></i> <?= $lang[$current_lang]['open_camera_file'] ?>
                                        </button>
                                    </div>

                                    <div id="modeBarcode" style="display:none; width:100%;">
                                        <div id="barcode-reader"></div>
                                        <div class="manual-input-group">
                                            <label class="form-label text-muted small"><?= $lang[$current_lang]['or_type_barcode'] ?></label>
                                            <div class="input-group">
                                                <input type="text" id="manualBarcode" class="form-control" placeholder="e.g: 89923819...">
                                                <button class="btn btn-primary" onclick="searchManualBarcode()"><i class="mdi mdi-magnify"></i></button>
                                            </div>
                                        </div>
                                        <div class="text-center mt-3">
                                            <button class="btn btn-danger" id="btnStopScanner" onclick="stopBarcodeScanner()" style="display:none">
                                                <i class="mdi mdi-stop"></i> <?= $lang[$current_lang]['stop_scanner'] ?>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="mt-3 text-center d-none" id="previewContainer">
                                    <small class="text-muted">Preview:</small>
                                    <img id="imagePreview" src="#" alt="Preview" class="img-fluid rounded mt-2" style="max-height: 200px; border: 1px solid var(--card-border);">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4 mb-4">
                        <div class="card fade-in h-100">
                            <div class="card-body">
                                <h5 class="card-title mb-3"><i class="mdi mdi-help-circle me-2"></i><?= $lang[$current_lang]['how_to_use'] ?></h5>
                                <div class="d-flex flex-column gap-3">
                                    <div class="d-flex align-items-start gap-3">
                                        <div class="stat-icon" style="width: 40px; height: 40px; font-size: 16px;">1</div>
                                        <div>
                                            <h6 style="color: var(--text)"><?= $lang[$current_lang]['step_1'] ?></h6>
                                            <small class="text-muted"><?= $lang[$current_lang]['step_1_desc'] ?></small>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-start gap-3">
                                        <div class="stat-icon" style="width: 40px; height: 40px; font-size: 16px;">2</div>
                                        <div>
                                            <h6 style="color: var(--text)"><?= $lang[$current_lang]['step_2'] ?></h6>
                                            <small class="text-muted"><?= $lang[$current_lang]['step_2_desc'] ?></small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card fade-in mt-2 d-none" id="resultsCard">
                    <div class="card-header">
                        <h5 class="card-title mb-0"><i class="mdi mdi-magnify me-2"></i><?= $lang[$current_lang]['search_results'] ?></h5>
                    </div>
                    <div class="card-body">
                        <div class="result-grid" id="resultsGrid"></div>
                    </div>
                </div>
            </div>
            
            <!-- MODAL DETAIL -->
            <div class="modal fade" id="modalDetail" tabindex="-1">
                <div class="modal-dialog modal-xl modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Detail Part</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                        </div>
                        <div class="modal-body p-3 p-md-4">
                           <div class="row">
                                <div class="col-12 col-lg-7 mb-4 mb-lg-0">
                                    <div class="viewer-container" id="viewerContainer">
                                        <img src="" id="viewerImage" class="viewer-image" style="display:none;">
                                        <div id="noImagePlaceholder" class="text-center text-muted d-flex flex-column align-items-center justify-content-center h-100">
                                            <i class="mdi mdi-image-off" style="font-size: 48px; opacity: 0.5;"></i> <span>No Image</span>
                                        </div>
                                        <div class="viewer-controls" id="viewerControls" style="display:none;">
                                            <button onclick="zoomIn()"><i class="mdi mdi-magnify-plus"></i></button>
                                            <button onclick="zoomOut()"><i class="mdi mdi-magnify-minus"></i></button>
                                            <button onclick="rotateImage()"><i class="mdi mdi-rotate-right"></i></button>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12 col-lg-5">
                                    <h4 id="detailName" style="color: var(--accent); font-weight: 700; border-bottom: 2px solid var(--card-border); padding-bottom: 10px; margin-bottom: 15px;"></h4>
                                    <table class="table table-sm table-borderless detail-info-table">
                                        <tr><td>Part Number</td><td>: <span id="detailCode"></span></td></tr>
                                        <tr><td>Category</td><td>: <span id="detailCategory"></span></td></tr>
                                        <tr><td>Location</td><td>: <span id="detailLocation"></span></td></tr>
                                        <tr><td>Stock</td><td>: <span id="detailStock"></span> <span id="detailUnit"></span></td></tr>
                                        <tr><td>Price</td><td>: Rp <span id="detailPrice"></span></td></tr>
                                        <tr><td>Status</td><td>: <span id="detailStatus"></span></td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="loading-overlay" id="loadingOverlay">
                <i class="mdi mdi-loading mdi-spin mdi-48px mb-3"></i>
                <h5><?= $lang[$current_lang]['processing_image'] ?></h5>
                <small><?= $lang[$current_lang]['analyzing_visual'] ?></small>
            </div>

            <!-- FOOTER -->
            <!-- Asumsi: footer.php SUDAH memuat jQuery, Bootstrap, Select2, SweetAlert, dan dinar.js -->
            <?php include 'includes/footer.php'; ?>
            
            <!-- SCRIPT KHUSUS HALAMAN INI -->
            <!-- Hanya load library yang BELUM ada di footer.php (Html5Qrcode) -->
            <script src="https://unpkg.com/html5-qrcode" onerror="console.error('Html5Qrcode failed to load')"></script>
            
            <script>
                // ==========================================
                // GLOBAL STATE
                // ==========================================
                let html5QrCode = null;
                let isScanning = false;
                const loadingOverlay = document.getElementById('loadingOverlay');

                // ==========================================
                // TAB SWITCHER
                // ==========================================
                function switchTab(mode) {
                    if (mode === 'image') {
                        $('#tabImage').addClass('active');
                        $('#tabBarcode').removeClass('active');
                        $('#modeImage').show();
                        $('#modeBarcode').hide();
                        stopBarcodeScanner();
                    } else {
                        $('#tabImage').removeClass('active');
                        $('#tabBarcode').addClass('active');
                        $('#modeImage').hide();
                        $('#modeBarcode').show();
                        
                        if (typeof Html5Qrcode !== 'undefined') {
                            if (!isScanning) startBarcodeScanner();
                        } else {
                            Swal.fire('Error', 'Barcode library not loaded. Check internet connection.', 'error');
                        }
                    }
                }

                // ==========================================
                // BARCODE SCANNER LOGIC
                // ==========================================
                function startBarcodeScanner() {
                    if (isScanning) return;
                    
                    $('#btnStopScanner').show();
                    $('#manualBarcode').val('');
                    
                    const readerElement = document.getElementById("barcode-reader");
                    if (!readerElement) return;

                    html5QrCode = new Html5Qrcode("barcode-reader");
                    const config = { fps: 10, qrbox: { width: 250, height: 150 }, aspectRatio: 1.0 };
                    
                    html5QrCode.start(
                        { facingMode: "environment" }, 
                        config,
                        onScanSuccess,
                        onScanFailure
                    ).then(() => { isScanning = true; })
                     .catch((err) => {
                         console.error(err);
                         Swal.fire('Error', 'Could not start camera.', 'error');
                         $('#btnStopScanner').hide();
                     });
                }

                function stopBarcodeScanner() {
                    if (html5QrCode && isScanning) {
                        html5QrCode.stop().then(() => { isScanning = false; $('#btnStopScanner').hide(); }).catch(err => console.log(err));
                    }
                }

                function onScanSuccess(decodedText, decodedResult) {
                    if (navigator.vibrate) navigator.vibrate(200);
                    stopBarcodeScanner();
                    searchByBarcode(decodedText);
                }

                function onScanFailure(error) { }

                function searchManualBarcode() {
                    const code = $('#manualBarcode').val();
                    if(code) searchByBarcode(code);
                }

                function searchByBarcode(code) {
                    loadingOverlay.classList.add('show');
                    $.post('../get/search_by_barcode.php', { barcode: code }, function(res) {
                        loadingOverlay.classList.remove('show');
                        if(res.status === 'success') {
                            displayResults([res.data]);
                            Swal.fire('Ditemukan!', 'Part: ' + res.data.name, 'success');
                        } else {
                            Swal.fire('Not Found', 'Barcode: ' + code, 'info');
                            setTimeout(() => { if(!isScanning) startBarcodeScanner(); }, 1000);
                        }
                    }, 'json').fail(() => { loadingOverlay.classList.remove('show'); Swal.fire('Error', 'Server error', 'error'); });
                }

                // ==========================================
                // IMAGE SEARCH LOGIC
                // ==========================================
                const dropZone = document.getElementById('modeImage');
                const fileInput = document.getElementById('fileInput');
                
                dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.style.borderColor = 'var(--accent)'; });
                dropZone.addEventListener('dragleave', () => { dropZone.style.borderColor = 'var(--card-border)'; });
                dropZone.addEventListener('drop', (e) => {
                    e.preventDefault();
                    dropZone.style.borderColor = 'var(--card-border)';
                    if (e.dataTransfer.files.length) handleImageFile(e.dataTransfer.files[0]);
                });
                
                fileInput.addEventListener('change', (e) => { if(e.target.files.length) handleImageFile(e.target.files[0]); });

                function handleImageFile(file) {
                    if (!file.type.startsWith('image/')) { Swal.fire('Error', 'Please select an image file', 'error'); return; }
                    const reader = new FileReader();
                    reader.onload = (e) => { $('#imagePreview').attr('src', e.target.result).show(); $('#previewContainer').removeClass('d-none'); };
                    reader.readAsDataURL(file);
                    uploadImageSearch(file);
                }

                function uploadImageSearch(file) {
                    loadingOverlay.classList.add('show');
                    let formData = new FormData();
                    formData.append('search_image', file);
                    $.ajax({
                        url: '../get/search_by_image.php',
                        type: 'POST', data: formData, contentType: false, processData: false, dataType: 'json',
                        success: function(res) {
                            loadingOverlay.classList.remove('show');
                            if(res.status === 'success') displayResults(res.data);
                            else Swal.fire('Not Found', 'No matching sparepart found.', 'info');
                        },
                        error: function() { loadingOverlay.classList.remove('show'); Swal.fire('Error', 'Failed to connect to server', 'error'); }
                    });
                }

                // ==========================================
                // DISPLAY RESULTS
                // ==========================================
                function displayResults(data) {
                    $('#resultsCard').removeClass('d-none');
                    $('#resultsGrid').html('');
                    if (!data || data.length === 0) { $('#resultsGrid').html('<div class="col-12 text-center text-muted py-5">No results</div>'); return; }
                    if (!Array.isArray(data)) data = [data];

                    data.forEach(item => {
                        const similarity = item.distance ? Math.max(0, 100 - (item.distance * 6)) : 100;
                        const imgSrc = item.image_path ? `../assets/img/product/${item.image_path}` : 'https://via.placeholder.com/250';
                        const html = `
                        <div class="result-card position-relative" onclick="viewDetail(${item.id})">
                            ${item.distance ? `<span class="similarity-badge">${similarity.toFixed(0)}% Match</span>` : ''}
                            <img src="${imgSrc}" class="result-img" alt="${item.name}">
                            <div class="result-body">
                                <div class="result-title">${item.name}</div>
                                <div class="result-meta">
                                    <span class="d-block"><i class="mdi mdi-barcode"></i> ${item.part_number}</span>
                                    <span class="d-block"><i class="mdi mdi-cube-outline"></i> Stock: ${item.stock} ${item.unit}</span>
                                </div>
                            </div>
                        </div>`;
                        $('#resultsGrid').append(html);
                    });
                    $('#resultsCard')[0].scrollIntoView({ behavior: 'smooth' });
                }

                // ==========================================
                // VIEW DETAIL LOGIC (SAFE WRAPPER)
                // ==========================================
                let currentZoom = 1, currentRotation = 0, currentX = 0, currentY = 0, isDragging = false, startX, startY, imagesList = [];

                // Safety check: Pastikan elemen ada sebelum menambah listener
                const viewer = document.getElementById('viewerContainer');
                if (viewer) {
                    viewer.addEventListener('mousedown', (e) => { 
                        isDragging = true; startX = e.clientX - currentX; startY = e.clientY - currentY; viewer.style.cursor = 'grabbing'; e.preventDefault(); 
                    });
                    document.addEventListener('mousemove', (e) => { if (!isDragging) return; currentX = e.clientX - startX; currentY = e.clientY - startY; applyTransform(); });
                    document.addEventListener('mouseup', () => { isDragging = false; viewer.style.cursor = 'grab'; });
                }

                function applyTransform() {
                    const img = document.getElementById('viewerImage');
                    if(img) img.style.transform = `translate(${currentX}px, ${currentY}px) scale(${currentZoom}) rotate(${currentRotation}deg)`;
                }
                
                function zoomIn() { currentZoom += 0.3; applyTransform(); }
                function zoomOut() { if(currentZoom > 0.5) currentZoom -= 0.3; applyTransform(); }
                function rotateImage() { currentRotation += 90; applyTransform(); }
                function resetView() { currentZoom = 1; currentRotation = 0; currentX = 0; currentY = 0; applyTransform(); }

                function loadMainImage(index) {
                    if(imagesList[index]) {
                        $('#viewerImage').attr('src', '../assets/img/product/' + imagesList[index]).show();
                        $('#noImagePlaceholder').hide(); $('#viewerControls').show();
                        resetView();
                    }
                }

                function viewDetail(id) {
                    $.get('../get/get_sparepart_detail.php', { id: id }, function(res) {
                        if(res.status === 'success') {
                            const data = res.data; imagesList = res.images;
                            resetView();
                            
                            $('#viewerImage').hide(); $('#viewerControls').hide(); $('#noImagePlaceholder').show();
                            $('#detailName').text(data.name);
                            $('#detailCode').text(data.part_number);
                            $('#detailCategory').text(data.category_name || '-');
                            $('#detailLocation').text(data.location_name || '-');
                            $('#detailStock').text(data.stock); $('#detailUnit').text(data.unit);
                            $('#detailPrice').text(parseInt(data.price).toLocaleString('id-ID'));
                            $('#detailStatus').html(data.status === 'active' ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>');
                            
                            if(imagesList.length > 0) loadMainImage(0);
                            else $('#noImagePlaceholder').show();
                            
                            new bootstrap.Modal(document.getElementById('modalDetail')).show();
                        }
                    }, 'json');
                }
            </script>
</body>
</html>