<?php

namespace App\Helpers;


use Auth;
use ReflectionClass;
use File;
use URL;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Carbon\Carbon;

class Helper
{
    public static function success_alert($message)
    {
        $string = '';
        if (is_array($message)) {
            $string = '<ul>';
            foreach ($message as $key => $value) {
                $string .= '<li>' . ucfirst($value) . '</li>';
            }
            $string .= '</li>';
        } else {
            $string = ucfirst($message);
        }
        $alert = '<div class="alert alert-success alert-dismissible text-left fade show" role="alert">
                    <strong>Success !</strong>
                    ' . $string . '
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>';
        return $alert;
    }


       /**summernote */
       public static function input_summernote($value)
       {
           libxml_use_internal_errors(true);
           $dom = new \DomDocument();
           $dom->loadHtml($value, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
           $images = $dom->getElementsByTagName('img');

           if (!empty($images)) {
               foreach ($images as $k => $img) {
                   $data = $img->getAttribute('src');
                   list($type, $data) = explode(';', $data);
                   list(, $data)      = explode(',', $data);
                   $data = base64_decode($data);
                   $image_name = "/summernote/images/" . Carbon::parse(NOW())->format('d-m-Y-His') . $k . '.png';
                   $path = public_path() . $image_name;
                   file_put_contents($path, $data);
                   $img->removeAttribute('src');
                   $img->setAttribute('src', $image_name);
               }
           }

           $value = $dom->saveHTML();
           return $value;
       }

    public static function parsing_alert($message)
    {
        $string = '';
        if (is_array($message)) {
            foreach ($message as $key => $value) {
                $string .= ucfirst($value) . '<br>';
            }
        } else {
            $string = ucfirst($message);
        }
        return $string;
    }

    public static function warning_alert($message)
    {
        $string = '';
        if (is_array($message)) {

            foreach ($message as $key => $value) {
                $string .= '<li>' . ucfirst($value) . '</li>';
            }
            $string .= '</li>';
        } else {
            $string = ucfirst($message);
        }
        $alert = '<div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <strong>Warning !</strong> ' . $string . '
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>';
        return $alert;
    }

    public static function failed_alert($message)
    {
        $string = '';
        if (is_array($message)) {
            $string = '<ul class="m-0">';
            foreach ($message as $key => $value) {
                $string .= '<li>' . ucfirst($value) . '</li>';
            }
            $string .= '</li>';
        } else {
            $string = ucfirst($message);
        }
        $alert = '<div class="alert alert-danger alert-dismissible text-left fade show" role="alert">
                    ' . $string . '
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>';
        return $alert;
    }

    public static function alert_fail($message)
    {
        $string = '';
        if (is_array($message)) {
            foreach ($message as $key => $value) {
                $string .= ucfirst($value) . '<br>';
            }
        } else {
            $string = ucfirst($message);
        }
        return $string;
    }

    public static function short_text($phrase, $max_words, $tanda_baca = null)
    {

        if ($tanda_baca != null) {
            $phrase_array = explode($tanda_baca, $phrase);
            if (count($phrase_array) > $max_words && $max_words > 0) {

                $phrase = implode($tanda_baca, array_slice($phrase_array, 0, $max_words)) . '...';
            }
        } else {
            $phrase_array = explode(' ', $phrase);
            if (count($phrase_array) > $max_words && $max_words > 0) {

                $phrase = implode(' ', array_slice($phrase_array, 0, $max_words)) . '...';
            }
        }

        return $phrase;
    }

    /**
     * cek jika dia super admin jangan dikasih user + permission
     */
    public static function get_permission_by_role()
    {

        $get_roles_user = Auth::user()->roles->pluck('id')->toArray();
        /**1 = super admin */
        if (in_array(1, $get_roles_user)) {
            $permission = Permission::get();
        } else {
            $not_in = [
                5, //permission-create
                6, //permission-delete
                7, //permission-update
                8, //permission-list
                9, //user-create
                10, //user-delete
                11, //user-update
                12, //user-list
            ];
            $permission = Permission::whereNotIn('id', $not_in)
                ->get();
        }
        return $permission;
    }

    public static function get_roles()
    {
        $get_roles_user = Auth::user()->roles->pluck('id')->toArray();
        /**1 = super admin */
        if (in_array(1, $get_roles_user)) {
            $permission = Role::get();
        } else {

            $not_in = [1];
            $permission = Role::whereNotIn('id', $not_in)
                ->get();
        }
        return $permission;
    }

    public static function is_super_admin()
    {
        return Auth::user()->roles->where('id', 1)->first();
    }
    public static function format_date($date, $format)
    {
        $newDate = date($format, strtotime($date));
        return $newDate;
    }

    public static function swal()
    {
        if (session('success')) {
            alert()->html('', session('success'), 'success');
        }

        if (session('error')) {
            alert()->html('', session('error'), 'error');
        }

        if (session('warning')) {
            alert()->html('', session('warning'), 'warning');
        }
    }

    /**Helper Enum */
    public static function enum($value)
    {
        if ($value == 0) {
            return 'Tidak';
        } else if ($value == 1) {
            return 'Ya';
        }
    }
    /**end enum */

    public static function declare_route()
    {
        $loader = require base_path('vendor/autoload.php');
        $methods = [];
        $route = [];
        $classes = [];
        // dd($loader->getClassMap());
        foreach ($loader->getClassMap() as $class => $file) {
            if (preg_match('/[a-z]+Controller$/', $class)) {
                $reflection = new ReflectionClass($class);
                // dd($reflection);
                // exclude inherited methods
                foreach ($reflection->getMethods() as $method)
                    if ($method->class == $reflection->getName()) {

                        $classes[] = $class;
                        if ($method->name == 'route') {
                            $methods[] = $method->name;
                            $route[] = app(get_class(new $class))->route();
                        }
                    }
            }
        }
        return $route;
    }

    public static function get_ip_user(){
        $ipaddress = '';
        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if(getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if(getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if(getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if(getenv('HTTP_FORWARDED'))
        $ipaddress = getenv('HTTP_FORWARDED');
        else if(getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';

        return $ipaddress;
    }

    public static function Hash($value, $type='encode', $return_json=false)
    {
        $secret = getenv('HASH');
        if ($type == 'encode') {
            $return =  base64_encode($value.$secret);
        }elseif ('decode') {
            $return =  str_replace($secret, '', base64_decode($value));
        }else{
            $return = 'Wrong type hashing';
        }
        
        if (!empty($return_json)) {
            echo json_encode($return);
        }else{
            return $return;
        }
    }

    public static function base64_to_image($string, $nama_module, $is_json=false)
    {
        $image = $string;  // your base64 encoded
        $image = str_replace('data:image/png;base64,', '', $image);
        $image = str_replace(' ', '+', $image);
        $imageName = str_random(10).'.'.'png';
        \File::put(storage_path(). '/images/'. $nama_module . '/' . $imageName, base64_decode($image));

        $return = URL::to('storage/images/'. $nama_module . '/' . $imageName);
        
        if (!empty($return_json)) {
            echo json_encode($return);
        }else{
            return $return;
        }
    }

}
