<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 */

namespace App\Services\System;

use App\Models\User;
use App\Services\SystemConfig\SettingDefinitions;

class GlobalSearchService
{
    /**
     * Search for users, pages, and settings.
     */
    public function search(string $query): array
    {
        $results = [];
        $query = strtolower(trim($query));

        if (empty($query)) {
            return $results;
        }

        // 1. Search Users
        $users = User::where('name', 'ILIKE', "%{$query}%")
            ->orWhere('email', 'ILIKE', "%{$query}%")
            ->orWhere('username', 'ILIKE', "%{$query}%")
            ->take(5)
            ->get()
            ->map(function ($user) {
                return [
                    'title' => $user->name,
                    'subtitle' => 'User: '.$user->email,
                    'url' => route('users').'?search='.urlencode($user->email),
                    'icon' => 'bi-person',
                    'category' => 'Users',
                ];
            });
        $results = array_merge($results, $users->toArray());

        // 2. Search Pages (Menus)
        $pages = [
            ['title' => 'Dashboard',               'url' => route('dashboard'),                  'icon' => 'bi-speedometer2'],
            ['title' => 'User Directory',           'url' => route('users'),                      'icon' => 'bi-people'],
            ['title' => 'Access Rights (Roles)',    'url' => route('roles'),                      'icon' => 'bi-shield-lock'],
            ['title' => 'Permissions',              'url' => route('permissions'),                'icon' => 'bi-key'],
            ['title' => 'Action Logs',              'url' => route('action-logs'),                'icon' => 'bi-journal-text'],
            ['title' => 'Notification Center',      'url' => route('notification-center.index'),  'icon' => 'bi-bell'],
            ['title' => 'Health & Logs',            'url' => route('system-monitoring'),          'icon' => 'bi-activity'],
            ['title' => 'Session Manager',          'url' => route('session-manager'),            'icon' => 'bi-person-badge'],
            ['title' => 'Global Settings',          'url' => route('system-config'),              'icon' => 'bi-gear'],
            ['title' => 'Mobile Settings',          'url' => route('mobile-settings.index'),      'icon' => 'bi-phone'],
            ['title' => 'Backup & Storage',         'url' => route('backup-restore.index'),       'icon' => 'bi-cloud-download'],
            ['title' => 'Maintenance Mode',         'url' => route('maintenance-mode'),           'icon' => 'bi-wrench'],
            ['title' => 'AI Self-Healing',          'url' => route('ai-self-healing.index'),      'icon' => 'bi-heart-pulse'],
            ['title' => 'My Profile',               'url' => route('profile.edit'),               'icon' => 'bi-person-circle'],
        ];

        foreach ($pages as $page) {
            if (str_contains(strtolower($page['title']), $query)) {
                $page['category'] = 'Pages';
                $page['subtitle'] = 'Navigation';
                $results[] = $page;
            }
        }

        // 3. Search Settings (from SettingDefinitions)
        $settingsResults = [];
        foreach (SettingDefinitions::ALL as $key => $meta) {
            $title = str_replace('_', ' ', $key);
            $description = $meta['description'];

            if (str_contains(strtolower($title), $query) || str_contains(strtolower($description), $query)) {
                $settingsResults[] = [
                    'title' => ucwords($title),
                    'subtitle' => 'Setting: '.$description,
                    'url' => route('system-config').'?anchor='.$meta['group'],
                    'icon' => 'bi-sliders',
                    'category' => 'Settings',
                ];
            }
            if (count($settingsResults) >= 10) {
                break;
            }
        }
        $results = array_merge($results, $settingsResults);

        // 4. AI Assistance Trigger
        if ((str_ends_with($query, '?') || strlen($query) > 10) && auth()->user()->can('use ai assistant')) {
            $results[] = [
                'title' => 'Ask AI Assistant',
                'subtitle' => 'Query: "'.$query.'"',
                'url' => '#ask-ai',
                'icon' => 'bi-robot',
                'category' => 'AI Help',
                'is_ai' => true,
                'query' => $query,
            ];
        }

        return $results;
    }
}
