<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Exception;

class ViewerDemandeTwo extends Component
{
    use WithPagination;
    public $demande, $listIntervenants = [], $listFiles = [];
    protected $listeners = [
        'viewDemandeTwo' => 'getDemande',
        'resetDemandeTwo' => 'initDemande'
    ];

    public function getDemande($key)
    {
        $this->resetPage();
        $this->demande = get_demande($key);

        if ($this->demande) {
            try {
                $this->listIntervenants = get_intervenants($key);
                $this->listFiles =  get_files($key);
            } catch (Exception $e) {
            }
        }
    }

    public function initDemande()
    {
        $this->demande = null;
        $this->listIntervenants = [];
        $this->listFiles = [];
    }

    public function decision($key, $decision)
    {

        try {
            // $traitment = traitement::where('fk_demande', $key)->get();
            $currentDateTime = Carbon::now();
            $date = $currentDateTime->toDateTimeString();

            if ($decision === "YES") {


                DB::table('traitment')
                    ->where('fk_demande', $key)
                    ->update([
                        'statut' => 'ALLOWED',
                        'date_traitment' => $date,
                        /* 'link' => , */
                        'user_mod' => get_pseudo()
                    ]);
                $msg = "demande acceptée";
            } else {
                DB::table('traitment')
                    ->where('fk_demande', $key)
                    ->update([
                        'statut' => 'REJECTED',
                        'date_traitment' => $date,
                        'user_mod' => get_pseudo()
                    ]);
                $msg = "demande rejectée";
            }

            $this->showToastr('success|' . $msg);
            $this->initDemande();
            // $this->dispatch('resetGestDemande');
        } catch (Exception $e) {
            $this->showToastr('failed|erreur soulevée' . $e);
        }
    }

    public function showToastr($message)
    {
        return $this->dispatch(
            'showToast',
            message: $message
        );
    }

    public function render()
    {
        return view('livewire.viewer-demande-two');
    }
}
