/**
 * EMRS — Camera, GPS & Consumer Search
 * Handles: live camera feed, image capture, GPS watermarking, consumer AJAX search
 */

// ── State ─────────────────────────────────────────────────────
let videoStream    = null;
let useFrontCam    = false;
let gpsData        = { lat: null, lng: null };
let captureReady   = false;

// ── Camera ─────────────────────────────────────────────────────
function startCamera() {
    const video = document.getElementById('cameraFeed');
    if (!video) return;

    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        showAlert('Camera API not supported on this browser. Please use Chrome/Firefox on Android.', 'warning');
        return;
    }

    // Stop any existing stream
    stopCamera();

    const constraints = {
        video: {
            facingMode: useFrontCam ? 'user' : { ideal: 'environment' },
            width:  { ideal: 1280 },
            height: { ideal: 720 }
        },
        audio: false
    };

    navigator.mediaDevices.getUserMedia(constraints)
        .then(stream => {
            videoStream = stream;
            video.srcObject = stream;
            video.play().catch(() => {});
            document.getElementById('videoWrapper')?.classList.remove('d-none');
            document.getElementById('previewWrapper')?.classList.add('d-none');
            captureReady = false;
        })
        .catch(err => {
            console.error('Camera error:', err);
            let msg = 'Camera access denied.';
            if (err.name === 'NotFoundError')     msg = 'No camera found on this device.';
            if (err.name === 'NotAllowedError')   msg = 'Camera permission denied. Please allow camera access.';
            if (err.name === 'NotReadableError')  msg = 'Camera is in use by another app.';
            showAlert(msg, 'danger');
        });
}

function stopCamera() {
    if (videoStream) {
        videoStream.getTracks().forEach(t => t.stop());
        videoStream = null;
    }
}

function switchCamera() {
    useFrontCam = !useFrontCam;
    startCamera();
}

// ── Capture + Watermark ───────────────────────────────────────
function captureImage() {
    const video   = document.getElementById('cameraFeed');
    const canvas  = document.getElementById('captureCanvas');
    const preview = document.getElementById('imagePreview');
    const imgInput= document.getElementById('image_data');
    const mrName  = document.getElementById('mr_name_val')?.value || 'MR';

    if (!video || !canvas) return;
    if (!video.videoWidth) {
        showAlert('Camera not ready. Please wait...', 'warning');
        return;
    }

    const W = video.videoWidth  || 1280;
    const H = video.videoHeight || 720;
    canvas.width  = W;
    canvas.height = H;

    const ctx = canvas.getContext('2d');

    // Draw camera frame
    ctx.drawImage(video, 0, 0, W, H);

    // ── Watermark ──────────────────────────────────────────────
    const now    = new Date();
    const dtStr  = now.toLocaleDateString('en-IN', {day:'2-digit',month:'short',year:'numeric'})
                 + ' ' + now.toLocaleTimeString('en-IN', {hour:'2-digit',minute:'2-digit',second:'2-digit'});
    const gpsStr = gpsData.lat
        ? `GPS: ${gpsData.lat.toFixed(6)}, ${gpsData.lng.toFixed(6)}`
        : 'GPS: Unavailable';

    const addrStr = gpsData.address
        ? gpsData.address.substring(0, 60) + (gpsData.address.length > 60 ? '...' : '')
        : null;

    const lines = [
        `MR: ${mrName}`,
        dtStr,
        gpsStr,
        ...(addrStr ? [addrStr] : [])
    ];

    const fontSize  = Math.max(14, Math.round(H * 0.025));
    const lineH     = fontSize * 1.5;
    const padX      = 10;
    const padY      = 8;
    const boxH      = lines.length * lineH + padY * 2;
    const boxY      = H - boxH;

    // Semi-transparent dark background strip
    ctx.fillStyle = 'rgba(0,0,0,0.62)';
    ctx.fillRect(0, boxY, W, boxH);

    // White text with shadow
    ctx.font        = `bold ${fontSize}px 'Segoe UI', Arial, sans-serif`;
    ctx.fillStyle   = '#ffffff';
    ctx.textBaseline= 'top';
    ctx.shadowColor = 'rgba(0,0,0,0.7)';
    ctx.shadowBlur  = 3;
    ctx.shadowOffsetX = 1;
    ctx.shadowOffsetY = 1;

    lines.forEach((line, i) => {
        ctx.fillText(line, padX, boxY + padY + i * lineH);
    });
    ctx.shadowBlur = 0;

    // Get JPEG base64
    const dataURL = canvas.toDataURL('image/jpeg', 0.88);
    if (imgInput) imgInput.value = dataURL;

    // Show preview
    if (preview) { preview.src = dataURL; }
    document.getElementById('videoWrapper')?.classList.add('d-none');
    document.getElementById('previewWrapper')?.classList.remove('d-none');

    captureReady = true;
    stopCamera();
}

