<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Indexoibdd;
use Livewire\WithPagination;

class Bddindexoi extends Component
{
    use WithPagination;
    public $search = '';
    public $item,$ip,$login,$passwd,$item_id;
    public $updateBdd = false;
    public $createItem = false;
    

    public $queryString = ['except'=> ''];
    public function edit($id)
    {
        $data = Indexoibdd::find($id);
        $this->item_id = $data->id;
        $this->item = $data->item;
        $this->ip = $data->ip;
        $this->login = $data->login;
        $this->passwd = $data->pass;
        $this->updateBdd = true;
    }
    public function update()
    {
        Indexoibdd::find($this->item_id)->fill([
            'item' => $this->item,
            'ip' => $this->ip,
            'login' => $this->login,
            'pass' => $this->passwd
        ])->save();
        session()->flash('success', 'Database Updated Successfully');
        $this->updateBdd = false;
    }
    public function delete($id)
    {
        Indexoibdd::find($id)->delete();
    }
    public function cancel()
    {
        $this->updateBdd = false;
    }
    public function cancelAdd()
    {
        $this->updateBdd = false;
    }
    public function cancelItem()
    {
        $this->createItem = false;
    }
    public function create(){
        $this->createItem = true;
        $this->resetFields();
    }
    public function store()
    {
        Indexoibdd::create([
            'item' => $this->item,
            'ip'    =>$this->ip,
            'login' =>$this->login,
            'pass'=>$this->passwd
        ]);
        session()->flash('success', 'Database created Successfully');
        $this->createItem = false;
        $this->resetFields();
    }

    public function render()
    {
        return view('livewire.indexoi.bdd.indexoidatabase',[
            'databases'=>Indexoibdd::where('login', 'LIKE', "%{$this->search}%")->orWhere('item', 'LIKE', "%{$this->search}%")->paginate(5)
            
        ]);
    }
    public function resetFields()
    {
        $this->item = '';
        $this->ip = '';
        $this->login = '';
        $this->passwd = '';
    }
}
