<?php

namespace App\Http\Controllers;

use App\Models\M_Kepemilikan;
use App\Models\M_Jadwal;
use App\Models\M_SensorUltrasonic;
use App\Models\M_SensorDHT22;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class KepemilikanController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'nama_kandang' => 'required|string|max:255',
            'waktu_pagi' => 'required|date_format:H:i',
            'waktu_siang' => 'required|date_format:H:i',
            'waktu_sore' => 'required|date_format:H:i',
            'suhu' => 'required|numeric',
            'kelembaban' => 'required|numeric',
            'jarak_pakan' => 'required|numeric',
        ]);

        // Dapatkan id user yang sedang login
        $id_user = Auth::id();

        // Buat kandang baru
        $kandang = M_Kepemilikan::create([
            'nama_kandang' => $request->nama_kandang,
            'id_user' => $id_user,
        ]);

        // Tambah jadwal pakan
        M_Jadwal::create([
            'id_user' => $id_user,
            'id_kandang' => $kandang->id_kandang,
            'keterangan' => 'Makan Pagi',
            'waktu' => $request->waktu_pagi,
        ]);
        M_Jadwal::create([
            'id_user' => $id_user,
            'id_kandang' => $kandang->id_kandang,
            'keterangan' => 'Makan Siang',
            'waktu' => $request->waktu_siang,
        ]);
        M_Jadwal::create([
            'id_user' => $id_user,
            'id_kandang' => $kandang->id_kandang,
            'keterangan' => 'Makan Sore',
            'waktu' => $request->waktu_sore,
        ]);

        // Tambah data sensor
        M_SensorDHT22::create([
            'id_user' => $id_user,
            'id_kandang' => $kandang->id_kandang,
            'suhu' => $request->suhu,
            'kelembaban' => $request->kelembaban,
        ]);

        // Tambah data jarak pakan
        M_SensorUltrasonic::create([
            'id_user' => $id_user,
            'id_kandang' => $kandang->id_kandang,
            'data' => $request->jarak_pakan,
        ]);

        // Redirect dengan pesan sukses
        return redirect()->back()->with('success', 'Data berhasil ditambahkan!');
    }
}
