<?php

namespace App\Livewire\Admin\Configuration;

use App\Models\ContactDataType;
use App\Models\ContactDetails;
use App\Rules\ContactRule;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;

class Create extends Component
{
    public $dataType, $data = [];

    public function render()
    {
        return view('livewire.admin.configuration.create');
    }

    public function mount()
    {
        $this->dataType = ContactDataType::all();
        foreach ($this->dataType as $value) {
            $register = ContactDetails::where('contact_data_type_id',$value->id)->first();
            if (!is_null($register)) $this->data[$value->id] = $register->resource;
        }
        info($this->dataType);
    }

    public function save()
    {
        $errors = false;
        foreach ($this->dataType as $value) {
            if (array_key_exists($value->id, $this->data)) {
                $validator = Validator::make($this->all(), [
                    'data.'.$value->id => [new ContactRule($value->validation)],
                ]);
                
                if ($validator->fails()) {
                    $errors = true;
                    foreach ($validator->errors()->getMessages() as $campo => $mensajes) {
                        info($campo);info($mensajes[0]);
                        $this->addError('data.'.$value->id, $mensajes[0]);
                    }
                }
            }
        }
        if ($errors == true) return;
        DB::beginTransaction();
        try {
            foreach ($this->dataType as $value) {
                $register = ContactDetails::where('contact_data_type_id',$value->id)->first();
                if (array_key_exists($value->id, $this->data)) {
                    if ($this->data[$value->id] != '' && $this->data[$value->id] != ' ') {
                        if (is_null($register)) {
                            ContactDetails::create([
                                'resource' => $this->data[$value->id],
                                'contact_data_type_id' => $value->id,
                                'status_id' => 8,
                            ]);
                        }else{
                            $register->update([
                                'resource' => $this->data[$value->id]
                            ]);
                        }
                    }
                    else{
                        if (!is_null($register)) $register->delete();
                    }
                }else{
                    if (!is_null($register)) $register->delete();
                }
            }
            session()->flash('status', 'Contactos Registrados Correctamente.');
            DB::commit();
            return redirect()->route('configuration.index');
        } catch (\Throwable $th) {
            DB::rollback();
            info($th->getMessage());
        }
    }
}
