<?php

namespace App\Http\Controllers;

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

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
     public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        if (view()->exists($request->path())) {
            return view($request->path());
        }
        return abort(404);
    }


    public function root()
    {
        $currentMonth = Carbon::now()->month;
        $currentYear = Carbon::now()->year;
        $user = Auth::user();
        return view('dashboard-administrator', compact('user'));
    }

    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()]);
                //    DB::table('control_logs')->insert(['action' => 'AUTO', 'triggered_by' => 'web', 'created_at' => Carbon::now(), 'updated_at' => Carbon::now()]);

        }

        return back()->with('status', "Perintah '$action' berhasil dikirim.");
    }
  

}
