38682-vm/api/search_customers.php
2026-02-25 19:30:09 +00:00

38 lines
1.3 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
$q = $_GET['q'] ?? '';
if (strlen($q) < 2) {
echo json_encode([]);
exit;
}
try {
$pdo = db();
// Fetch Loyalty Settings
$settingsStmt = $pdo->query("SELECT points_for_free_meal FROM loyalty_settings WHERE id = 1");
$settings = $settingsStmt->fetch(PDO::FETCH_ASSOC);
$threshold = $settings ? intval($settings['points_for_free_meal']) : 70;
$stmt = $pdo->prepare("SELECT id, name, phone, email, points FROM customers WHERE name LIKE ? OR phone LIKE ? LIMIT 10");
$searchTerm = "%$q%";
$stmt->execute([$searchTerm, $searchTerm]);
$customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($customers as &$customer) {
$customer['points'] = intval($customer['points']);
$customer['eligible_for_free_meal'] = $customer['points'] >= $threshold;
$customer['eligible_count'] = floor($customer['points'] / $threshold);
$customer['points_needed'] = max(0, $threshold - ($customer['points'] % $threshold));
$customer['threshold'] = $threshold;
}
echo json_encode($customers);
} catch (Exception $e) {
error_log("Customer Search Error: " . $e->getMessage());
echo json_encode(['error' => 'Database error']);
}