<?php
require_once '../../config/db.php';
header('Content-Type: application/json');

$q = trim($_GET['q'] ?? '');

try {
    if($q === '') {
        $stmt = $pdo->prepare(
            "SELECT id, name, phone FROM parties
             WHERE deleted_at IS NULL
             ORDER BY id DESC LIMIT 10"
        );
        $stmt->execute();
    } else {
        $like = '%' . $q . '%';
        $stmt = $pdo->prepare(
            "SELECT id, name, phone FROM parties
             WHERE deleted_at IS NULL
               AND (name LIKE ? OR phone LIKE ?)
             ORDER BY name LIMIT 10"
        );
        $stmt->execute([$like, $like]);
    }
    echo json_encode(['ok' => true, 'customers' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
} catch(Exception $e) {
    echo json_encode(['ok' => false, 'customers' => [], 'error' => $e->getMessage()]);
}