<?php

namespace App\Http\Controllers\Brand;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SidebarController extends Controller
{
    /**
     * Get badge counts for sidebar navigation
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBadges(Request $request)
    {
        try {
            $user = $request->user();
            $brandId = $user->brand_id;

            // Get pending proposals count
            $pendingProposals = DB::table('proposals')
                ->where('brand_id', $brandId)
                ->whereIn('status', ['draft', 'sent', 'negotiation'])
                ->count();

            // Get active campaigns count
            $activeCampaigns = DB::table('campaigns')
                ->where('brand_id', $brandId)
                ->where('status', 'active')
                ->count();

            // Get unread messages count
            $unreadMessages = DB::table('message_threads')
                ->join('messages', 'message_threads.id', '=', 'messages.thread_id')
                ->where('message_threads.brand_id', $brandId)
                ->where('messages.sender_id', '!=', $user->id)
                ->whereNull('messages.read_at')
                ->distinct('message_threads.id')
                ->count('message_threads.id');

            // Get notifications count (unread)
            $notifications = $user->unreadNotifications()->count();

            return response()->json([
                'success' => true,
                'badges' => [
                    'pendingProposals' => $pendingProposals,
                    'activeCampaigns' => $activeCampaigns,
                    'unreadMessages' => $unreadMessages,
                    'notifications' => $notifications,
                ]
            ]);
        } catch (\Exception $e) {
            \Log::error('Brand sidebar badges error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'badges' => [
                    'pendingProposals' => 0,
                    'activeCampaigns' => 0,
                    'unreadMessages' => 0,
                    'notifications' => 0,
                ]
            ], 500);
        }
    }

    /**
     * Get quick search results
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function quickSearch(Request $request)
    {
        $query = $request->input('query', '');
        $user = $request->user();
        $brandId = $user->brand_id;

        if (strlen($query) < 2) {
            return response()->json([
                'success' => true,
                'results' => []
            ]);
        }

        $results = [];

        // Search campaigns
        $campaigns = DB::table('campaigns')
            ->where('brand_id', $brandId)
            ->where('name', 'LIKE', "%{$query}%")
            ->limit(5)
            ->get(['id', 'name', 'status']);

        foreach ($campaigns as $campaign) {
            $results[] = [
                'name' => $campaign->name,
                'category' => 'Campaign',
                'url' => route('brand.campaigns.show', $campaign->id),
                'meta' => "Status: {$campaign->status}"
            ];
        }

        // Search creators
        $creators = DB::table('users')
            ->where('name', 'LIKE', "%{$query}%")
            ->whereHas('roles', function ($q) {
                $q->where('name', 'creator');
            })
            ->limit(5)
            ->get(['id', 'name', 'email']);

        foreach ($creators as $creator) {
            $results[] = [
                'name' => $creator->name,
                'category' => 'Creator',
                'url' => route('brand.creators.show', $creator->id),
                'meta' => $creator->email
            ];
        }

        // Search proposals
        $proposals = DB::table('proposals')
            ->where('brand_id', $brandId)
            ->where('title', 'LIKE', "%{$query}%")
            ->limit(5)
            ->get(['id', 'title', 'status']);

        foreach ($proposals as $proposal) {
            $results[] = [
                'name' => $proposal->title,
                'category' => 'Proposal',
                'url' => route('brand.proposals.show', $proposal->id),
                'meta' => "Status: {$proposal->status}"
            ];
        }

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