<?php

namespace App\Http\Livewire\People;

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

class BusinessController extends Component
{
    public $listMode = true;
    public $createMode = false;
    public $companies = [];
    public $company_code;
    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 get_companies()
    {
        return Company::get();
    }

    public function store()
    {
        $this->validate();
        try {
            HelperController::save_global_level($this->name, $this->email, $this->phone, $this->password, 'Business Controller', 'business_controller', $this->company_code);
            $this->reset();
            session()->flash('success', 'Business controller saved successfully');
        } catch (\Throwable $th) {
            session()->flash('danger', $th->getMessage());
        }
    }

    public function index()
    {
        return User::where('role', 'business_controller')->with('companies')->get();
    }
    public function render()
    {
        $this->users = $this->index();
        $this->companies = $this->get_companies();
        return view('livewire.people.business-controller');
    }
}