diff --git a/app/Http/Controllers/api/GlobalSearchApiController.php b/app/Http/Controllers/api/GlobalSearchApiController.php index faad13e..ad156f9 100644 --- a/app/Http/Controllers/api/GlobalSearchApiController.php +++ b/app/Http/Controllers/api/GlobalSearchApiController.php @@ -7,6 +7,7 @@ use App\Models\Art; use App\Models\Book; use App\Models\Branch; use App\Models\BylawDocument; +use App\Models\BylawNode; use App\Models\Chapter; use App\Models\Division; use App\Models\Gate; @@ -49,12 +50,13 @@ class GlobalSearchApiController extends Controller $limitPerTable = 100; // ========================================================= - // 1. Search Arts (Exact match to ArtController) + // 1. Search Arts FIRST (Exact match to ArtController) // ========================================================= $arts = Art::with(['law.category', 'chapter', 'part', 'volum', 'book', 'section', 'gate']) ->where(function ($q) use ($searchTerm) { $q->where('title', 'LIKE', "%{$searchTerm}%") - ->orWhere('text', 'LIKE', "%{$searchTerm}%"); + ->orWhere('text', 'LIKE', "%{$searchTerm}%") + ->orWhere('number', 'LIKE', "%{$searchTerm}%"); }) ->take($limitPerTable)->get()->map(function($item) use ($searchTerm) { $formatted = $this->formatArt($item, $searchTerm, Art::class); @@ -64,7 +66,7 @@ class GlobalSearchApiController extends Controller $staticResults = $staticResults->concat($arts); // ========================================================= - // 2. Search Laws and Structural Models (Exact match to ArtController) + // 2. Search Laws and Structural Models // ========================================================= $structuralModels = [ Law::class, Volum::class, Book::class, Division::class, @@ -89,9 +91,9 @@ class GlobalSearchApiController extends Controller } // ========================================================= - // 3. Search Bylaw Documents + // 3. Search Bylaw Documents (With fixed node_content fetching) // ========================================================= - $bylaws = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) + $bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) ->where('is_published', true) ->where(function ($q) use ($searchTerm) { $q->where('title', 'LIKE', "%{$searchTerm}%") @@ -103,11 +105,24 @@ class GlobalSearchApiController extends Controller ->from('bylaw_nodes') ->where('node_content', 'LIKE', "%{$searchTerm}%"); }); - })->take($limitPerTable)->get()->map(function($item) { - $formatted = $this->formatBylaw($item); - $formatted['type'] = 'bylaw'; - return $formatted; - }); + })->take($limitPerTable)->get(); + + // Safely bulk-fetch nodes for these bylaws + $docIds = $bylawsQuery->pluck('id')->map(fn($id) => (int)$id)->toArray(); + $nodesByDoc = collect(); + if (!empty($docIds)) { + $nodesByDoc = BylawNode::whereIn('document_id', $docIds) + ->orderBy('sort_order', 'asc') + ->get() + ->groupBy(fn($node) => (int)$node->document_id); + } + + $bylaws = $bylawsQuery->map(function($item) use ($nodesByDoc) { + $itemNodes = $nodesByDoc->get((int)$item->id, collect()); + $formatted = $this->formatBylaw($item, $itemNodes); + $formatted['type'] = 'bylaw'; + return $formatted; + }); $sortableResults = $sortableResults->concat($bylaws); // ========================================================= @@ -193,7 +208,7 @@ class GlobalSearchApiController extends Controller 'total' => $paginator->total(), ]; - return $this->success($responseData, '', ''); + return $this->success($responseData, 'Success', 'Global Search Results Fetched'); } /** @@ -213,7 +228,8 @@ class GlobalSearchApiController extends Controller $artQuery = Art::with(['law', 'law.category', 'chapter', 'part', 'volum', 'book', 'section', 'gate']) ->where(function ($q) use ($searchTerm) { $q->where('title', 'LIKE', "%{$searchTerm}%") - ->orWhere('text', 'LIKE', "%{$searchTerm}%"); + ->orWhere('text', 'LIKE', "%{$searchTerm}%") + ->orWhere('number', 'LIKE', "%{$searchTerm}%"); }); $totalCount += $artQuery->count(); $arts = $artQuery->take($limitPerTable)->get()->map(function($item) use ($searchTerm) { @@ -250,7 +266,7 @@ class GlobalSearchApiController extends Controller } // 3. Bylaw Documents - $bylawQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) + $bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) ->where('is_published', true) ->where(function ($q) use ($searchTerm) { $q->where('title', 'LIKE', "%{$searchTerm}%") @@ -263,9 +279,22 @@ class GlobalSearchApiController extends Controller ->where('node_content', 'LIKE', "%{$searchTerm}%"); }); }); - $totalCount += $bylawQuery->count(); - $bylaws = $bylawQuery->take($limitPerTable)->get()->map(function($item) { - $formatted = $this->formatBylaw($item); + + $totalCount += $bylawsQuery->count(); + $bylawsRaw = $bylawsQuery->take($limitPerTable)->get(); + + $docIds = $bylawsRaw->pluck('id')->map(fn($id) => (int)$id)->toArray(); + $nodesByDoc = collect(); + if (!empty($docIds)) { + $nodesByDoc = BylawNode::whereIn('document_id', $docIds) + ->orderBy('sort_order', 'asc') + ->get() + ->groupBy(fn($node) => (int)$node->document_id); + } + + $bylaws = $bylawsRaw->map(function($item) use ($nodesByDoc) { + $itemNodes = $nodesByDoc->get((int)$item->id, collect()); + $formatted = $this->formatBylaw($item, $itemNodes); $formatted['type'] = 'bylaw'; return $formatted; }); @@ -306,7 +335,7 @@ class GlobalSearchApiController extends Controller return $this->success([ 'items' => $results->take(15)->values(), 'count' => $totalCount - ], '', ''); + ], 'Success', 'Global Fast Search Results'); } /* ----------------------------------------------------------------- @@ -318,21 +347,31 @@ class GlobalSearchApiController extends Controller return ! auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false); } - private function formatBylaw($item) + /** + * UPDATED: Uses the exact encoding and fallback logic tested in BylawApiController + */ + private function formatBylaw($item, $itemNodes = null) { $isLocked = $this->isLockedForCurrentUserGeneric($item); - $description = $item->description; - $cleanDesc = trim(strip_tags($description ?? '')); + if ($itemNodes === null) { + $itemNodes = BylawNode::where('document_id', $item->id)->orderBy('sort_order', 'asc')->get(); + } - if (empty($cleanDesc)) { - $nodeContents = DB::table('bylaw_nodes') - ->where('document_id', $item->id) - ->orderBy('sort_order', 'asc') - ->pluck('node_content') - ->toArray(); + // Extract content and encode safely (fixes JSON encoding bugs) + $nodeContentAsDescription = $itemNodes->pluck('node_content') + ->map(function ($text) { + $safeText = trim((string)$text); + return mb_convert_encoding($safeText, 'UTF-8', 'UTF-8'); + }) + ->filter(function ($text) { + return $text !== ''; + }) + ->implode("\n\n"); - $description = implode("\n\n", array_filter($nodeContents)); + // If the database nodes were actually empty, fallback to the description column + if (empty($nodeContentAsDescription)) { + $nodeContentAsDescription = mb_convert_encoding(trim((string)$item->description), 'UTF-8', 'UTF-8'); } return [ @@ -342,7 +381,7 @@ class GlobalSearchApiController extends Controller 'approval_authority_name' => optional($item->approvalAuthority)->name, 'approval_date' => $item->approval_date, 'promulgation_number' => $item->promulgation_number, - 'description' => $isLocked ? null : $description, + 'description' => $isLocked ? null : $nodeContentAsDescription, 'is_locked' => $isLocked, ]; } @@ -379,10 +418,6 @@ class GlobalSearchApiController extends Controller ]; } - /** - * Exact 1:1 match with ArtController::searchModel mapping - * All relations (law, chapter, etc) are strictly Strings to prevent App Crashes! - */ private function formatArt($item, $searchTerm, $modelClass) { $law = $item->law ?? Law::find($item->law_id); @@ -390,6 +425,7 @@ class GlobalSearchApiController extends Controller $text = $item->text ?? ''; $searchQuoted = preg_quote($searchTerm, '/'); + if (!empty($searchTerm) && preg_match('/\b(.{0,50})\b('.$searchQuoted.')\b(.{0,50})\b/i', $text, $matches)) { $context = trim($matches[1] ?? '').' '.($matches[2] ?? '').' '.trim($matches[3] ?? ''); } else { @@ -404,10 +440,10 @@ class GlobalSearchApiController extends Controller 'is_locked' => $isLocked, 'route' => array_values($this->route($modelClass, $item)), 'category' => optional($law?->category)->name, - 'law' => $law?->title ?? '', // STRICLY STRING! Prevents Android App Crash! + 'law' => $law?->title ?? '', // STRICLY STRING 'count_art' => $law?->arts?->count() ?? 0, - 'count_volums' => $law?->volums?->count() ?? 0, // WITH S - 'count_volum' => $law?->volums?->count() ?? 0, // WITHOUT S (Fallback) + 'count_volums' => $law?->volums?->count() ?? 0, + 'count_volum' => $law?->volums?->count() ?? 0, 'price' => $law?->price, 'image' => $law?->image, ];