<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Customers.php';

try {
    session_start();
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Login required.']);
        exit;
    }

    $database = new Database();    $conn = $database->getConnection();

    $term = trim((string)($_GET['term'] ?? ''));
    $customers = new Customers($conn, true); // skip schema DDL on every keystroke
    echo json_encode(['success' => true, 'customers' => $customers->search($term, 12)]);
} catch (Throwable $e) {
    error_log('Customer search failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Unable to search customers.']);
}