<?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\Plan;
use App\Models\State;
use App\Traits\OrderByTable;

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

    public $name, $nit, $address, $email, $state, $city, $signature, $imageName, $image, $phone, $plan_id, $plan_payment_status;
    public $legal_representative, $document_type_representative, $document_representative, $document_expedition_representative;
    public $search, $selected_id, $pageTitle, $componentName, $customFileName, $count_reg;
    public $cities, $states, $selectedState;
    public $breadcrumb_show = true;

    private $pagination = 10;

    protected $paginationTheme = 'bootstrap';

    public function mount()
    {
        UserAuthPermission('Companies_index');
        $this->pageTitle = 'Listado';
        $this->componentName = 'Empresas';
        $this->selectedState = NULL;
        $this->states = State::all();
        $this->cities = collect();
    }

    public function render()
    {
        if (strlen($this->search) > 0)
            $companies = Company::select('companies.*', 'states.name as state_name', 'cities.name as city_name', 'plans.name as plan_name')
                                ->join('states', 'states.code', '=', 'companies.state')
                                ->join('cities', 'cities.code', '=', 'companies.city')
                                ->join('plans', 'plans.id', '=', 'companies.plan_id')
                                ->where('companies.name', 'like', '%' . $this->search. '%')
                                ->orderBy($this->sortBy, $this->sortDirection)
                                ->paginate($this->pagination);
        else
            $companies = Company::select('companies.*', 'states.name as state_name', 'cities.name as city_name', 'plans.name as plan_name')
                                ->join('states', 'states.code', '=', 'companies.state')
                                ->join('cities', 'cities.code', '=', 'companies.city')
                                ->join('plans', 'plans.id', '=', 'companies.plan_id')
                                ->orderBy($this->sortBy, $this->sortDirection)
                                ->paginate($this->pagination);

        $this->count_reg = $companies->total();

        $plans = Plan::all();


        return view('livewire.companies.component',[
            'companies' => $companies,
            'plans' => $plans,
        ])
        ->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 openAdd()
    {
        $useractions = UserAuthPermissionActions('Companies_create');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1]);
            return false;
        }
        $this->selected_id = 0;
        $this->resetUI();
        $this->emit('show-modal','Abrir Modal');
    }

    public function Edit(Company $company)
    {
        $useractions = UserAuthPermissionActions('Companies_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1],$company);
            return false;
        }
        $this->selected_id = $company->id;
        $this->name = $company->name;
        $this->nit = $company->nit;
        $this->address = $company->address;
        $this->selectedState = $company->state;
        $this->city = $company->city;
        $this->phone = $company->phone;
        $this->email = $company->email;
        $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;
        $this->emit('show-modal', 'Abrir Modal');
    }

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

        $messages = [
            'name.required' => 'Ingresa el Nombre',
            'name.max' => 'El Nombre debe tener menos de 100 caracteres',
            'name.min' => 'El Nombre debe tener mas de 3 caracteres',
            'name.unique' => 'El Nombre ya existe',
            'nit.required' => 'Ingrese el Nit',
            'nit.max' => 'El Nit debe tener menos de 15 caracteres',
            'nit.min' => 'El Nit debe tener mas de 6 caracteres',
            'nit.unique' => 'El Nit ya existe',
            'address.required' => 'Ingresa la Dirección',
            'address.min' => 'La dirección debe tener como mínimo 3 caracteres',
            'city.required' => 'Ingresa la ciudad',
            'city.min' => 'la ciudad debe tener como mínimo 3 caracteres',
            'phone.required' => 'Ingresa el teléfono',
            'phone.max' => 'El teléfono debe tener como máximo 15 caracteres',
            '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' => 'Ingrese el Representante Legal',
            'legal_representative.max' => 'El Representante Legal debe tener menos de 100 caracteres',
            'legal_representative.min' => 'El Representante Legal debe tener mas de 3 caracteres',
            'document_type_representative.required' => 'Seleccione el Tipo de Documento',
            'document_representative.required' => 'Ingrese el Documento',
            'document_representative.max' => 'El Documento debe tener menos de 15 caracteres',
            'document_representative.min' => 'El Documento debe tener mas de 3 caracteres',
            'document_expedition_representative.required' => 'Ingrese Lugar de Expedición del documento',
            'plan_id.required' => 'Selecciona un plan',
            'plan_id.not_in' => 'Selecciona un plan diferente a Seleccionar',
            'plan_payment_status.required' => 'Selecciona un estado del Plan',
            'plan_payment_status.not_in' => 'Selecciona un estado del Plan diferente a Seleccionar',
        ];

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

        $company = Company::create([
            '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,
            'plan_id' => $this->plan_id,
            'plan_payment_status' => $this->plan_payment_status,
        ]);

        if($this->image)
        {
            $customFileName = $company->id. '_' .uniqid(time(), false).'.'.$this->image->extension();
            $this->image->storeAs('public/companies/' .$company->id. '/', $customFileName);
            $company->image = $customFileName;
            $company->save();
        }
        if($this->signature)
        {
            $customFileName = 'signature_'.$company->id. '_' .$this->document_representative.'.'.$this->signature->extension();
            $this->signature->storeAs('public/companies/' .$company->id. '/', $customFileName);
            $company->signature = $customFileName;
            $company->save();
        }
        $this->resetUI();
        $this->emit('item-added', 'Empresa registrada correctamente');

    }

    public function Update()
    {
        $useractions = UserAuthPermissionActions('Companies_update');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1],$this->selected_id);
            return false;
        }
        $rules = [
            'name' => 'required|min:3|max:100|unique:companies,name,'.$this->selected_id,
            'nit' => 'required|min:6|max:15|unique:companies,nit,'.$this->selected_id,
            'address' => 'required|min:3',
            'city' => 'required|min:3',
            'phone' => "required|unique:companies,phone,{$this->selected_id}|max:15",
            'email' => 'required|email|unique:companies,email,'.$this->selected_id,
            'legal_representative' => 'required|min:3|max:100',
            'document_type_representative' => 'required',
            'document_representative' => 'required|min:3|max:15',
            'document_expedition_representative' => 'required',
            'plan_id' => 'required|not_in:Seleccionar',
            'plan_payment_status' => 'required|not_in:Seleccionar',
        ];
        $messages = [
            'name.required' => 'Ingresa el Nombre',
            'name.min' => 'El Nombre debe tener como mínimo 3 caracteres',
            'name.max' => 'El Nombre debe tener menos de 100 caracteres',
            'name.unique' => 'El Nombre ya existe',
            'nit.required' => 'Ingresa el NIT',
            'nit.min' => 'El NIT debe tener como mínimo 6 caracteres',
            'nit.max' => 'El NIT debe tener como máximo 15 caracteres',
            'nit.unique' => 'El NIT ya existe',
            'address.required' => 'Ingresa la Dirección',
            'address.min' => 'La dirección debe tener como mínimo 3 caracteres',
            'city.required' => 'Ingresa la ciudad',
            'city.min' => 'la ciudad debe tener como mínimo 3 caracteres',
            'phone.required' => 'Ingresa el teléfono',
            'phone.max' => 'El teléfono debe tener como máximo 15 caracteres',
            '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 caracteres',
            'legal_representative.max' => 'El representante legal debe tener como máximo 100 caracteres',
            '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 caracteres',
            'document_representative.min' => 'El documento debe tener como mínimo 3 caracteres',
            'document_expedition_representative.required' => 'Ingrese el lugar de expedición del documento',
            'plan_id.required' => 'Selecciona un plan',
            'plan_id.not_in' => 'Selecciona un plan diferente a Seleccionar',
            'plan_payment_status.required' => 'Selecciona un estado del Plan',
            'plan_payment_status.not_in' => 'Selecciona un estado del Plan diferente a Seleccionar',
        ];

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

        $company = Company::find($this->selected_id);
        $document_representative_current = $company->document_representative;
        $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,
            'plan_id' => $this->plan_id,
            'plan_payment_status' => $this->plan_payment_status,
        ]);

        /*$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
                }
            }
        }

        if($this->signature)
        {
            $customFileName = 'signature_'.$company->id. '_' .$this->document_representative.'.'. $this->signature->extension();
            $this->signature->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->resetUI();
        $this->emit('item-updated', 'Empresa Actualizada correctamente');

    }

    protected $listeners = ['deleteRow' => 'Destroy'];

    public function Destroy(Company $company)
    {
        $useractions = UserAuthPermissionActions('Companies_delete');
        if (!empty($useractions)){
            $this->emit($useractions[0],$useractions[1],$this->selected_id);
            return false;
        }
        $usersCount = Company::find($company->id)->users()->count();
        if($usersCount > 0)
        {
            $this->emit('item-error', 'No se puede eliminar la Empresa porque tiene Usuarios asociados');
            return;
        }
        $logo_company = $company->image;
        if ($logo_company != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/companies/' .$company->id. '/'. $logo_company))//verificamos que la imagen exista fisicamente
            {
                unlink('storage/companies/' .$company->id. '/' . $logo_company); //eliminamos la imagen
            }
        }
        $signature_company = $company->signature;
        if ($signature_company != null)//si la consulta devuelve el nombre de una imagen
        {
            if(file_exists('storage/companies/'. $company->id. '/'. $signature_company))//verificamos que la imagen exista fisicamente
            {
                unlink('storage/companies/' . $company->id. '/' . $signature_company); //eliminamos la imagen
            }
        }
        $company->delete();
        $this->emit('item-deleted', 'Se eliminó la Empresa con éxito');
    }

    public function resetUI()
    {
        $this->name = '';
        $this->nit = '';
        $this->address = '';
        $this->selectedState = '';
        $this->state = '';
        $this->city = '';
        $this->phone = '';
        $this->email = '';
        $this->image = '';
        $this->plan_id = '';
        $this->plan_payment_status = '';
        $this->signature = '';
        $this->legal_representative = '';
        $this->document_type_representative = '';
        $this->document_representative = '';
        $this->document_expedition_representative = '';
        $this->image = '';
        $this->selected_id = 0;
        $this->resetValidation();
        $this->resetPage();
    }

}
