<?php

namespace App\Http\Controllers;

use App\Config\Constants;
use App\Models\User;
use App\Services\Activation\IActivationService;
use App\Services\Menu\IMenuRegistrarService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class BaseController extends Controller
{
    public function accessDenied()
    {
        $pageConfigs = ['myLayout' => 'blank', 'displayCustomizer' => false];

        return view('access-denied', ['pageConfigs' => $pageConfigs]);
    }

    public function Index()
    {
        $activationService = app()->make(IActivationService::class);
        $licenseInfo = $activationService->getActivationInfo();

        if (isset($licenseInfo) && isset($licenseInfo['success']) && $licenseInfo['success'] && ! auth()->check()) {
            return redirect()->route('login');
        }

        return view('activation.index', [
            'licenseInfo' => $licenseInfo,
        ]);
    }

    public function activate(Request $request)
    {
        $request->validate([
            'licenseKey' => 'required|string',
            'email' => 'required|email',
        ]);

        $licenseKey = $request->input('licenseKey');

        $activationService = app()->make(IActivationService::class);

        $email = $request->input('email', '');

        if ($request->filled('envato_username')) {
            $envatoUsername = $request->input('envato_username');
            $result = $activationService->envatoActivate($licenseKey, $envatoUsername, $email);
        } else {
            $result = $activationService->activate($licenseKey, $email);
        }

        if ($result->get('success')) {
            $activationCode = $result->get('activation_code');

            $file = storage_path('app/activation_code.txt');
            file_put_contents($file, $activationCode);

            $cacheKey = 'license_validity_'.config('app.url');
            Cache::store('file')->put($cacheKey, true, now()->addHour());

            return redirect()->route('activation.index')->with('message', 'Activation successful.');
        } else {
            $errorMsg = $result->get('message') ?? 'Activation failed. Please try again.';

            return redirect()->route('activation.index')->with('error', $errorMsg);
        }
    }

    public function getSearchDataAjax()
    {
        $user = auth()->user();
        $menuService = app(IMenuRegistrarService::class);

        // Check if dynamic menus are registered
        if ($menuService->hasRegisteredMenus()) {
            // Use dynamic menus from the registrar service
            $pages = $menuService->toSearchArray($user);
        } else {
            // Legacy: Fall back to JSON files
            $pages = $this->getSearchPagesFromLegacyJson($user);
        }

        $response = [
            'pages' => $pages,
        ];

        // Get team members for search (only active employees)
        $users = User::activeEmployees()->whereNot('id', $user->id)->get();

        $members = [];
        foreach ($users as $member) {
            $members[] = [
                'name' => $member->getFullName(),
                'subtitle' => $member->email,
                'src' => $member->profile_picture ? asset(Constants::BaseFolderEmployeeProfileWithSlash.$member->profile_picture) : null,
                'initial' => $member->getInitials(),
                'url' => 'employees/view/'.$member->id,
            ];
        }

        $response['members'] = $members;

        return response()->json($response);
    }

    /**
     * Get search pages from legacy JSON menu files.
     *
     * @return array<array{name: string, url: string, icon: string|null}>
     */
    private function getSearchPagesFromLegacyJson(User $user): array
    {
        // Determine menu file based on role priority
        $menuFilePath = base_path('resources/menu/verticalMenu.json');

        if ($user->hasRole(['hr', 'hr_manager', 'hr_executive'])) {
            $menuFilePath = base_path('resources/menu/hrMenu.json');
        } elseif ($user->hasRole(['field_employee', 'office_employee', 'manager', 'team_leader'])) {
            $menuFilePath = base_path('resources/menu/employeeMenu.json');
        }

        $menuJson = file_get_contents($menuFilePath);
        $menuData = json_decode($menuJson, true);
        $menuItems = $menuData['menu'] ?? [];

        $pages = [];
        foreach ($menuItems as $item) {
            $this->extractSearchPagesFromItem($item, $pages);
        }

        return $pages;
    }

    /**
     * Recursively extract searchable pages from a menu item.
     *
     * @param  array<string, mixed>  $item
     * @param  array<array{name: string, url: string, icon: string|null}>  $pages
     */
    private function extractSearchPagesFromItem(array $item, array &$pages): void
    {
        // Skip headers
        if (isset($item['menuHeader'])) {
            return;
        }

        // Process submenu items recursively
        if (isset($item['submenu']) && is_array($item['submenu'])) {
            foreach ($item['submenu'] as $subItem) {
                $this->extractSearchPagesFromItem($subItem, $pages);
            }
        } elseif (isset($item['url']) && $item['url'] !== 'javascript:;') {
            // Add leaf items with URLs
            $url = $item['url'];
            if (str_starts_with($url, '/')) {
                $url = substr($url, 1);
            }

            $pages[] = [
                'name' => $item['name'] ?? '',
                'url' => $url,
                'icon' => $item['icon'] ?? 'bx-file',
            ];
        }
    }
}
