<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class SensorController extends Controller
{
    /**
     * Menerima data sensor dari ESP8266/ESP32
     */
    public function update(Request $request)
    {
        $validated = $request->validate([
            'suhu' => 'nullable|numeric',
            'kelembaban' => 'nullable|numeric',
            'cahaya' => 'nullable|numeric',
        ]);
        
        // Simpan data sensor ke database
        DB::table('sensor_logs')->insert([
            'suhu' => $validated['suhu'] ?? null,
            'kelembaban' => $validated['kelembaban'] ?? null,
            'cahaya' => $validated['cahaya'] ?? null,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
        
        // Update status koneksi
        $this->updateConnectionStatus(true);
        
        return response()->json([
            'success' => true,
            'message' => 'Data sensor berhasil disimpan'
        ]);
    }
    
    /**
     * Mendapatkan data sensor terbaru
     */
    public function latest()
    {
        // Ambil data sensor terbaru
        $latestData = DB::table('sensor_logs')
            ->latest('created_at')
            ->first();
            
        // Periksa status koneksi
        $connectionStatus = $this->getConnectionStatus();
        
        return response()->json([
            'suhu' => $latestData->suhu ?? null,
            'kelembaban' => $latestData->kelembaban ?? null,
            'cahaya' => $latestData->cahaya ?? null,
            'timestamp' => $latestData ? Carbon::parse($latestData->created_at)->format('Y-m-d H:i:s') : null,
            'connected' => $connectionStatus
        ]);
    }
    
    /**
     * Mendapatkan riwayat data sensor
     */
    public function history(Request $request)
    {
        $limit = $request->input('limit', 24);
        $page = $request->input('page', 1);
        $offset = ($page - 1) * $limit;
        
        // Ambil data riwayat
        $logs = DB::table('sensor_logs')
            ->orderBy('created_at', 'desc')
            ->skip($offset)
            ->take($limit)
            ->get();
            
        // Hitung total data
        $total = DB::table('sensor_logs')->count();
        
        return response()->json([
            'data' => $logs,
            'pagination' => [
                'total' => $total,
                'per_page' => $limit,
                'current_page' => $page,
                'last_page' => ceil($total / $limit)
            ]
        ]);
    }
    
    /**
     * Update status koneksi ESP8266/ESP32
     */
    private function updateConnectionStatus($connected)
    {
        DB::table('device_status')->updateOrInsert(
            ['device' => 'esp32'],
            [
                'connected' => $connected,
                'last_seen' => Carbon::now(),
                'updated_at' => Carbon::now()
            ]
        );
    }
    
    /**
     * Cek status koneksi ESP8266/ESP32
     */
    private function getConnectionStatus()
    {
        $status = DB::table('device_status')
            ->where('device', 'esp32')
            ->first();
            
        if (!$status) {
            return false;
        }
        
        // Jika terakhir update > 1 menit, anggap terputus
        $lastSeen = Carbon::parse($status->last_seen);
        $now = Carbon::now();
        
        return $status->connected && $lastSeen->diffInMinutes($now) < 1;
    }
} 