<?php

use App\Entities\Lista;
use App\Entities\SubLista;
use Carbon\Carbon;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Jenssegers\Date\Date;
use Intervention\Image\Facades\Image;

if (!function_exists('messageFlash')) {
    /**
     * @param $message
     * @param $alert
     */
    function messageFlash($message, $alert)
    {
        Session::flash('message', $message);
        Session::flash('alert-class', 'alert-' . $alert);
    }
}

if (!function_exists('notifyFlash')) {
    /**
     * @param $message
     * @param $alert
     * @param null $icon
     * @param null $position
     * @param null $delay
     */
    function notifyFlash($message, $alert, $icon = null, $position = null, $delay = null)
    {
        Session::flash('notify', [
            'message' => $message,
            'alert' => $alert,
            'icon' => $icon,
            'position' => $position,
            'delay' => $delay
        ]);
    }
}

if (!function_exists('verifyActive')) {
    /**
     * @param $deleted_at
     * @return string
     */
    function verifyActive($deleted_at)
    {
//        $deleted = ($deleted_at != null) ? "close color-red" : "check color-green";

        if ($deleted_at != null) {
            $deleted = '<span class="badge badge-danger"><i class="zmdi zmdi-close "></i> Eliminado </span>';
        } else {
            $deleted = '<span class="badge badge-success"> <i class="zmdi zmdi-check "></i> Activo </span>';
        }


        return $deleted;
    }
}

if (!function_exists('username')) {
    /**
     * @param $firstName
     * @param $lastName
     * @return string
     */
    function username($firstName, $lastName)
    {
        $first = explode(' ', strtolower($firstName))[0];
        $last = explode(' ', strtolower($lastName))[0];
        return str_slug($first) . "." . str_slug($last);
    }
}

if (!function_exists('nameUser')) {
    /**
     * @param $firstName
     * @param $lastName
     * @return string
     */
    function nameUser($firstName, $lastName)
    {
        $first = explode(' ', $firstName)[0];
        $last = explode(' ', $lastName)[0];
        return $first . " " . $last;
    }
}

if (!function_exists('dateCumpleanio')) {
    /**
     * @param $date
     * @return string
     */
    function dateCumpleanio($date)
    {
        $carbon = new Date();
        $carbon::setLocale('es');
//        $birthday = $carbon::createFromFormat('Y-m-d', $date)->format('l, j \d\e F Y');
        $birthday = $carbon::createFromFormat('Y-m-d', $date)->format('j');
        return $birthday;
    }
}


if (!function_exists('dateCarbon')) {
    /**
     * @param $date
     * @return string
     */
    function dateCarbon($date)
    {
        $carbon = new Date();
        $carbon::setLocale('es');
//        $birthday = $carbon::createFromFormat('Y-m-d', $date)->format('l, j \d\e F Y');
        $birthday = $carbon::createFromFormat('Y-m-d', $date)->format('j \d\e F');
        return $birthday;
    }
}

if (!function_exists('verificaCumple')) {
    /**
     * @param $date
     * @return string
     */
    function verificaCumple($date)
    {
        $carbon = new Date();
        $dia = $carbon::createFromFormat('Y-m-d', $date)->format('d-m');
        $day = date('d-m');
        if ($day == $dia) {
            return true;
        }
        return false;
    }
}

if (!function_exists('getMonth')) {

    /**
     * @return array
     */
    function getMonth()
    {
//        $dias = array("Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo");
//        $mesPrefijo = array("Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic");
        $mesCompleto = [
            "01" => "Enero",
            "02" => "Febrero",
            "03" => "Marzo",
            "04" => "Abril",
            "05" => "Mayo",
            "06" => "Junio",
            "07" => "Julio",
            "08" => "Agosto",
            "09" => "Septiembre",
            "10" => "Octubre",
            "11" => "Noviembre",
            "12" => "Diciembre"
        ];

        return $mesCompleto;
    }
}

if (!function_exists('dateTicketCarbon')) {
    /**
     * @param $date
     * @return string
     */
    function dateTicketCarbon($date)
    {
        $carbon = new Date();
        $carbon::setLocale('es');
        $birthday = $carbon::createFromFormat('Y-m-d H:i:s', $date)->format('l, j \d\e F \a\ \l\a\s H:i:s');
        return $birthday;
    }
}

