<?php

namespace App\Http\Controllers;

use App\Models\Business;
use App\Models\Lead;
use App\Models\Project;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Log;

class SearchController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->input('query');
        Log::info("Search Query: " . $query);
        $user = $request->user();

        if (!$query) {
            return response()->json([
                'businesses' => [],
                'leads' => [],
                'projects' => [],
            ]);
        }

        // Helper closure to check access
        $checkAccess = function ($item) use ($user) {
            if ($user->isAdmin()) {
                return true;
            }

            $isCreator = $item->created_by == $user->id;
            $isAssigned = $item->assignedTo->contains($user->id);

            if ($user->isHead()) {
                // Head sees if:
                // 1. Created by them (covered above) or their team
                // 2. Assigned to them (covered above) or their team
                $teamMemberIds = $user->members->pluck('id')->toArray();
                
                $isTeamCreator = in_array($item->created_by, $teamMemberIds);
                $isTeamAssigned = $item->assignedTo->whereIn('id', $teamMemberIds)->isNotEmpty();

                return $isCreator || $isAssigned || $isTeamCreator || $isTeamAssigned;
            }

            // Team Member
            return $isCreator || $isAssigned;
        };

        // Search Businesses (Global Scope)
        $businesses = Business::with(['assignedTo', 'creator'])
            ->where(function ($q) use ($query) {
                $q->where('person_name', 'like', "%{$query}%")
                    ->orWhere('company_name', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%")
                    ->orWhere('mobile', 'like', "%{$query}%")
                    ->orWhere('purpose', 'like', "%{$query}%");
            })
            ->latest()
            ->take(20) // Limit results for performance
            ->get()
            ->map(function ($business) use ($checkAccess) {
                $hasAccess = $checkAccess($business);

                return [
                    'id' => $business->id,
                    'person_name' => $business->person_name,
                    'company_name' => $business->company_name,
                    // Restricted fields
                    'email' => $hasAccess ? $business->email : '********',
                    'mobile' => $hasAccess ? $business->mobile : '********',
                    'notes' => $hasAccess ? $business->notes : '********',
                    // Visible fields
                    'purpose' => $business->purpose,
                    'added_by' => $business->creator->name ?? 'Unknown',
                    'type' => 'business',
                    'can_view_details' => $hasAccess,
                ];
            });

        // Search Leads (Global Scope)
        $leads = Lead::with(['assignedTo', 'creator'])
            ->where(function ($q) use ($query) {
                $q->where('person_name', 'like', "%{$query}%")
                    ->orWhere('company_name', 'like', "%{$query}%")
                    ->orWhere('email', 'like', "%{$query}%")
                    ->orWhere('mobile', 'like', "%{$query}%")
                    ->orWhere('purpose', 'like', "%{$query}%");
            })
            ->latest()
            ->take(20)
            ->get()
            ->map(function ($lead) use ($checkAccess) {
                $hasAccess = $checkAccess($lead);

                return [
                    'id' => $lead->id,
                    'person_name' => $lead->person_name,
                    'company_name' => $lead->company_name,
                    // Restricted
                    'email' => $hasAccess ? $lead->email : '********',
                    'mobile' => $hasAccess ? $lead->mobile : '********',
                    'notes' => $hasAccess ? $lead->notes : '********',
                    // Visible
                    'purpose' => $lead->purpose,
                    'status' => $lead->status, 
                    'added_by' => $lead->creator->name ?? 'Unknown',
                    'type' => 'lead',
                    'can_view_details' => $hasAccess,
                ];
            });

        // Search Projects (Global Scope)
        $projects = Project::with(['assignedTo', 'creator'])
            ->where(function ($q) use ($query) {
                $q->where('company_name', 'like', "%{$query}%")
                    ->orWhere('contact_person', 'like', "%{$query}%")
                    ->orWhere('mobile', 'like', "%{$query}%")
                    ->orWhere('purpose', 'like', "%{$query}%");
            })
            ->latest()
            ->take(20)
            ->get()
            ->map(function ($project) use ($checkAccess) {
                $hasAccess = $checkAccess($project);
                
                return [
                    'id' => $project->id,
                    'company_name' => $project->company_name,
                    'contact_person' => $project->contact_person,
                    // Restricted
                    'mobile' => $hasAccess ? $project->mobile : '********',
                    'notes' => $hasAccess ? $project->notes ?? '' : '********',
                    // Visible
                    'purpose' => $project->purpose,
                    'deadline' => $project->deadline,
                    'added_by' => $project->creator->name ?? 'Unknown',
                    'type' => 'project',
                    'can_view_details' => $hasAccess,
                ];
            });

        return response()->json([
            'businesses' => $businesses,
            'leads' => $leads,
            'projects' => $projects,
        ]);
    }
}
