<?php

namespace App\Actions\App;

use App\Models\Menu;
use App\Traits\ApiResponseTrait;
use Exception;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\File;

class ShowMenu
{
    use ApiResponseTrait;

    public function page($data)
    {
        $menu = json_decode(base64_decode($data['params']), true);


        $getMenu = Menu::find(Crypt::decrypt($menu['id']));

        $html       = '';
        $plugins    = '';
        $roleSlug   = $menu['role'];
        $getMenu->view_path = str_replace('~|role|~', $roleSlug, $getMenu->view_path);

        $this->createFileMenu($getMenu);

        $html       = view('admin/' . $getMenu->view_path . '/'.$getMenu->view_file)->render();
        $plugins    = view('admin/' . $getMenu->view_path . '/plugins')->render();

        $html       = base64_encode($html);
        $plugins    = base64_encode($plugins);

        $item['name'] = $menu['name'];
        $item['url']  = $menu['url'];
        $item['html'] = $html;
        $item['plugins'] = $plugins;
        // throw new Exception('View file does not exist!');
        return $item;
    }


    private function createFileMenu($getMenu)
    {
        if (!empty($getMenu->view_path)) {
            $basePath = resource_path('views/admin/' . $getMenu->view_path);

            // Pastikan foldernya ada
            if (!File::exists($basePath)) {
                File::makeDirectory($basePath, 0755, true);
            }

            // Buat file default.blade.php jika belum ada
            $defaultPath = $basePath . '/default.blade.php';
            if (!File::exists($defaultPath)) {
                File::put($defaultPath, '');
            }

            // Buat file plugins.blade.php jika belum ada
            $pluginsPath = $basePath . '/plugins.blade.php';
            if (!File::exists($pluginsPath)) {
                File::put($pluginsPath, '');
            }
        }
    }
}