if (!function_exists('fechaEstadoTicket')) {
    /**
     * @param $date
     * @return string
     */
    function fechaEstadoTicket($date)
    {
        $carbon = new Date();
        $carbon::setLocale('es');
        $birthday = $carbon::createFromFormat('Y-m-d H:i:s', $date)->format('j \d\e M \|\ H:i:s');
        return $birthday;
    }
}

if (!function_exists('formatDate')) {
    /**
     * @param $date
     * @param null $split
     * @return array|string
     */
    function formatDate($date, $split = null)
    {
        if ($date == null) {
            return $date;
        }
        if ($split == null) {
            $date = explode('-', $date);
        } else {
            $date = explode(' ', $date);
            $date = explode('-', $date[0]);
        }

        $date = $date[2] . '-' . $date[1] . '-' . $date[0];
        return $date;
    }
}

if (!function_exists('messageDate')) {
    /**
     * @param $date
     * @return string
     */
    function messageDate($date)
    {
        $carbon = new Date();
        $carbon::setLocale('es');
        $birthday = $carbon::createFromFormat('Y-m-d H:i:s', $date)->format('l, j \d\e F \d\e\l Y \-\ H:i:s');
        return $birthday;
    }
}

if (!function_exists('monthActual')) {
    /**
     * @param $date
     * @return string
     */
    function monthActual()
    {
        $carbon = new Date();
        $carbon::setLocale('es');
        $birthday = Date::now()->format('F');
        return $birthday;
    }
}

if (!function_exists('formatDate')) {
    /**
     * @param $date
     * @param null $delimiter
     * @return array|null|string
     */
    function formatDate($date, $delimiter = null)
    {
        if ($date != null || $date != "") {
            $delimiter = ($delimiter == null) ? '-' : $delimiter;
            $date = explode($delimiter, $date);
            $date = $date[2] . '-' . strpad($date[1], 2) . '-' . strpad($date[0], 2);
            return $date;
        }
        return null;
    }
}

if (!function_exists('formatDateImport')) {
    /**
     * @param $date
     * @param null $delimiter
     * @return array|null|string
     */
    function formatDateImport($date, $delimiter = null)
    {
        if ($date != null || $date != "") {
            $parameter = ($delimiter == null) ? '-' : $delimiter;
            $dateExplode = explode(" ", $date);
            $dateNow = explode($parameter, $dateExplode[0]);
            $dateNow = $dateNow[0] . '-' . strpad($dateNow[1], 2) . '-' . strpad($dateNow[2], 2);
            return $dateNow;
        }
        return null;
    }
}

if (!function_exists('formatDateHour')) {
    /**
     * @param $date
     * @return string
     */
    function formatDateHour($date)
    {
        if ($date == null) {
            return null;
        } else {
            $date = explode(' ', $date);
            $fecha = formatDate($date[0]);
            $response = $fecha . '<br><i class="fa fa-clock-o"></i> ' . $date[1];
            return $response;
        }

    }
}

if (!function_exists('ticketTerminado')) {
    /**
     * @param $data
     * @return string
     */
    function ticketTerminado($data)
    {
        if ($data == null) {
            $response = '<span style="border-radius:50px;background: red;color: #fff;padding:4px 6px;"><i class="fa fa-times"></i> Abierto</span>';
        } else {
            $response = '<span style="border-radius:50px;background: green;color: #fff;padding:4px 6px;"><i class="fa fa-check"></i> Cerrado</span>';
        }

        return $response;
    }
}

if (!function_exists('estadoTicket')) {

    /**
     * @param $pendiente
     * @param $asignado
     * @param $conincidencia
     * @param $atendido
     * @return array
     */
    function estadoTicket($pendiente, $asignado, $conincidencia, $atendido)
    {
        $response = [];
        if ($atendido != null) {
            $response = [
                'message' => 'Atendido',
                'color' => 'primary'
            ];
        } elseif ($conincidencia != null) {
            $response = [
                'message' => 'Con Incidencia',
                'color' => 'danger'
            ];
        } elseif ($asignado != null) {
            $response = [
                'message' => 'Asignado',
                'color' => 'success'
            ];
        } elseif ($pendiente != null) {
            $response = [
                'message' => 'Pendiente',
                'color' => 'warning'
            ];
        }

        return $response;
    }
}

