<?php

namespace App\Http\Livewire\People;

use App\Http\Controllers\Helpers\HelperController;
use App\Models\Plant;
use App\Models\User;
use Livewire\Component;

class PlantController extends Component
{
    public $listMode = true;
    public $createMode = false;
    public $plants = [];
    public $users = [];
    public $name, $phone, $email, $password, $password_confirmation, $plant_code;

    protected $rules = [
        'password' => ['confirmed'],
        'email' => ['unique:users,email']
    ];

    public function create(){
       $this->listMode = false;
       $this->createMode = true;
    }

    public function list(){

    }

    public function store(){
        $this->validate();
        try {
            HelperController::save_plant_level($this->name, $this->email, $this->phone, $this->password,'Plant Controller', $this->plant_code, 'plant_controller');
            session()->flash('success', 'Plant controller saved successfully');
        } catch (\Throwable $th) {
            session()->flash('danger',$th->getMessage());
        }
    }

    public function fetch_plants()
    {
        return Plant::all();
    }

    public function index(){
        return User::where('role','plant_controller')->with(['plants'])->get();
    }
    public function render()
    {
        $this->plants = $this->fetch_plants();
        $this->users = $this->index();
        return view('livewire.people.plant-controller');
    }
}
