TKK_E32230273/search_api.php

86 lines
3.2 KiB
PHP

<?php
require_once 'koneksi.php';
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
header('Content-Type: application/json');
$q = isset($_GET['q']) ? trim($_GET['q']) : '';
if (strlen($q) < 1) {
echo json_encode(['status' => 'success', 'data' => ['overview' => [], 'account' => [], 'occupant' => []]]);
exit;
}
// ========== OVERVIEW (Sidebar Menus) ==========
$menus = [
['name' => 'Dashboard', 'category' => 'Main', 'icon' => 'icon-grid', 'url' => 'dashboard.php'],
['name' => 'Profile', 'category' => 'Main', 'icon' => 'ti-github', 'url' => 'profile.php'],
['name' => 'New Occupant', 'category' => 'Occupant', 'icon' => 'icon-layout', 'url' => 'new_occupant.php'],
['name' => 'Manage Occupant','category' => 'Occupant', 'icon' => 'icon-layout', 'url' => 'manage_occupant.php'],
['name' => 'Access', 'category' => 'Main', 'icon' => 'icon-toggle', 'url' => 'access.php'],
['name' => 'New Account', 'category' => 'Account', 'icon' => 'icon-head', 'url' => 'new_account.php'],
['name' => 'Operations Account', 'category' => 'Account', 'icon' => 'icon-head', 'url' => 'operations_account.php'],
['name' => 'Schedule', 'category' => 'Main', 'icon' => 'icon-clock', 'url' => 'schedule.php'],
['name' => 'History', 'category' => 'Main', 'icon' => 'icon-paper', 'url' => 'history.php'],
['name' => 'Notifications','category' => 'Main', 'icon' => 'icon-bell', 'url' => 'notifications.php'],
['name' => 'Chat', 'category' => 'Main', 'icon' => 'ti-comments', 'url' => 'chats.php'],
];
$overviewResults = [];
$qLower = mb_strtolower($q);
foreach ($menus as $m) {
if (
mb_strpos(mb_strtolower($m['name']), $qLower) !== false ||
mb_strpos(mb_strtolower($m['category']), $qLower) !== false
) {
$overviewResults[] = $m;
}
}
// ========== ACCOUNT ==========
$accountResults = [];
try {
$like = '%' . $q . '%';
$stmt = $pdo->prepare("SELECT id_account, name, username, foto FROM account WHERE name LIKE ? OR username LIKE ? ORDER BY name ASC LIMIT 5");
$stmt->execute([$like, $like]);
$accountResults = $stmt->fetchAll();
// Ensure foto has a fallback
foreach ($accountResults as &$a) {
if (empty($a['foto']) || !file_exists($a['foto'])) {
$a['foto'] = 'images/admin.png';
}
}
unset($a);
} catch (Exception $e) {
// silently fail
}
// ========== OCCUPANT ==========
$occupantResults = [];
try {
$like = '%' . $q . '%';
$stmt = $pdo->prepare("SELECT id_occupant, name, foto, no_hp FROM occupant WHERE name LIKE ? OR no_hp LIKE ? ORDER BY name ASC LIMIT 5");
$stmt->execute([$like, $like]);
$occupantResults = $stmt->fetchAll();
// Ensure foto has a fallback
foreach ($occupantResults as &$o) {
if (empty($o['foto']) || !file_exists($o['foto'])) {
$o['foto'] = 'images/admin.png';
}
}
unset($o);
} catch (Exception $e) {
// silently fail
}
echo json_encode([
'status' => 'success',
'data' => [
'overview' => $overviewResults,
'account' => $accountResults,
'occupant' => $occupantResults,
]
]);