if (!function_exists('tecnicoTicket')) {
    /**
     * @param $tecnico
     * @return string
     */
    function tecnicoTicket($tecnico)
    {
        if ($tecnico == null) {
            $response = null;
        } else {
            $arrayColor = ['#283593', '#4E342E', '#37474F', '#E91E63'];
            switch ($tecnico->id) {
                case 29:
                    $response = '<span class="tecnicoColor" style="background-color: ' . $arrayColor[0] . ';">' . $tecnico->last_first_name . '</span>';
                    break;
                case 263:
                    $response = '<span class="tecnicoColor" style="background-color: ' . $arrayColor[1] . ';">' . $tecnico->last_first_name . '</span>';;
                    break;
                case 67:
                    $response = '<span class="tecnicoColor" style="background-color: ' . $arrayColor[2] . ';">' . $tecnico->last_first_name . '</span>';
                    break;
                default:
                    $response = '<span class="tecnicoColor" style="background-color: ' . $arrayColor[3] . ';">' . $tecnico->last_first_name . '</span>';
                    break;
            }
        }


        return $response;
    }
}

if (!function_exists('estadoTicketFecha')) {

    /**
     * @param $pendienteFecha
     * @param $asignadoFecha
     * @param $conincidenciaFecha
     * @param $atendidoFecha
     * @return string
     */
    function estadoTicketFecha($pendienteFecha, $asignadoFecha, $conincidenciaFecha, $atendidoFecha)
    {
        $response = '';
        if ($atendidoFecha != null) {
            $response = $atendidoFecha;
        } elseif ($conincidenciaFecha != null) {
            $response = $conincidenciaFecha;
        } elseif ($asignadoFecha != null) {
            $response = $asignadoFecha;
        } elseif ($pendienteFecha != null) {
            $response = $pendienteFecha;
        }

        return $response;
    }
}

if (!function_exists('strpad')) {
    /**
     * @param $string
     * @param int $pad_length
     * @param string $pad_string
     * @param int $pad_type
     * @return string
     */
    function strpad($string, $pad_length = 8, $pad_string = "0", $pad_type = STR_PAD_LEFT)
    {
        $pad = str_pad($string, $pad_length, $pad_string, $pad_type);
        return $pad;
    }
}

if (!function_exists('formatPrice')) {
    /**
     * @param $price
     * @param int $decimal
     * @param string $separatorDecimal
     * @param string $separatorThousands
     * @return string
     */
    function formatPrice($price, $decimal = 2, $separatorDecimal = '.', $separatorThousands = '')
    {
        return number_format($price, $decimal, $separatorDecimal, $separatorThousands);
    }
}

if (!function_exists('mostrarTelefonos')) {

    function mostrarTelefonos($empresa = null, $personal = null)
    {
        $phoneEmpresa = ($empresa != null) ? "<strong>(E)</strong> " . $empresa . "<br>" : "";
        $phonePersonal = ($personal != null) ? "<strong>(P)</strong> " . $personal : "";
        #$phoneEmpresa = ($empresa != null) ? "<strong><i class='fa fa-phone'></i> Emp:</strong> " . $empresa . "<br>" : "";
        #$phonePersonal = ($personal != null) ? "<strong><i class='fa fa-mobile-phone'></i> Pers:</strong> " . $personal : "";

        return $phoneEmpresa . $phonePersonal;
    }
}

if (!function_exists('urlTexto')) {
    /**
     * @param $value
     * @return string
     */
    function urlTexto($value)
    {
        $text = '<strong>' . ucfirst(str_slug($value, ' ')) . '</strong>';

        return $text;
    }
}

if (!function_exists('encodeUriComponent')) {
    /**
     * @param $texto
     * @return string
     */
    function encodeUriComponent($texto)
    {
        return rawurlencode($texto);
    }

}

