<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Tpmemail;
// use Illuminate\Http\Request;
use Livewire\WithPagination;


class Tpm extends Component
{
    use WithPagination;
    public $search = '';
    public $mail, $password, $compte_id;
    public $updateMail = false;
    public $createEmail = false;
    protected $queryString =[
        'search' => ['except'=>'']
    ];
    public function resetFields()
    {
        $this->mail = '';
        $this->password = '';
    }
    public function render()
    {
        return view('livewire.tpm.mail.tpm',[
            'mails'=> Tpmemail::where('mail', 'LIKE', "%{$this->search}%")->paginate(5)
        ]);
    }
    public function edit($id)
    {
        $mail = Tpmemail::find($id);
        $this->mail = $mail->mail;
        $this->password = $mail->pass;
        $this->compte_id = $mail->id;
        $this->updateMail = true;
        
    }
    public function cancel()
    {
        $this->updateMail = false;
        $this->resetFields();
    }
    public function cancelAdd()
    {
        $this->createEmail = false;
        $this->resetFields();
    }
    public function update()
    {
        Tpmemail::find($this->compte_id)->fill([
            'mail'=>$this->mail,
            'pass'=>$this->password
        ])->save();
        session()->flash('success', 'Email Updated Successfully');
        
        $this->updateMail = false;
        $this->resetFields();

    }
    public function delete($id)
    {
        Tpmemail::find($id)->delete();
    }
    public function create()
    {
        
        $this->createEmail = true;
        $this->resetFields();
    }
    public function store()
    {
        $this->validate([
            'mail' => 'required' ,
            
        ]);
        Tpmemail::create([
            'mail' => $this->mail,
            'pass' => $this->password

        ]);
        session()->flash('success', 'Email created Successfully');
        
        $this->createEmail = false;

    }
    

}
