<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Campaign;
use App\Models\AiJob;

class SearchController extends Controller
{
    /**
     * Global search for super admin
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {
        $query = $request->input('q', '');
        
        if (strlen($query) < 2) {
            return response()->json(['results' => []]);
        }

        $results = [];

        // Search Tenants/Brands
        $tenants = Tenant::where('name', 'LIKE', "%{$query}%")
            ->orWhere('domain', 'LIKE', "%{$query}%")
            ->limit(5)
            ->get();

        foreach ($tenants as $tenant) {
            $results[] = [
                'title' => $tenant->name,
                'type' => 'Tenant/Brand',
                'url' => route('superadmin.tenants.show', $tenant->id),
                'icon' => 'fas fa-building'
            ];
        }

        // Search Users
        $users = User::where('name', 'LIKE', "%{$query}%")
            ->orWhere('email', 'LIKE', "%{$query}%")
            ->limit(5)
            ->get();

        foreach ($users as $user) {
            $results[] = [
                'title' => $user->name . ' (' . $user->email . ')',
                'type' => 'User',
                'url' => route('superadmin.users.show', $user->id),
                'icon' => 'fas fa-user'
            ];
        }

        // Search Campaigns
        try {
            $campaigns = Campaign::where('name', 'LIKE', "%{$query}%")
                ->orWhere('description', 'LIKE', "%{$query}%")
                ->limit(5)
                ->get();

            foreach ($campaigns as $campaign) {
                $results[] = [
                    'title' => $campaign->name,
                    'type' => 'Campaign',
                    'url' => route('superadmin.campaigns.show', $campaign->id),
                    'icon' => 'fas fa-bullhorn'
                ];
            }
        } catch (\Exception $e) {
            // Campaign table might not exist
        }

        // Search AI Jobs
        try {
            $aiJobs = AiJob::where('type', 'LIKE', "%{$query}%")
                ->orWhere('status', 'LIKE', "%{$query}%")
                ->limit(5)
                ->get();

            foreach ($aiJobs as $job) {
                $results[] = [
                    'title' => 'AI Job #' . $job->id . ' - ' . $job->type,
                    'type' => 'AI Job',
                    'url' => route('admin.ai-jobs.show', $job->id),
                    'icon' => 'fas fa-robot'
                ];
            }
        } catch (\Exception $e) {
            // AI Jobs table might not exist
        }

        // Add navigation items that match
        $navigationResults = $this->searchNavigation($query);
        $results = array_merge($results, $navigationResults);

        // Limit total results
        $results = array_slice($results, 0, 15);

        return response()->json(['results' => $results]);
    }

    /**
     * Search through navigation menu items
     *
     * @param string $query
     * @return array
     */
    private function searchNavigation(string $query): array
    {
        $navigationItems = [
            ['title' => 'Dashboard', 'url' => route('superadmin.dashboard'), 'type' => 'Navigation', 'icon' => 'fas fa-tachometer-alt'],
            ['title' => 'Tenants', 'url' => route('superadmin.tenants.index'), 'type' => 'Navigation', 'icon' => 'fas fa-building'],
            ['title' => 'Users', 'url' => route('superadmin.users.index'), 'type' => 'Navigation', 'icon' => 'fas fa-users'],
            ['title' => 'Roles', 'url' => route('superadmin.roles.index'), 'type' => 'Navigation', 'icon' => 'fas fa-user-shield'],
            ['title' => 'Permissions', 'url' => route('superadmin.permissions.index'), 'type' => 'Navigation', 'icon' => 'fas fa-key'],
            ['title' => 'Campaigns', 'url' => route('superadmin.campaigns.index'), 'type' => 'Navigation', 'icon' => 'fas fa-bullhorn'],
            ['title' => 'Proposals', 'url' => route('superadmin.proposals.index'), 'type' => 'Navigation', 'icon' => 'fas fa-file-contract'],
            ['title' => 'AI Jobs', 'url' => route('admin.ai-jobs.index'), 'type' => 'Navigation', 'icon' => 'fas fa-robot'],
            ['title' => 'Queue Status', 'url' => route('superadmin.queue.status'), 'type' => 'Navigation', 'icon' => 'fas fa-server'],
            ['title' => 'System Logs', 'url' => route('superadmin.logs.application'), 'type' => 'Navigation', 'icon' => 'fas fa-file-alt'],
            ['title' => 'Settings', 'url' => route('superadmin.settings.global'), 'type' => 'Navigation', 'icon' => 'fas fa-cog'],
        ];

        return array_filter($navigationItems, function($item) use ($query) {
            return stripos($item['title'], $query) !== false;
        });
    }
}