if (!function_exists('existsContent')) {
    /**
     * @param $value
     * @return string
     */
    function existsContent($value)
    {
        $content = ($value == null || $value == "") ? '-' : $value;

        return $content;
    }

}

if (!function_exists('loadPhotoProfile')) {
    /**
     * @param $foto
     * @param $sexo
     * @param $destination
     * @return string
     */
    function loadPhotoProfile($foto, $sexo, $destination = 'perfil')
    {
        if ($foto != null || $foto != "") {
            $imgSrc = asset('web/' . $destination . '/thumbnail/thumb-' . $foto);
        } else {
            $type = ($sexo == "M") ? "man" : "women";
            $imgSrc = asset('img/profile/' . $type . '.png');
        }

        return $imgSrc;
    }
}


if (!function_exists('existPhonePersona')) {
    /**
     * @param null $phone
     * @param null $phonePersonal
     * @return null
     */
    function existPhonePersona($phone = null, $phonePersonal = null)
    {
        $call = null;
        if ($phone != null || $phone != "") {
            $call = $phone;
        } else {
            if ($phonePersonal != null || $phonePersonal != "") {
                $call = $phonePersonal;
            }
        }

        return $call;
    }

}

if (!function_exists('loadImagePersona')) {
    /**
     * @param $file
     * @param null $pictureOld
     * @param string $destination
     * @return string
     */
    function loadImagePersona($file, $pictureOld = null, $destination = 'perfil')
    {
        if ($pictureOld != null) {
            if (Storage::disk($destination)->exists($pictureOld)) {
                Storage::disk($destination)->delete($pictureOld);
                Storage::disk($destination . 'Thumbnail')->delete('thumb-' . $pictureOld);
            }
        }
        $slug = date('Y') . '-' . date('m') . '-' . date('d') . '-' . uniqid();
        $ext = $file->getClientOriginalExtension();
        $fileName = $slug . '.' . $ext;

        $thumbnail = public_path('web/' . $destination . '/thumbnail/thumb-' . $fileName);

        Image::make($file->getRealPath())->resize(250, 250)->save($thumbnail);

        Storage::disk($destination)->put($fileName, file_get_contents($file->getRealPath()));

        return $fileName;
    }
}

if (!function_exists('listaNombre')) {
    /**
     * @param $slug
     * @return mixed
     */
    function listaNombre($slug)
    {
        try {
            $lista = Lista::where('slug', $slug)->first();
            $subLista = SubLista::where('lista_id', $lista->id)->whereNull('sub_lista_id')->orderBy('nombre', 'ASC')->pluck('nombre', 'id')->all();
        } catch (Exception $e) {
            $subLista = [];
        }

        return $subLista;
    }
}

if (!function_exists('subListaNombre')) {
    /**
     * @param $slugLista
     * @param $slugSubLista
     * @return array
     */
    function subListaNombre($slugLista, $slugSubLista)
    {
        try {
            $lista = Lista::where('slug', $slugLista)->first();
            $subLista = SubLista::where('slug', $slugSubLista)->first();
            $listaSub = SubLista::where([['lista_id', $lista->id], ['sub_lista_id', $subLista->id]])->orderBy('nombre', 'ASC')->pluck('nombre', 'id')->all();

        } catch (Exception $e) {
            $listaSub = [];
        }

        return $listaSub;
    }
}

if (!function_exists('dataSubListaId')) {
    /**
     * @param $slugLista
     * @param $slugSubLista
     * @return mixed
     */
    function dataSubListaId($slugLista, $slugSubLista)
    {
        $lista = Lista::where('slug', $slugLista)->first();
        $subLista = SubLista::where([['lista_id', $lista->id], ['slug', $slugSubLista]])->first();
        $response = $subLista->id;

        return $response;
    }
}

if (!function_exists('getInfoConstanteId')) {
    /**
     * @param $slugLista
     * @param $slugSubLista
     * @return mixed
     */
    function getInfoConstanteId($slugLista, $slugSubLista)
    {
        $response = dataSubListaId(Config::get('constants.' . $slugLista), Config::get('constants.' . $slugSubLista));

        return $response;
    }
}
