<?php

use PhpOffice\PhpSpreadsheet\Shared\Date;
use Carbon\Carbon;

use App\Models\Master\Menu;
use App\Models\Master\AccessMenu;
use App\Models\User;
use App\Models\Master\Group;
use App\Models\Master\Instansi;
use App\Models\Master\Dataset;
use App\Models\Master\Topik;
use App\Models\Master\TabelData;
use App\Models\Log;

if (!function_exists('taskLabel')) {
    function transformDate($value)
    {
        try {
            if (is_numeric($value)) {
                // kalau numeric, berarti serial number Excel
                return Carbon::instance(Date::excelToDateTimeObject($value));
            } elseif ($value) {
                // kalau sudah string (misal: 2025-08-27)
                return Carbon::parse($value);
            }
        } catch (\Exception $e) {
            return null;
        }

        return null;
    }
}

if (!function_exists('taskLabel')) {
    /**
     * @param $val
     *
     * @return string
     */
    function taskLabel($val)
    {
        if ($val == 'store') {
            $task = 'save';
        } elseif ($val == 'save_permission') {
            $task = 'save group access';
        } elseif ($val == 'destroy') {
            $task = 'delete';
        } elseif ($val == 'batch') {
            $task = 'delete';
        } else {
            $task = $val;
        }

        return $task;
    }
}
if (!function_exists('logActivity')) {
    /**
     * @param $request
     * @param $note
     */
    function logActivity($request, $note)
    {
        $repository = app(\App\Models\Log::class);
        $data = [
            'module' => $request->route()->getAction('prefix'),
            'task' => taskLabel($request->route()->getActionMethod()),
            'user_id' => session('uid'),
            'ipaddress' => $request->getClientIp(),
            'useragent' => $request->header('User-Agent'),
            'note' => $note,
            'created_at' => \Carbon\Carbon::now()
        ];

        if (session('superuser') == false)
            $repository->create($data);
    }
}


if (!function_exists('trimId')) {
    /**
     * @param $val
     * @return array
     */
    function trimId($val)
    {
        $string = explode('+', $val);
        return $string;
    }
}


if (!function_exists('dateTime')) {
    /**
     * make secure id
     *
     * @param string|null $val
     *
     * @return string
     */
    function dateTime($date)
    {
        return date('d-m-Y H:i:s',strtotime(@$date));
    }
}

if (!function_exists('encode_id')) {
    /**
     * make secure id
     *
     * @param string|null $val
     *
     * @return string
     */
    function encode_id(?string $val = ''): string
    {
        $params = ['val' => $val];
        return rtrim(base64_encode(serialize($params)), "=");
    }
}

if (!function_exists('decode_id')) {
    /**
     * @param string|null $val
     * ${STATIC}
     *
     * @return      mixed|null
     * @author      alex.gz <amqit.consultant@gmail.com>
     * @created     02/12/2023 4:28
     *
     */
    function decode_id(?string $val = ''): mixed
    {
        $secure = unserialize(base64_decode($val));
        return $secure ? $secure['val'] : null;
    }
}

if (!function_exists('permission')) {
    /**
     * @param        $access
     * @param        $key
     * @param string $method
     * @param bool   $view
     *
     * @return mixed
     */
    function permission($access, $key, string $method = 'menu', bool $view = false): mixed
    {   
        if (@session('group_id') != 1) {
            if ($method == 'module') {
                if (is_array($access)) {
                    $model = AccessMenu::where('module', 'LIKE', "{$key}%")->where('ms_group_id', session('group_id'))->first();
                    $query = count(array_intersect((array)$access, (array)$model->access));
                } else {
                    $query = AccessMenu::where($access, true)->where('module', 'LIKE', $key.'%')->where('ms_group_id', session('group_id'))->count();
                    if ($query > 0) {
                        return true;
                    } else {
                        return abort('401');
                    }
                }
            } else {
                $query = AccessMenu::where($access, true)->where('ms_menu_id', $key)->where('ms_group_id', session('group_id'))->count();
            }

            if ($query > 0) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }

    }
}