function retakePhoto() {
    const imgInput = document.getElementById('image_data');
    if (imgInput) imgInput.value = '';
    captureReady = false;
    document.getElementById('videoWrapper')?.classList.remove('d-none');
    document.getElementById('previewWrapper')?.classList.add('d-none');
    startCamera();
}

// ── GPS ───────────────────────────────────────────────────────
function getGPS() {
    if (!navigator.geolocation) {
        showAlert('GPS not supported on this device.', 'warning');
        return;
    }

    const btn     = document.getElementById('gpsBtn');
    const display = document.getElementById('gpsDisplay');

    if (btn) { btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Getting GPS…'; btn.disabled = true; }

    navigator.geolocation.getCurrentPosition(
        pos => {
            gpsData.lat = pos.coords.latitude;
            gpsData.lng = pos.coords.longitude;

            const latInp = document.getElementById('gps_lat');
            const lngInp = document.getElementById('gps_lng');
            if (latInp) latInp.value = gpsData.lat.toFixed(8);
            if (lngInp) lngInp.value = gpsData.lng.toFixed(8);

            const accStr = pos.coords.accuracy ? ` (±${Math.round(pos.coords.accuracy)}m)` : '';
            if (display) display.textContent = `Lat: ${gpsData.lat.toFixed(6)}, Lng: ${gpsData.lng.toFixed(6)}${accStr}`;
            if (btn) {
                btn.innerHTML = '<i class="bi bi-geo-alt-fill me-1"></i>GPS Captured ✓';
                btn.className = btn.className.replace('btn-outline-secondary','btn-success');
                btn.disabled = false;
            }

            // Reverse geocode — get readable address
            fetch(`https://nominatim.openstreetmap.org/reverse?lat=${gpsData.lat}&lon=${gpsData.lng}&format=json`)
                .then(r => r.json())
                .then(data => {
                    const addr = data.display_name || `${gpsData.lat.toFixed(6)}, ${gpsData.lng.toFixed(6)}`;
                    if (display) display.innerHTML =
                        `<i class="bi bi-geo-alt-fill text-success me-1"></i><strong>${addr}</strong>`;
                    // Save address for watermark
                    gpsData.address = addr;
                    // Store in hidden field if exists
                    const addrInp = document.getElementById('gps_address');
                    if (addrInp) addrInp.value = addr;
                })
                .catch(() => {
                    if (display) display.textContent = `Lat: ${gpsData.lat.toFixed(6)}, Lng: ${gpsData.lng.toFixed(6)}${accStr}`;
                });
        },
        err => {
            console.warn('GPS error:', err.code, err.message);
            if (display) display.textContent = 'GPS unavailable — continuing without GPS';
            if (btn) {
                btn.innerHTML = '<i class="bi bi-geo-alt me-1"></i>Get GPS';
                btn.disabled = false;
            }
        },
        { enableHighAccuracy: true, timeout: 12000, maximumAge: 0 }
    );
}

// ── Consumer Search (AJAX) ────────────────────────────────────
function searchConsumer(type, checkBill = false) {
    const q         = document.getElementById('searchQuery')?.value.trim();
    const resultDiv = document.getElementById('consumerResult');
    if (!q) { showAlert('Please enter a meter number or connection number.', 'warning'); return; }
    if (q.length < 2) { showAlert('Enter at least 2 characters to search.', 'warning'); return; }

    if (resultDiv) resultDiv.innerHTML =
        '<div class="d-flex align-items-center gap-2 text-muted py-2"><div class="spinner-border spinner-border-sm"></div>Searching…</div>';

    const billParam = checkBill ? '&check_bill=1' : '';
    fetch(`${BASE_URL}/modules/readings/search_consumer.php?q=${encodeURIComponent(q)}&type=${encodeURIComponent(type)}${billParam}`)
        .then(r => {
            if (!r.ok) throw new Error('Network error');
            return r.json();
        })
        .then(data => {
            if (data.success && data.consumer) {
                const c = data.consumer;

                // ── Block duplicate bill for same month ───────────
                if (c.bill_this_month) {
                    document.getElementById('consumer_id').value = '';
                    if (resultDiv) resultDiv.innerHTML = `
                        <div class="alert alert-danger mb-0 mt-2 p-3" style="border-radius:12px;">
                            <div class="d-flex align-items-center gap-2 mb-2">
                                <i class="bi bi-x-circle-fill" style="font-size:1.3rem;"></i>
                                <span class="fw-bold" style="font-size:.95rem;">Bill Already Distributed This Month</span>
                            </div>
                            <div style="font-size:.84rem;line-height:1.7;background:rgba(0,0,0,.06);border-radius:8px;padding:10px 12px;">
                                <div><i class="bi bi-person-badge me-1"></i><strong>Consumer:</strong> ${escHtml(c.consumer_name)}</div>
                                <div><i class="bi bi-hash me-1"></i><strong>Meter No:</strong> ${escHtml(c.meter_number)}</div>
                                <div><i class="bi bi-person-fill me-1"></i><strong>Distributed By:</strong> ${escHtml(c.bill_mr_name)}</div>
                                <div><i class="bi bi-calendar-check me-1"></i><strong>Date:</strong> ${escHtml(c.bill_date)}</div>
                                <div><i class="bi bi-clock me-1"></i><strong>Month:</strong> ${escHtml(c.bill_month_label)}</div>
                            </div>
                            <div class="mt-2 text-danger fw-semibold" style="font-size:.8rem;">
                                <i class="bi bi-info-circle me-1"></i>Next bill next month se submit hoga.
                            </div>
                        </div>`;
                    document.getElementById('formSection')?.classList.add('d-none');
                    return;
                }

                document.getElementById('consumer_id').value = c.id;

                if (resultDiv) resultDiv.innerHTML = `
                    <div class="alert alert-success d-flex align-items-start gap-2 mb-0 mt-2 py-2">
                        <i class="bi bi-person-check-fill flex-shrink-0 mt-1"></i>
                        <div>
                            <div class="fw-semibold">${escHtml(c.consumer_name)}</div>
                            <div class="text-success" style="font-size:.8rem;">
                                Meter: ${escHtml(c.meter_number)} &nbsp;|&nbsp;
                                Conn: ${escHtml(c.connection_number)} &nbsp;|&nbsp;
                                Type: ${escHtml(c.type.toUpperCase())}
                            </div>
                            ${c.address ? `<div class="text-muted" style="font-size:.76rem;">${escHtml(c.address)}</div>` : ''}
                        </div>
                    </div>`;

                // Show form section + init camera + GPS
                const formSection = document.getElementById('formSection');
                if (formSection) {
                    formSection.classList.remove('d-none');
                    formSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    document.dispatchEvent(new CustomEvent('cameraReady'));
                }
                getGPS();
            } else {
                document.getElementById('consumer_id').value = '';
                if (resultDiv) resultDiv.innerHTML =
                    `<div class="alert alert-warning mb-0 mt-2 py-2">${escHtml(data.message || 'Consumer not found. Check the number and try again.')}</div>`;
            }
        })
        .catch(err => {
            if (resultDiv) resultDiv.innerHTML =
                '<div class="alert alert-danger mb-0 mt-2 py-2">Search failed. Please check your connection and try again.</div>';
            console.error('Search error:', err);
        });
}

// Search box — Enter key + auto-check on bills page
document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchQuery');
    if (!searchInput) return;

    // Enter key always triggers search
    searchInput.addEventListener('keydown', e => {
        if (e.key === 'Enter') {
            e.preventDefault();
            const url  = new URL(window.location.href);
            const type = url.searchParams.get('type') || 'kcc';
            searchConsumer(type, !!window.EMRS_CHECK_BILL);
        }
    });

    // On bills page: auto-check as soon as user stops typing (700ms debounce)
    if (window.EMRS_CHECK_BILL) {
        let autoTimer;

        searchInput.addEventListener('input', () => {
            clearTimeout(autoTimer);
            const q = searchInput.value.trim();
            if (q.length < 4) {
                document.getElementById('consumerResult').innerHTML = '';
                document.getElementById('formSection')?.classList.add('d-none');
                document.getElementById('consumer_id').value = '';
                return;
            }
            autoTimer = setTimeout(() => searchConsumer('kcc', true), 700);
        });

        // Also check when user tabs/clicks out of the field
        searchInput.addEventListener('blur', () => {
            const q = searchInput.value.trim();
            if (q.length >= 4) searchConsumer('kcc', true);
        });
    }
});

// ── Alerts ────────────────────────────────────────────────────
function showAlert(msg, type = 'info') {
    const container = document.getElementById('alertContainer');
    if (!container) { console.log(`[Alert/${type}]`, msg); return; }

    const div = document.createElement('div');
    div.className = `alert alert-${type} alert-dismissible fade show d-flex align-items-center gap-2`;
    div.style.fontSize = '.88rem';
    const icons = { success:'check-circle-fill', danger:'exclamation-circle-fill', warning:'exclamation-triangle-fill', info:'info-circle-fill' };
    div.innerHTML = `<i class="bi bi-${icons[type]||'info-circle-fill'} flex-shrink-0"></i>${escHtml(msg)}
        <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>`;
    container.appendChild(div);
    setTimeout(() => { div.classList.remove('show'); setTimeout(() => div.remove(), 300); }, 5000);
}

// ── HTML escape ───────────────────────────────────────────────
function escHtml(str) {
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
