501 lines
21 KiB
PHP
501 lines
21 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Art;
|
|
use App\Models\Book;
|
|
use App\Models\Branch;
|
|
use App\Models\BylawDocument;
|
|
use App\Models\Chapter;
|
|
use App\Models\Division;
|
|
use App\Models\Gate;
|
|
use App\Models\JudicialPrecedent;
|
|
use App\Models\Law;
|
|
use App\Models\LegalOpinion;
|
|
use App\Models\Part;
|
|
use App\Models\Section;
|
|
use App\Models\Volum;
|
|
use App\Traits\BaseApiResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class GlobalSearchApiController extends Controller
|
|
{
|
|
use BaseApiResponse;
|
|
|
|
/**
|
|
* Massive Search across ALL data types
|
|
*/
|
|
public function search(Request $request)
|
|
{
|
|
$request->validate([
|
|
'search' => 'nullable|string',
|
|
'sort_by' => 'nullable|in:date,number',
|
|
'sort' => 'nullable|in:asc,desc',
|
|
'per_page' => 'nullable|integer|min:1|max:100',
|
|
'page' => 'nullable|integer|min:1',
|
|
]);
|
|
|
|
$searchTerm = $request->input('search');
|
|
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
|
|
$page = (int) $request->input('page', 1);
|
|
|
|
$staticResults = collect(); // Arts and Structures (Always at the top)
|
|
$sortableResults = collect(); // Bylaws, Opinions, Precedents (Sorted if requested)
|
|
|
|
if (!empty($searchTerm)) {
|
|
$limitPerTable = 100;
|
|
|
|
// =========================================================
|
|
// 1. Search Arts (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('number', 'LIKE', "%{$searchTerm}%");
|
|
})
|
|
->take($limitPerTable)->get()->map(function($item) use ($searchTerm) {
|
|
$formatted = $this->formatArt($item, $searchTerm, Art::class);
|
|
$formatted['type'] = 'art';
|
|
return $formatted;
|
|
});
|
|
$staticResults = $staticResults->concat($arts);
|
|
|
|
// =========================================================
|
|
// 2. Search Laws and Structural Models (Exact match to ArtController)
|
|
// =========================================================
|
|
$structuralModels = [
|
|
Law::class, Volum::class, Book::class, Division::class,
|
|
Section::class, Chapter::class, Part::class, Gate::class,
|
|
Branch::class
|
|
];
|
|
|
|
foreach ($structuralModels as $modelClass) {
|
|
$query = $modelClass::query();
|
|
$modelInstance = new $modelClass;
|
|
$table = $modelInstance->getTable();
|
|
|
|
$query->where('title', 'LIKE', "%{$searchTerm}%");
|
|
|
|
$items = $query->take($limitPerTable)->get()->map(function($item) use ($modelClass, $table) {
|
|
$formatted = $this->formatStructure($item, $modelClass);
|
|
$formatted['type'] = ($table === 'section') ? 'sections' : $table;
|
|
return $formatted;
|
|
});
|
|
|
|
$staticResults = $staticResults->concat($items);
|
|
}
|
|
|
|
// =========================================================
|
|
// 3. Search Bylaw Documents
|
|
// =========================================================
|
|
$bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
|
|
->where('is_published', true)
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('title', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('description', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhereIn('id', function($subQuery) use ($searchTerm) {
|
|
$subQuery->select('document_id')
|
|
->from('bylaw_nodes')
|
|
->where('node_content', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('title', 'LIKE', "%{$searchTerm}%");
|
|
});
|
|
})->take($limitPerTable)->get();
|
|
|
|
// Safely bulk-fetch nodes using DB facade
|
|
$docIds = $bylawsQuery->pluck('id')->toArray();
|
|
$allNodes = collect();
|
|
if (!empty($docIds)) {
|
|
$allNodes = DB::table('bylaw_nodes')
|
|
->whereIn('document_id', $docIds)
|
|
->orderBy('sort_order', 'asc')
|
|
->get();
|
|
}
|
|
|
|
$bylaws = $bylawsQuery->map(function($item) use ($allNodes) {
|
|
$itemNodes = $allNodes->where('document_id', $item->id);
|
|
$formatted = $this->formatBylaw($item, $itemNodes);
|
|
$formatted['type'] = 'bylaw';
|
|
return $formatted;
|
|
});
|
|
$sortableResults = $sortableResults->concat($bylaws);
|
|
|
|
// =========================================================
|
|
// 4. Search Judicial Precedents
|
|
// =========================================================
|
|
$judicials = JudicialPrecedent::with('category')
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
|
|
})->take($limitPerTable)->get()->map(function($item) {
|
|
$formatted = $this->formatJudicial($item);
|
|
$formatted['type'] = 'judicial_precedent';
|
|
return $formatted;
|
|
});
|
|
$sortableResults = $sortableResults->concat($judicials);
|
|
|
|
// =========================================================
|
|
// 5. Search Legal Opinions
|
|
// =========================================================
|
|
$opinions = LegalOpinion::with('category')
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
|
|
})->take($limitPerTable)->get()->map(function($item) {
|
|
$formatted = $this->formatOpinion($item);
|
|
$formatted['type'] = 'legal_opinion';
|
|
return $formatted;
|
|
});
|
|
$sortableResults = $sortableResults->concat($opinions);
|
|
}
|
|
|
|
// --- Apply Dynamic Memory Sorting ONLY to Legal Docs ---
|
|
if ($request->has('sort_by') && $request->input('sort_by') != null) {
|
|
$sortBy = $request->input('sort_by');
|
|
$sortOrder = $request->input('sort', 'desc');
|
|
|
|
if ($sortBy === 'number') {
|
|
$sortCallback = function ($item) {
|
|
return (string) ($item['promulgation_number'] ?? $item['ruling_number'] ?? $item['opinion_number'] ?? '0');
|
|
};
|
|
|
|
if ($sortOrder === 'asc') {
|
|
$sortableResults = $sortableResults->sortBy($sortCallback, SORT_NATURAL)->values();
|
|
} else {
|
|
$sortableResults = $sortableResults->sortByDesc($sortCallback, SORT_NATURAL)->values();
|
|
}
|
|
} elseif ($sortBy === 'date') {
|
|
$sortCallback = function ($item) {
|
|
return (string) ($item['approval_date'] ?? $item['ruling_date'] ?? $item['opinion_date'] ?? '1970-01-01');
|
|
};
|
|
|
|
if ($sortOrder === 'asc') {
|
|
$sortableResults = $sortableResults->sortBy($sortCallback)->values();
|
|
} else {
|
|
$sortableResults = $sortableResults->sortByDesc($sortCallback)->values();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Combine Results: Arts and Structures ALWAYS pin to the top!
|
|
$results = $staticResults->concat($sortableResults);
|
|
|
|
// --- Execute Manual Pagination on the final Collection ---
|
|
$total = $results->count();
|
|
$paginatedItems = $results->forPage($page, $perPage)->values();
|
|
|
|
$paginator = new LengthAwarePaginator(
|
|
$paginatedItems,
|
|
$total,
|
|
$perPage,
|
|
$page,
|
|
['path' => $request->url(), 'query' => $request->query()]
|
|
);
|
|
|
|
$responseData = [
|
|
'items' => $paginator->items(),
|
|
'current_page' => $paginator->currentPage(),
|
|
'last_page' => $paginator->lastPage(),
|
|
'per_page' => $paginator->perPage(),
|
|
'total' => $paginator->total(),
|
|
];
|
|
|
|
return $this->success($responseData, 'Success', 'Global Search Results Fetched');
|
|
}
|
|
|
|
/**
|
|
* Top-level fast search for quick dropdown UI elements
|
|
*/
|
|
public function fast_search(Request $request)
|
|
{
|
|
$searchTerm = $request->input('search');
|
|
$results = collect();
|
|
$totalCount = 0;
|
|
|
|
$limitPerTable = 3;
|
|
|
|
if (!empty($searchTerm)) {
|
|
|
|
// 1. Search Arts FIRST
|
|
$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('number', 'LIKE', "%{$searchTerm}%");
|
|
});
|
|
$totalCount += $artQuery->count();
|
|
$arts = $artQuery->take($limitPerTable)->get()->map(function($item) use ($searchTerm) {
|
|
$formatted = $this->formatArt($item, $searchTerm, Art::class);
|
|
$formatted['type'] = 'art';
|
|
return $formatted;
|
|
});
|
|
$results = $results->concat($arts);
|
|
|
|
// 2. Structural Models
|
|
$structuralModels = [
|
|
Law::class, Volum::class, Book::class, Division::class,
|
|
Section::class, Chapter::class, Part::class, Gate::class,
|
|
Branch::class
|
|
];
|
|
|
|
foreach ($structuralModels as $modelClass) {
|
|
$query = $modelClass::query();
|
|
$modelInstance = new $modelClass;
|
|
$table = $modelInstance->getTable();
|
|
|
|
$query->where('title', 'LIKE', "%{$searchTerm}%");
|
|
|
|
$totalCount += $query->count();
|
|
|
|
if ($results->count() < 15) {
|
|
$items = $query->take($limitPerTable)->get()->map(function($item) use ($modelClass, $table) {
|
|
$formatted = $this->formatStructure($item, $modelClass);
|
|
$formatted['type'] = ($table === 'section') ? 'sections' : $table;
|
|
return $formatted;
|
|
});
|
|
$results = $results->concat($items);
|
|
}
|
|
}
|
|
|
|
// 3. Bylaw Documents
|
|
$bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
|
|
->where('is_published', true)
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('title', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('description', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhereIn('id', function($subQuery) use ($searchTerm) {
|
|
$subQuery->select('document_id')
|
|
->from('bylaw_nodes')
|
|
->where('node_content', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('title', 'LIKE', "%{$searchTerm}%");
|
|
});
|
|
});
|
|
|
|
$totalCount += $bylawsQuery->count();
|
|
$bylawsRaw = $bylawsQuery->take($limitPerTable)->get();
|
|
|
|
// Bulk-fetch nodes safely using DB facade
|
|
$docIds = $bylawsRaw->pluck('id')->toArray();
|
|
$allNodes = collect();
|
|
if (!empty($docIds)) {
|
|
$allNodes = DB::table('bylaw_nodes')
|
|
->whereIn('document_id', $docIds)
|
|
->orderBy('sort_order', 'asc')
|
|
->get();
|
|
}
|
|
|
|
$bylaws = $bylawsRaw->map(function($item) use ($allNodes) {
|
|
$itemNodes = $allNodes->where('document_id', $item->id);
|
|
$formatted = $this->formatBylaw($item, $itemNodes);
|
|
$formatted['type'] = 'bylaw';
|
|
return $formatted;
|
|
});
|
|
$results = $results->concat($bylaws);
|
|
|
|
// 4. Judicial Precedents
|
|
$judicialQuery = JudicialPrecedent::with('category')
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
|
|
});
|
|
$totalCount += $judicialQuery->count();
|
|
$judicials = $judicialQuery->take($limitPerTable)->get()->map(function($item) {
|
|
$formatted = $this->formatJudicial($item);
|
|
$formatted['type'] = 'judicial_precedent';
|
|
return $formatted;
|
|
});
|
|
$results = $results->concat($judicials);
|
|
|
|
// 5. Legal Opinions
|
|
$opinionQuery = LegalOpinion::with('category')
|
|
->where(function ($q) use ($searchTerm) {
|
|
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
|
|
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
|
|
});
|
|
$totalCount += $opinionQuery->count();
|
|
$opinions = $opinionQuery->take($limitPerTable)->get()->map(function($item) {
|
|
$formatted = $this->formatOpinion($item);
|
|
$formatted['type'] = 'legal_opinion';
|
|
return $formatted;
|
|
});
|
|
$results = $results->concat($opinions);
|
|
}
|
|
|
|
return $this->success([
|
|
'items' => $results->take(15)->values(),
|
|
'count' => $totalCount
|
|
], 'Success', 'Global Fast Search Results');
|
|
}
|
|
|
|
/* -----------------------------------------------------------------
|
|
* FORMATTING HELPERS
|
|
* ----------------------------------------------------------------- */
|
|
|
|
private function isLockedForCurrentUserGeneric($item): bool
|
|
{
|
|
if (auth()->check() && auth()->user() && method_exists(auth()->user(), 'isSubscriber')) {
|
|
return !auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
|
|
}
|
|
return (bool) ($item->is_locked ?? false);
|
|
}
|
|
|
|
/**
|
|
* Exact 1:1 match with BylawApiController's encoding approach
|
|
*/
|
|
private function formatBylaw($item, $itemNodes = null)
|
|
{
|
|
$isLocked = $this->isLockedForCurrentUserGeneric($item);
|
|
|
|
if ($itemNodes === null) {
|
|
$itemNodes = DB::table('bylaw_nodes')->where('document_id', $item->id)->orderBy('sort_order', 'asc')->get();
|
|
}
|
|
|
|
$nodeContentAsDescription = collect($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");
|
|
|
|
if (empty($nodeContentAsDescription)) {
|
|
$nodeContentAsDescription = mb_convert_encoding(trim((string)$item->description), 'UTF-8', 'UTF-8');
|
|
}
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'title' => $item->title,
|
|
'category_name' => optional($item->category)->name,
|
|
'approval_authority_name' => optional($item->approvalAuthority)->name,
|
|
'approval_date' => $item->approval_date,
|
|
'promulgation_number' => $item->promulgation_number,
|
|
'description' => $isLocked ? null : $nodeContentAsDescription,
|
|
'is_locked' => $isLocked,
|
|
];
|
|
}
|
|
|
|
private function formatJudicial($item)
|
|
{
|
|
$isLocked = $this->isLockedForCurrentUserGeneric($item);
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'title' => $item->subject,
|
|
'ruling_number' => $item->ruling_number,
|
|
'ruling_date' => $item->ruling_date,
|
|
'text' => $isLocked ? null : $item->full_text,
|
|
'issuing_authority' => $item->issuing_authority,
|
|
'category_name' => optional($item->category)->name,
|
|
'is_locked' => $isLocked,
|
|
];
|
|
}
|
|
|
|
private function formatOpinion($item)
|
|
{
|
|
$isLocked = $this->isLockedForCurrentUserGeneric($item);
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'title' => $item->subject,
|
|
'opinion_number' => $item->opinion_number,
|
|
'opinion_date' => $item->opinion_date,
|
|
'text' => $isLocked ? null : $item->full_text,
|
|
'issuing_authority' => $item->issuing_authority,
|
|
'category_name' => optional($item->category)->name,
|
|
'is_locked' => $isLocked,
|
|
];
|
|
}
|
|
|
|
private function formatArt($item, $searchTerm, $modelClass)
|
|
{
|
|
$law = $item->law ?? Law::find($item->law_id);
|
|
$isLocked = ! auth()->user()->isSubscriber() && (bool) ($law?->is_locked ?? false);
|
|
|
|
$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 {
|
|
$context = $text;
|
|
}
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'title' => $item->title,
|
|
'number' => $item->number,
|
|
'text' => $isLocked ? null : $context,
|
|
'is_locked' => $isLocked,
|
|
'route' => array_values($this->route($modelClass, $item)),
|
|
'category' => optional($law?->category)->name,
|
|
'law' => $law?->title ?? '',
|
|
'count_art' => $law?->arts?->count() ?? 0,
|
|
'count_volums' => $law?->volums?->count() ?? 0,
|
|
'count_volum' => $law?->volums?->count() ?? 0,
|
|
'price' => $law?->price,
|
|
'image' => $law?->image,
|
|
];
|
|
}
|
|
|
|
private function formatStructure($item, $modelClass)
|
|
{
|
|
$law = Law::find($item?->law_id ?? $item->id);
|
|
$isLocked = ! auth()->user()->isSubscriber() && (bool) ($law?->is_locked ?? false);
|
|
|
|
$payload = [
|
|
'id' => $item->id,
|
|
'title' => $item->title,
|
|
'number' => $item->number,
|
|
'is_locked' => $isLocked,
|
|
'route' => array_values($this->route($modelClass, $item)),
|
|
'law' => $law?->title ?? '',
|
|
];
|
|
|
|
if ((new $modelClass)->getTable() == 'laws') {
|
|
$payload['category'] = optional($law?->category)?->name ?? '';
|
|
$payload['image'] = $law?->image;
|
|
}
|
|
|
|
return $payload;
|
|
}
|
|
|
|
private function route($modelClass, $query)
|
|
{
|
|
if ((new $modelClass)->getTable() == 'art') {
|
|
$route = array_filter([
|
|
$query->relationLoaded('law') ? $query->law?->title : Law::find($query->law_id)?->title,
|
|
$query->relationLoaded('volum') ? $query->volum?->title : Volum::find($query->volum_id)?->title,
|
|
$query->relationLoaded('book') ? $query->book?->title : Book::find($query->book_id)?->title,
|
|
Division::find($query->division_id)?->title,
|
|
$query->relationLoaded('section') ? $query->section?->title : Section::find($query->section_id)?->title,
|
|
$query->relationLoaded('chapter') ? $query->chapter?->title : Chapter::find($query->chapter_id)?->title,
|
|
$query->relationLoaded('part') ? $query->part?->title : Part::find($query->part_id)?->title,
|
|
$query->relationLoaded('gate') ? $query->gate?->title : Gate::find($query->gate_id)?->title,
|
|
Branch::find($query->branch_id)?->title,
|
|
]);
|
|
return array_values($route);
|
|
}
|
|
|
|
if ((new $modelClass)->getTable() == 'laws') {
|
|
return array_values(array_filter([Law::find($query->id)?->title]));
|
|
}
|
|
|
|
return [];
|
|
}
|
|
}
|