<?php

namespace App\Http\Controllers\Api;

use App\Classes\PermsSeed;
use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\Api\Permission\IndexRequest;
use App\Models\Permission;
use Examyou\RestAPI\ApiResponse;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use ReflectionClass;

class PermissionController extends ApiBaseController
{
    /**
     * The model associated with the controller.
     *
     * @var string
     */
    protected $model = Permission::class;

    /**
     * The request class for index operations.
     *
     * @var string
     */
    protected $indexRequest = IndexRequest::class;

    /**
     * Get module-wise permissions grouped by module and group
     *
     * @return \Examyou\RestAPI\ApiResponse
     */
    public function moduleWisePermissions()
    {
        // Fetch only module-specific permissions (where module_name is NOT NULL)
        // Default/common permissions are hardcoded in the Vue component
        $permissions = Permission::select('id', 'name', 'module_name', 'group')
            ->whereNotNull('module_name')
            ->get();

        $modulePermissions = [];

        // Group permissions by module_name
        foreach ($permissions as $permission) {
            $moduleName = strtolower($permission->module_name);

            // Initialize module array if not exists
            if (!isset($modulePermissions[$moduleName])) {
                // Generate lang_trans from module_name (convert to lowercase)
                $langTrans = 'menu.' . strtolower($moduleName);

                $modulePermissions[$moduleName] = [
                    'module_name' => $moduleName,
                    'lang_trans' => $langTrans,
                    'permissions' => []
                ];
            }

            // Get group name (use 'common' if not set)
            $groupName = strtolower($permission->group ?? 'common');

            // Initialize group array if not exists within this module
            if (!isset($modulePermissions[$moduleName]['permissions'][$groupName])) {
                $modulePermissions[$moduleName]['permissions'][$groupName] = [
                    'group' => $groupName,
                    'lang_trans' => 'menu.' . $groupName,
                    'permissions' => []
                ];
            }

            // Extract permission type suffix (_view, _create, _edit, _delete, _view_all)
            $langTrans = $this->getPermissionLangTrans($permission->name);

            // Add permission to the group
            $modulePermissions[$moduleName]['permissions'][$groupName]['permissions'][] = [
                'xid' => $permission->xid,
                'name' => $permission->name,
                'lang_trans' => $langTrans
            ];
        }

        // Convert grouped permissions to indexed array
        foreach ($modulePermissions as &$module) {
            $module['permissions'] = array_values($module['permissions']);
        }

        // Convert to indexed array
        $modulePermissions = array_values($modulePermissions);

        return ApiResponse::make('Success', [
            'permissions' => $modulePermissions,
        ]);
    }

    /**
     * Get lang_trans for a permission based on its suffix
     *
     * @param string $permissionName
     * @return string
     */
    private function getPermissionLangTrans(string $permissionName): string
    {
        // Check if permission ends with common suffixes
        if (Str::endsWith($permissionName, '_view')) {
            return 'common.view';
        } elseif (Str::endsWith($permissionName, '_create')) {
            return 'common.create';
        } elseif (Str::endsWith($permissionName, '_edit')) {
            return 'common.edit';
        } elseif (Str::endsWith($permissionName, '_delete')) {
            return 'common.delete';
        } elseif (Str::endsWith($permissionName, '_view_all')) {
            return 'common.view_all';
        }

        // If no common suffix found, return the permission name as lang_trans
        return $permissionName;
    }
}
