<?php

namespace App\Http\Livewire;

use App\Models\City;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Company;
use App\Models\State;
use App\Traits\OrderByTable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Company_ConfigController extends Component
{
    use WithPagination;
    use WithFileUploads;
    use OrderByTable;

    public $name, $nit, $address, $email, $state, $city, $signature_upload, $signature_view, $imageName, $image, $image_view, $phone, $plan_id, $plan_payment_status;
    public $legal_representative, $document_type_representative, $document_representative, $document_expedition_representative;
    public $company_id, $pageTitle, $componentName, $customFileName;
    public $cities, $states, $selectedState;
    public $breadcrumb_show = true;
    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount(Request $request)
    {
        UserAuthPermission('Company_configuration_index');
        $this->company_id = Company::find(Auth::user()->CompanyId())->id;
        $this->pageTitle = 'Configuración';
        $this->componentName = 'Empresa';
        $company = Company::find($this->company_id);
        $this->company_name = $company->name;
        $this->company_plan_name = Company::find($this->company_id )->plan->name;
        $this->company_plan_id = Company::find($this->company_id )->plan->id;
        $this->selectedState = NULL;
        $this->states = State::all();
        $this->cities = collect();

        $this->name = $company->name;
        $this->nit = $company->nit;
        $this->address = $company->address;
        $this->selectedState = $company->state;
        $this->updatedSelectedState($this->selectedState);
        $this->city = $company->city;
        $this->phone = $company->phone;
        $this->email = $company->email;
        $this->image_view = $company->imagen;
        $this->signature_view = $company->signature;
        $this->legal_representative = $company->legal_representative;
        $this->document_type_representative = $company->document_type_representative;
        $this->document_representative = $company->document_representative;
        $this->document_expedition_representative = $company->document_expedition_representative;
        $this->plan_id = $company->plan_id;
        $this->plan_payment_status = $company->plan_payment_status;
        /*
        if ($request->session()->get('item-updated') == 'Datos actualizados') {
            $this->emit('item-updated', 'Información actualizada correctamente');
            $request->session()->forget('item-updated');
        }
        */
    }

    public function render()
    {

        return view('livewire.company.config.component')
        ->extends('layouts.theme.admin.app')
        ->section('content');
    }

    public function updatedSelectedState($state)
    {
        if (!is_null($state)) {
            $this->cities = City::where('state_code', $state)->get();
        }
    }



    public function refreshComponent() {
        return redirect()->route('configuracion-empresa')->with('item-updated', 'Datos actualizados');

    }

    public function OpenUploadSignature()
    {
        $useractions = UserAuthPermissionActions('Company_configuration_add_signature');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $company = Company::find($this->company_id);
        if ($this->document_representative != $company->document_representative) {
            $this->emit('item-error', 'El número de firma ha cambiado, por favor Guarde los cambios');
            return false;
        }
        $this->emit('show-modal-upload-signature','Abrir Modal');
    }

    public function uploadSignature()
    {
        $useractions = UserAuthPermissionActions('Company_configuration_add_signature');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }

        $rules =[
            'signature_upload' => 'required|image|mimes:jpeg,png,jpg|max:1024|dimensions:max_width=350,max_height=180|dimensions:min_width=280,min_height=120',
        ];
        $messages =[
            'signature_upload.required' => 'Debe seleccionar una imagen',
            'signature_upload.image' => 'Debe seleccionar una imagen',
            'signature_upload.mimes' => 'Debe seleccionar una imagen con formato jpeg,png,jpg',
            'signature_upload.max' => 'La imagen debe pesar máximo 1MB',
            'signature_upload.dimensions' => 'La imagen debe tener una resolución máxima de 350px de ancho y 180px de alto',
            'signature_upload.dimensions' => 'La imagen debe tener una resolución mínima de 280px de ancho y 120px de alto',
        ];
        $this->validate($rules, $messages);

        $company = Company::find($this->company_id);
        $document_representative_current = $company->document_representative; //Documento del representante legal almacenado en la base de datos
        $customFileName = 'signature_'.$company->id. '_' .$this->document_representative.'.'. $this->signature_upload->extension();
        $this->signature_upload->storeAs('public/companies/'.$company->id. '/' ,$customFileName);
        $signatureName = $company->signature; //nombre de la imagen actual guardada en la base de datos

        $company->signature = $customFileName; //asignamos el nuevo nombre de la imagen
        $company->save();
        /*
        if ($signatureName != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/companies/' .$company->id. '/'. $signatureName))//verificamos que la imagen exista fisicamente
            {
                if ($document_representative_current == $this->document_representative) {
                    unlink('storage/companies/'. $company->id. '/' . $signatureName); //eliminamos la imagen
                }
            }
        }
        */
        $this->emit('item-updated-upload-signature', 'Firma guardada');
    }

    public function resetUI()
    {

    }


    public function Update()
    {
        $useractions = UserAuthPermissionActions('Company_configuration_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1],$this->company_id);
            return false;
        }
        $rules = [
            'name' => 'required|min:3|max:50|unique:companies,name,'.$this->company_id,
            'nit' => 'required|min:6|max:15|unique:companies,nit,'.$this->company_id,
            'address' => 'required|min:3',
            'city' => 'required|min:3',
            'phone' => "required|unique:companies,phone,{$this->company_id}|max:15",
            'email' => 'required|email|unique:companies,email,'.$this->company_id,
            'legal_representative' => 'required|min:3|max:100',
            'document_type_representative' => 'required',
            'document_representative' => 'required|min:3|max:15',
            'document_expedition_representative' => 'required',

        ];
        $messages = [
            'name.required' => 'Ingrega el Nombre',
            'name.min' => 'El Nombre debe tener como mínimo 3 cáracteres',
            'name.max' => 'El Nombre debe tener menos de 50 caracteres',
            'name.unique' => 'El Nombre ya existe',
            'nit.required' => 'Ingresa el NIT',
            'nit.min' => 'El NIT debe tener como mínimo 6 cáracteres',
            'nit.max' => 'El NIT debe tener como máximo 15 cáracteres',
            'nit.unique' => 'El NIT ya existe',
            'address.required' => 'Ingresa la Dirección',
            'address.min' => 'La dirección debe tener como mínimo 3 cáracteres',
            'city.required' => 'Ingrega la ciudad',
            'city.min' => 'la ciudad debe tener como mínimo 3 cáracteres',
            'phone.required' => 'Ingrega el teléfono',
            'phone.max' => 'El teléfono debe tener como máximo 15 cáracteres',
            'phone.unique' => 'El teléfono ya existe',
            'email.required' => 'Ingrese el email',
            'email.email' => 'El email no es valido',
            'email.unique' => 'El email ya fue registrado por otra empresa',
            'legal_representative.required' => 'Ingresa el representante legal',
            'legal_representative.min' => 'El representante legal debe tener como mínimo 3 cáracteres',
            'legal_representative.max' => 'El representante legal debe tener como máximo 100 cáracteres',
            'document_type_representative.required' => 'Seleccione el tipo de documento',
            'document_representative.required' => 'Ingrese el documento',
            'document_representative.max' => 'El documento debe tener como máximo 15 cáracteres',
            'document_representative.min' => 'El documento debe tener como mínimo 3 cáracteres',
            'document_expedition_representative.required' => 'Ingrese el lugar de expedición del documento',
        ];

        $this->validate($rules, $messages);

        $company = Company::find($this->company_id);

        $company->update([
            'name' => $this->name,
            'nit' => $this->nit,
            'address' => $this->address,
            'state' => $this->selectedState,
            'city' => $this->city,
            'phone' => $this->phone,
            'email' => $this->email,
            'legal_representative' => $this->legal_representative,
            'document_type_representative' => $this->document_type_representative,
            'document_representative' => $this->document_representative,
            'document_expedition_representative' => $this->document_expedition_representative,
        ]);

        /*$user->syncRoles($this->role);*/

        if($this->image)
        {
            $customFileName = $company->id. '_' .uniqid(time(), false). '.' . $this->image->extension();
            $this->image->storeAs('public/companies/' .$company->id. '/',$customFileName);
            $imageName = $company->image; //nombre de la imagen actual guardada en la base de datos

            $company->image = $customFileName; //asignamos el nuevo nombre de la imagen
            $company->save();
            if ($imageName != null)//si la consulta devuelve el nombre de una imagen
            {
                if(file_exists('storage/companies/' .$company->id. '/' .$imageName))//verificamos que la imagen exista fisicamente
                {
                    unlink('storage/companies/' .$company->id. '/'. $imageName); //eliminamos la imagen
                }
            }
        }


        $this->resetUI();
        $this->emit('item-updated', 'Información actualizada correctamente');
        /*
        if ($this->signature_view == NULL) {
            $this->refreshComponent();
        }
        */
    }



}
