<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Theme;
use Illuminate\Support\Facades\Gate;

class RoleAssignmentController extends Controller
{
    /**
     * Display all roles with their statistics.
     */
    public function indexRoles()
    {
        // Authorization check - only Super Manager can access
        abort_unless(auth()->user()->hasRole('Super Manager'), 403, 'Only Super Managers can access role management.');

        $roles = Role::with(['permissions', 'users'])->orderBy('name')->get();
        $themes = \App\Models\Theme::orderBy('name')->get();

        return view('roles.index', compact('roles', 'themes'));
    }

    /**
     * Module grouping map for permissions.
     * Maps a keyword found in the permission name to a human-readable module label.
     * Checked in order — first match wins.
     */
    private static array $moduleMap = [
        // Administration
        'users'                  => 'Administration › Users',
        'roles'                  => 'Administration › Roles',
        'permissions'            => 'Administration › Permissions',
        'dashboards'             => 'Administration › Dashboards',
        'otp settings'           => 'Administration › OTP Settings',
        'sessions'               => 'Administration › Sessions',
        'login attempts'         => 'Administration › Login Attempts',
        'user profiles'          => 'Administration › User Profiles',
        'system settings'        => 'Administration › System Settings',
        'themes'                 => 'Administration › Themes',
        'admin panel'            => 'Administration › Admin Panel',
        'statistics'             => 'Administration › Statistics',
        'audit logs'             => 'Administration › Audit Logs',
        'two-factor'             => 'Administration › Two-Factor',
        'social accounts'        => 'Administration › Social Accounts',
        'verification email'     => 'Administration › Email Verification',
        'user password'          => 'Administration › Password Reset',

        // Membership & Loans
        'members'                => 'Membership & Loans › Members',
        'membership categories'  => 'Membership & Loans › Categories',
        'membership certificate' => 'Membership & Loans › Certificates',
        'renewal'                => 'Membership & Loans › Renewals',
        'subscription fees'      => 'Membership & Loans › Subscription Fees',
        'contribution fees'      => 'Membership & Loans › Contribution Fees',
        'contributions'          => 'Membership & Loans › Contributions',
        'loan products'          => 'Membership & Loans › Loan Products',
        'loan applications'      => 'Membership & Loans › Loan Applications',
        'loans'                  => 'Membership & Loans › Loans',
        'transactions'           => 'Membership & Loans › Transactions',

        // Health Directory
        'institutions'           => 'Health Directory › Institutions',
        'machines'               => 'Health Directory › Machines',
        'marketor dashboard'     => 'Health Directory › Marketor Dashboard',
        'admin dashboard'        => 'Health Directory › Admin Dashboard',

        // Payments
        'payments'               => 'Payments › Payments',
        'payment configuration'  => 'Payments › Configuration',
        'payment logs'           => 'Payments › Logs',
        'payment connection'     => 'Payments › Connection',

        // Training
        'training packages'      => 'Training › Packages',
        'training sessions'      => 'Training › Sessions',
        'trainers'               => 'Training › Trainers',
        'training registrations' => 'Training › Registrations',
        'training attendance'    => 'Training › Attendance',
        'training certificates'  => 'Training › Certificates',
        'training payments'      => 'Training › Payments',
        'training reports'       => 'Training › Reports',
        'training settings'      => 'Training › Settings',
        'training categories'    => 'Training › Categories',
        'training'               => 'Training › General',

        // Mentorship
        'mentorship categories'  => 'Mentorship › Categories',
        'mentorship programmes'  => 'Mentorship › Programmes',
        'mentorship applications'=> 'Mentorship › Applications',
        'mentorship assignments' => 'Mentorship › Assignments',
        'mentorship sessions'    => 'Mentorship › Sessions',
        'mentorship certificates'=> 'Mentorship › Certificates',
        'mentorship payments'    => 'Mentorship › Payments',
        'mentorship statistics'  => 'Mentorship › Statistics',
        'mentorship'             => 'Mentorship › General',

        // Research & Advocacy
        'publications'           => 'Research & Advocacy › Publications',
        'campaigns'              => 'Research & Advocacy › Campaigns',
        'stories'                => 'Research & Advocacy › Stories',
        'polls'                  => 'Research & Advocacy › Polls',
        'advocacy analytics'     => 'Research & Advocacy › Analytics',
        'advocacy reports'       => 'Research & Advocacy › Reports',

        // Partnership
        'partners'               => 'Partnership › Partners',
        'partnerships'           => 'Partnership › Partnerships',
        'forum'                  => 'Partnership › Forum',
        'partner contacts'       => 'Partnership › Contacts',

        // Knowledge Sharing
        'discussion topics'      => 'Knowledge Sharing › Discussion Topics',
        'discussion replies'     => 'Knowledge Sharing › Discussion Replies',
        'discussions'            => 'Knowledge Sharing › Discussions',
        'knowledge base categories' => 'Knowledge Sharing › KB Categories',
        'knowledge base questions'  => 'Knowledge Sharing › KB Questions',
        'knowledge base answers'    => 'Knowledge Sharing › KB Answers',
        'knowledge base'         => 'Knowledge Sharing › General',

        // Communication
        'tickets'                => 'Communication › Tickets',
        'ticket categories'      => 'Communication › Ticket Categories',
        'emails'                 => 'Communication › Emails',
        'email templates'        => 'Communication › Email Templates',
        'email statistics'       => 'Communication › Email Statistics',
        'sms templates'          => 'Communication › SMS Templates',
        'sms statistics'         => 'Communication › SMS Statistics',
        'sms logs'               => 'Communication › SMS Logs',
        'sms connection'         => 'Communication › SMS Connection',
        'sms configuration'      => 'Communication › SMS Configuration',
        'sms'                    => 'Communication › SMS',
        'chats'                  => 'Communication › Chat',
        'chat categories'        => 'Communication › Chat Categories',
        'chat agents'            => 'Communication › Chat Agents',
        'chat statistics'        => 'Communication › Chat Statistics',

        // Email Configuration
        'email configuration'    => 'System Config › Email Config',
        'email logs'             => 'System Config › Email Logs',

        // Google Meet
        'google meet'            => 'System Config › Google Meet',

        // Organization & Governance
        'organizations'          => 'Organization & Governance › Organizations',
        'leadership positions'   => 'Organization & Governance › Leadership Positions',
        'leadership history'     => 'Organization & Governance › Leadership History',
        'leadership'             => 'Organization & Governance › Leadership',
        'election cycles'        => 'Organization & Governance › Election Cycles',
        'voting procedures'      => 'Organization & Governance › Voting Procedures',
        'staff history'          => 'Organization & Governance › Staff History',
        'organogram'             => 'Organization & Governance › Organogram',

        // Content Management
        'pages'                  => 'Content Management › Pages',
        'topbar notifications'   => 'Content Management › Topbar Notifications',
        'email subscribers'      => 'Content Management › Email Subscribers',
        'what we do images'      => 'Content Management › What We Do Images',
        'sliders'                => 'Content Management › Sliders',
        'hero cards'             => 'Content Management › Hero Cards',

        // Self-Paced Learning
        'self-paced'             => 'Self-Paced Learning',

        // Health Institution Registration (duplicate key removed — handled above)

        // Fallback
        'resources'              => 'General › Resources',
        'reports'                => 'General › Reports',
        'settings'               => 'General › Settings',
    ];