if (!function_exists('access')) {
    /**
     * @param $access
     * @param $key
     *
     * @return bool
     */
    function access($access, $key)
    {
        if (session('group_alias') != 'administrator') {
            $query = AccessMenu::where($access, 1)->where('module', $key)->where('ms_group_id', session('group_id'))->count();
            if ($query > 0) {
                return true;
            } else if (session('group_alias') == 'administrator') {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}

if (!function_exists('activeMenuClass')) {
    /**
     * Helper to grab the application version.
     *
     * @return mixed
     */
    function activeMenuClass($route){
        // dd(request()->route()->getName());
        // if(request()->route()->getName() == $route){
        //     return true;
        // }else{
        //     return false;
        // }

        if (\Str::is($route, request()->route()->getName())) {
            return true;
        } else {
            return false;
        }
    }
    
}

if (!function_exists('renderMenu')) {
    
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function renderMenu()
    {
        
        $parent = Menu::where('status',true)->where('menu_type','sidebar')->where('parent_id',0)->orderBy('ordering','ASC')->get();
        $html = '';
        foreach ($parent as $p1) {
            // echo $p1->MsMenuId.'<br>';
            $child2 = Menu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p1->MsMenuId)->orderBy('ordering','ASC')->get();
            $access1 = permission('is_read', $p1->MsMenuId, 'menu', true);

            $ch1 = count($child2) > 0 ? '' : '';
            $link1 = count($child2) > 0 ? '' : 'menu-link';
            $collapse1 = count($child2) > 0 ? 'data-fc-type="collapse"' : '';
            $show = activeMenuClass($p1->module) ? 'style="display:block!important;"' : '';
            $active = activeMenuClass($p1->module) ? 'sidebar-item-active' : '';

            if($access1){
                if (count($child2) > 0) {
                    $html .= '<div class="menu-dropdown">
                                <button class="'.$active.' w-full flex items-center justify-between px-6 py-3 text-slate-500 hover:text-blue-600 hover:bg-slate-50 transition-all dropdown-trigger group">
                                    <div class="flex items-center">
                                        <i data-lucide="'.$p1->menu_icons.'" class="w-5 h-5 shrink-0"></i>
                                        <span class="sidebar-text font-semibold text-sm ml-3">'.$p1->title.'</span>
                                    </div>
                                    <i data-lucide="chevron-down" class="sidebar-dropdown-icon w-4 h-4 transition-transform duration-200"></i>
                                </button>
                                <div class="submenu" '.$show.' >';
                                foreach ($child2 as $p2) {
                                    
                                    $active2 = activeMenuClass($p2->module) ? 'sidebar-item-active' : '';
                                    $html .=  '<a href="'.url($p2->url).'" class="'.$active2.' flex items-center pl-14 pr-6 py-2.5 text-xs font-medium text-slate-500 hover:text-blue-600 transition-colors">'.$p2->title.'</a>';
                                }
                                $html .= '</div>
                            </div>';
                }else{
                    $html .= '<a href="'.url($p1->url).'" class="'.$active.' flex items-center px-6 py-3 transition-all group">
                                <i data-lucide="'.$p1->menu_icons.'" class="w-5 h-5 shrink-0"></i>
                                <span class="sidebar-text font-semibold text-sm ml-3">'.$p1->title.'</span>
                            </a>';
                }
            }

            // if ($access1) {
            //     $active1 = activeMenuClass($p1->module) ? 'sidebar-item-active' : '';

            //     $html .= '<li class=" menu-item ' . $ch1 . '">
            //     <a '.$collapse1.' class=" menu-link '.$active1.'" href="' . url($p1->url) . '">
            //     <span class="menu-icon"><i class="' . $p1->menu_icons . '"></i>
            //     </span> <span class="menu-text ">' . @$p1->title.'</span>';
            //     if (count($child2) > 0) {
            //         $html .= '<span class="menu-arrow"></span>';
            //         $html .= '</a>';
            //         $html .= '<ul class="sub-menu hidden">';
            //         foreach ($child2 as $p2) {
            //             $child3 = Menu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p2->MsMenuId)->get();
            //             $access2 = permission('is_read', $p2->MsMenuId, 'menu', true);
            //             $ch2 = count($child3) > 0 ? '' : '';
            //             $collapse2 = count($child3) > 0 ? 'data-fc-type="collapse"' : '';
            //             $link2 = count($child3) > 0 ? '' : 'menu-link';
            //             if ($access2) {
            //                 $active2 = activeMenuClass($p2->module) ? 'active' : '';
            //                 $html .= '<li class=" menu-item ' . $ch2 . '"><a '.$collapse2.' class="menu-link '.$active2.'" href="' . url($p2->url) . '"><span class="menu-icon"><i class="' . $p2->menu_icons . '"></i></span> <span class="menu-text ">' . @$p2->title.'<span>';
            //                 if (count($child3) > 0) {
            //                     $html .= '<span class="menu-arrow"></span>';
            //                     $html .= '</a>';
            //                     $html .= '<ul class="sub-menu hidden">';
            //                     foreach ($child3 as $p3) {
            //                         $child4 = Menu::where('status',true)->where('menu_type','sidebar')->where('parent_id',$p3->MsMenuId)->get();
            //                         $access3 = permission('is_read', $p3->MsMenuId, 'menu', true);
            //                         $collapse3 = count($child4) > 0 ? 'data-fc-type="collapse"' : '';
            //                         $ch3 = count($child4) > 0 ? '' : '';
            //                         $link3 = count($child4) > 0 ? '' : 'menu-link';
            //                         if ($access3) {
            //                             $active3 = activeMenuClass($p3->module) ? 'active' : '';
            //                             // $active3 = $active ? ' ' . null : null;
            //                             $html .= '<li class=" menu-item ' . $ch3 .'"><a '.$collapse3.' class="menu-link '.$active3.'" href="' . url($p3->url) . '"> <span class="menu-text ">' . @$p3->title.'</span>';
            //                             if (count($child4) > 0) {
            //                                 $html .= '<span class="menu-arrow"></span>';
            //                                 $html .= '</a>';
            //                                 $html .= '<ul class="sub-menu hidden">';
            //                                 foreach ($child4 as $p4) {
            //                                     $html .= '<li class=" ' . null . '"><a class="menu-link" href="' . url($p4->url) . '"> <span class="menu-text ">' . @$p4->title.'<span>';
            //                                 }
            //                                 $html .= '</ul>';
            //                             } else {
            //                                 $html .= '</a>';
            //                             }
            //                             $html .= '</li>';
            //                         }
            //                     }
            //                     $html .= '</ul>';
            //                 } else {
            //                     $html .= '</a>';
            //                 }
            //                 $html .= '</li>';
            //             }
            //         }
            //         $html .= '</ul>';
            //     } else {
            //         $html .= '</a>';
            //     }
            //     $html .= '</li>';
            // }
        }
        return $html;
    }
}

if (!function_exists('include_route_files')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_route_files($folder)
    {
        include_files_in_folder($folder);
    }
}

if (!function_exists('include_files_in_folder')) {
    /**
     * Loops through a folder and requires all PHP files
     * Searches sub-directories as well.
     *
     * @param $folder
     */
    function include_files_in_folder($folder)
    {
        try {
            $rdi = new RecursiveDirectoryIterator($folder);
            $it = new RecursiveIteratorIterator($rdi);

            while ($it->valid()) {
                if (!$it->isDot() && $it->isFile() && $it->isReadable() && $it->current()->getExtension() === 'php') {
                    require $it->key();
                }

                $it->next();
            }
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }
}
if (!function_exists('topikById')) {
    function topikById($id){
        $keyId = decode_id($id);
        $topik = Topik::find($keyId);
        return $topik;
    }
}

if (!function_exists('tabelById')) {
    function tabelById($id){
        $tabel = TabelData::find($id);
        return $tabel;
    }
}

if (!function_exists('tabelInstansi')) {
    function tabelInstansi($idInstansi){

        // $table = Dataset::find($id);
        $instansi = Instansi::find($idInstansi);

        $decode = json_decode($instansi->resource_data);
        $res = "Belum ada data";
        if(@$decode){
            $res = [];
            $d = '<div class="flex flex-col gap-1 justify-start items-start">';
            foreach ($decode as $key => $value) {
                if (($value !== null) && ($value !== "")) {
                    $d .= '<span class="p-2 bg-gray-200 rounded">'.tabelById($value)->name.'</span>';
                }
                
            }
            $d .= '</div>';
            array_push($res, $d);

            $res = implode("", $res);
        }

        return $res;
    }
}

if (!function_exists('topikByDataset')) {
    function topikByDataset($json){

        // $table = Dataset::find($id);

        $decode = json_decode($json);

        $res = "Belum ada data";
        if(count($decode) > 0){
            $res = [];
            $d = '';
            foreach ($decode as $key => $value) {
                if (($value !== null) && ($value !== "")) {
                    $d .= '<span class="p-1 bg-info rounded text-white">'.topikById($value)->name.'</span>&nbsp;';
                }
                
            }
            // $d .= '</ul>';
            array_push($res, $d);

            $res = implode("", $res);
        }

        return $res;
    }
}

if (!function_exists('tags')) {
    function tags($json){

        // $table = Dataset::find($id);

        $decode = json_decode($json);

        $res = "Belum ada data";
        if(count($decode) > 0){
            $res = [];
            $d = '';
            foreach ($decode as $key => $value) {
                if (($value !== null) && ($value !== "")) {
                    $d .= '<span class="p-1 bg-warning rounded text-white mr-3">'.$value.'</span>&nbsp;';
                }
                
            }
            // $d .= '</ul>';
            array_push($res, $d);

            $res = implode("", $res);
        }

        return $res;
    }
}