<?php

namespace App\Http\Controllers;

use App\Models\Lamp;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DeviceController extends Controller
{

    public function control(Request $request)
    {
        $action = $request->input('action');

        if ($action === 'on') {
            // Contoh: nyalakan perangkat
            DB::table('lamp_status')->update(['status' => 'ON', 'updated_at' => Carbon::now()]);
            DB::table('control_logs')->insert(['action' => 'ON', 'triggered_by' => 'web', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
        } elseif ($action === 'off') {
            DB::table('lamp_status')->update(['status' => 'OFF', 'updated_at' => Carbon::now()]);
            DB::table('control_logs')->insert(['action' => 'OFF', 'triggered_by' => 'web', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);
        } elseif ($action === 'auto') {
            DB::table('lamp_status')->update(['status' => 'AUTO', 'updated_at' => Carbon::now()]);
        }

        return back()->with('status', "Perintah '$action' berhasil dikirim.");
    }
    public function getStatus()
    {
        $device = DB::table('lamp_status')->first();

        if ($device) {
            return response($device->status, 200);
        } else {
            return response('off', 404); // default jika device tidak ditemukan
        }
    }

    public function storeSensorData(Request $request)
{
    try {
        DB::table('sensors')->insert([
            'ldr_value' => $request->input('ldr_value'),
            'motion_detected' => $request->input('motion_value'),
            'sound_value' => $request->input('sound_value'),
            'created_at' => now(),
        ]);

        return response()->json(['message' => 'Data diterima']);
    } catch (\Exception $e) {
        Log::error('Gagal menyimpan sensor:', ['error' => $e->getMessage()]);
        return response()->json(['error' => $e->getMessage()], 500);
    }
}
 public function storeLamp(Request $request)
    {
        $validated = $request->validate([
            'mode' => 'required|string',       // AUTO / MANUAL
            'state' => 'required|boolean',     // 1 = ON, 0 = OFF
        ]);



        return response()->json(['message' => 'Lamp status saved']);
    }

}