    /**
     * Resolve the module group for a permission name.
     */
    private function resolveModule(string $permissionName): string
    {
        $lower = strtolower($permissionName);
        foreach (self::$moduleMap as $keyword => $module) {
            if (str_contains($lower, $keyword)) {
                return $module;
            }
        }
        return 'General › Other';
    }

    /**
     * Display the role assignment interface.
     * Only accessible to Super Manager.
     */
    public function index()
    {
        // Authorization check - only Super Manager can access
        abort_unless(auth()->user()->hasRole('Super Manager'), 403, 'Only Super Managers can access role assignment.');

        $roles = Role::with('permissions')->orderBy('name')->get();

        // Build a map: permission_id => [role_id, ...]
        $permissionRoleMap = [];
        foreach ($roles as $role) {
            foreach ($role->permissions as $perm) {
                $permissionRoleMap[$perm->id][] = $role->id;
            }
        }

        // Group permissions by resolved module
        $permissions = Permission::orderBy('name')->get()->groupBy(function ($permission) {
            return $this->resolveModule($permission->name);
        })->sortKeys();

        // Load themes for the theme selector
        $themes = \App\Models\Theme::orderBy('name')->get();

        return view('roles.assign', compact('roles', 'permissions', 'permissionRoleMap', 'themes'));
    }

    /**
     * Update role permissions and theme.
     */
    public function update(Request $request, Role $role)
    {
        // Authorization check - only Super Manager can update
        abort_unless(auth()->user()->hasRole('Super Manager'), 403, 'Only Super Managers can assign permissions.');

        $validThemeSlugs = \App\Models\Theme::pluck('slug')->toArray();

        $validated = $request->validate([
            'permissions' => 'nullable|array',
            'permissions.*' => 'exists:permissions,id',
            'theme' => ['nullable', 'string', \Illuminate\Validation\Rule::in($validThemeSlugs)],
        ]);

        // Sync permissions
        if (isset($validated['permissions'])) {
            $role->syncPermissions($validated['permissions']);
        } else {
            $role->syncPermissions([]);
        }

        // Update theme if provided
        if (isset($validated['theme'])) {
            $role->update(['theme' => $validated['theme']]);
        }

        return redirect()->back()->with('success', 'Permissions updated successfully for ' . $role->name);
    }

    /**
     * Assign a single permission to a role (for AJAX requests).
     */
    public function assignPermission(Request $request, Role $role)
    {
        // Authorization check
        abort_unless(auth()->user()->hasRole('Super Manager'), 403);
        
        $validated = $request->validate([
            'permission_id' => 'required|exists:permissions,id'
        ]);
        
        $permission = Permission::findById($validated['permission_id']);
        $role->givePermissionTo($permission);
        
        return response()->json([
            'success' => true,
            'message' => 'Permission assigned successfully'
        ]);
    }

    /**
     * Remove a permission from a role (for AJAX requests).
     */
    public function removePermission(Request $request, Role $role)
    {
        // Authorization check
        abort_unless(auth()->user()->hasRole('Super Manager'), 403);
        
        $validated = $request->validate([
            'permission_id' => 'required|exists:permissions,id'
        ]);
        
        $permission = Permission::findById($validated['permission_id']);
        $role->revokePermissionTo($permission);
        
        return response()->json([
            'success' => true,
            'message' => 'Permission removed successfully'
        ]);
    }
}
