@extends('layouts.app')

@section('title', 'Pengaturan ESP32-CAM')

@section('content')
    <div class="mt-8 max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="bg-white shadow-lg rounded-lg overflow-hidden">
            <div class="p-6">
                <h2 class="text-2xl font-bold text-gray-800 mb-6">Pengaturan ESP32-CAM</h2>
                
                <!-- Status ESP32-CAM -->
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-2">Status ESP32-CAM</h3>
                    <div class="flex flex-col sm:flex-row sm:items-center">
                        <div class="mb-4 sm:mb-0 sm:mr-6">
                            <form id="checkStatusForm" class="flex items-center">
                                <input type="text" id="cameraIp" placeholder="192.168.240.201" value="192.168.240.201"
                                    class="px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                                <button type="submit" class="ml-2 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition duration-300">
                                    Cek Status
                                </button>
                            </form>
                        </div>
                        <div id="cameraStatus" class="flex items-center">
                            <span class="inline-block h-3 w-3 rounded-full mr-2 bg-gray-300"></span>
                            <span class="text-gray-500">Belum diperiksa</span>
                        </div>
                    </div>
                </div>
                
                <!-- Pengambilan Gambar Manual -->
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-2">Pengambilan Gambar Manual</h3>
                    <form id="captureImageForm" class="flex flex-col sm:flex-row sm:items-center">
                        <div class="mb-4 sm:mb-0 sm:mr-6">
                            <input type="text" id="captureIp" placeholder="192.168.240.201" value="192.168.240.201"
                                class="px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <button type="submit" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition duration-300 flex items-center">
                            <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <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>
                            Ambil Foto Sekarang
                        </button>
                    </form>
                    <div id="captureResult" class="mt-4 hidden"></div>
                </div>
                
                <!-- Penjadwalan -->
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-2">Penjadwalan Pengambilan Gambar</h3>
                    <p class="text-sm text-gray-600 mb-4">
                        Sistem mengambil gambar dari ESP32-CAM secara otomatis setiap 15 menit. 
                        Untuk mengubah ini, administrator perlu mengatur cron job di server.
                    </p>
                    <div class="flex items-center">
                        <div class="h-4 w-4 rounded-full bg-green-500 mr-2"></div>
                        <span class="text-sm text-gray-700">Penjadwalan aktif</span>
                    </div>
                </div>
                
                <!-- Riwayat Gambar Terakhir -->
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-4">Riwayat Gambar Terakhir</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama File</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Ukuran</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200" id="recentImagesTable">
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center" colspan="3">
                                        Memuat data...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <!-- Manual Cleanup -->
                <div class="mb-6 p-4 bg-gray-50 rounded-lg">
                    <h3 class="text-lg font-semibold text-gray-700 mb-2">Pembersihan Manual</h3>
                    <p class="text-sm text-gray-600 mb-4">
                        Sistem secara otomatis membersihkan foto yang berusia lebih dari 7 hari tetapi menyimpan minimal 10 foto terakhir.
                    </p>
                    <button id="cleanupButton" class="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition duration-300">
                        Bersihkan Foto Lama
                    </button>
                    <div id="cleanupResult" class="mt-2 hidden"></div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        // Ambil data foto terbaru
        fetch('/api/esp32cam/latest')
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('recentImagesTable');
                if (data.status === 'success') {
                    tableBody.innerHTML = '';
                    // Tambahkan foto terbaru
                    let row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${data.photo.name}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${data.photo.time}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${data.photo.size}</td>
                    `;
                    tableBody.appendChild(row);
                } else {
                    tableBody.innerHTML = `
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center" colspan="3">
                                Belum ada foto tersedia
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('recentImagesTable').innerHTML = `
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-red-500 text-center" colspan="3">
                            Gagal memuat data: ${error.message}
                        </td>
                    </tr>
                `;
            });
        
        // Form cek status ESP32-CAM
        document.getElementById('checkStatusForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const cameraIp = document.getElementById('cameraIp').value;
            const statusElement = document.getElementById('cameraStatus');
            
            if (!cameraIp) {
                alert('Masukkan IP address ESP32-CAM');
                return;
            }
            
            statusElement.innerHTML = `
                <span class="inline-block h-3 w-3 rounded-full mr-2 bg-yellow-500 animate-pulse"></span>
                <span class="text-yellow-600">Memeriksa status...</span>
            `;
            
            fetch(`http://${cameraIp}/status`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    statusElement.innerHTML = `
                        <span class="inline-block h-3 w-3 rounded-full mr-2 bg-green-500"></span>
                        <span class="text-green-600">ESP32-CAM terhubung!</span>
                        <span class="ml-2 text-sm text-gray-500">
                            RSSI: ${data.wifi.rssi} dBm, 
                            Uptime: ${data.uptime} detik
                        </span>
                    `;
                })
                .catch(error => {
                    statusElement.innerHTML = `
                        <span class="inline-block h-3 w-3 rounded-full mr-2 bg-red-500"></span>
                        <span class="text-red-600">Tidak dapat terhubung ke ESP32-CAM</span>
                        <span class="ml-2 text-sm text-gray-500">${error.message}</span>
                    `;
                });
        });
        
        // Form pengambilan gambar
        document.getElementById('captureImageForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const cameraIp = document.getElementById('captureIp').value;
            const resultElement = document.getElementById('captureResult');
            
            if (!cameraIp) {
                alert('Masukkan IP address ESP32-CAM');
                return;
            }
            
            resultElement.innerHTML = `
                <div class="p-3 bg-yellow-50 text-yellow-700 rounded-md">
                    <span class="font-medium">Mengambil gambar...</span> Tunggu sebentar.
                </div>
            `;
            resultElement.classList.remove('hidden');
            
            // Debug request payload
            const payload = {
                camera_ip: cameraIp
            };
            console.log('Sending request with payload:', payload);
            
            fetch('/api/esp32cam/fetch-from-camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify(payload)
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    resultElement.innerHTML = `
                        <div class="p-3 bg-green-50 text-green-700 rounded-md">
                            <span class="font-medium">Berhasil!</span> Gambar telah disimpan dengan nama ${data.filename}.
                            <a href="/dashboard" class="text-blue-500 hover:underline">Lihat di dashboard</a>
                        </div>
                    `;
                } else {
                    resultElement.innerHTML = `
                        <div class="p-3 bg-red-50 text-red-700 rounded-md">
                            <span class="font-medium">Gagal:</span> ${data.message}
                        </div>
                    `;
                }
            })
            .catch(error => {
                resultElement.innerHTML = `
                    <div class="p-3 bg-red-50 text-red-700 rounded-md">
                        <span class="font-medium">Error:</span> ${error.message}
                    </div>
                `;
            });
        });
        
        // Tombol cleanup
        document.getElementById('cleanupButton').addEventListener('click', function() {
            const resultElement = document.getElementById('cleanupResult');
            
            resultElement.innerHTML = `
                <div class="p-3 bg-yellow-50 text-yellow-700 rounded-md">
                    <span class="font-medium">Membersihkan foto lama...</span> Tunggu sebentar.
                </div>
            `;
            resultElement.classList.remove('hidden');
            
            fetch('/api/esp32cam/cleanup')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        resultElement.innerHTML = `
                            <div class="p-3 bg-green-50 text-green-700 rounded-md">
                                <span class="font-medium">Berhasil!</span> ${data.message}
                            </div>
                        `;
                    } else {
                        resultElement.innerHTML = `
                            <div class="p-3 bg-red-50 text-red-700 rounded-md">
                                <span class="font-medium">Gagal:</span> ${data.message}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    resultElement.innerHTML = `
                        <div class="p-3 bg-red-50 text-red-700 rounded-md">
                            <span class="font-medium">Error:</span> ${error.message}
                        </div>
                    `;
                });
        });
    });
    </script>
@endsection 