<?php
header('Content-Type: application/json; charset=utf-8');
require_once '../includes/db.php';
require_once '../includes/auth_middleware.php';

// Must have permission to view customers or add/edit forms
$user = $_SESSION['user'];
$canViewCust = isset($user['permissions']['customers']['view']) && $user['permissions']['customers']['view'] === true;
$canAddForm = isset($user['permissions']['forms']['add']) && $user['permissions']['forms']['add'] === true;
$canEditForm = isset($user['permissions']['forms']['edit']) && $user['permissions']['forms']['edit'] === true;
if (!$canViewCust && !$canAddForm && !$canEditForm) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['status' => 'error', 'message' => 'عذراً، لا تمتلك الصلاحية الكافية للبحث عن العملاء.']);
    exit;
}

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

if (strlen($q) < 1) {
    echo json_encode(["status" => "success", "data" => []]);
    exit;
}

// Search for active customers whose name contains the query string
$like = '%' . $q . '%';
$stmt = $conn->prepare("SELECT id, name, phone FROM customers WHERE name LIKE ? AND status = 'active' ORDER BY name ASC LIMIT 10");
$stmt->bind_param("s", $like);
$stmt->execute();
$result = $stmt->get_result();

$customers = [];
while ($row = $result->fetch_assoc()) {
    $customers[] = [
        "id"    => $row['id'],
        "name"  => $row['name'],
        "phone" => $row['phone'] ?? ''
    ];
}
$stmt->close();

echo json_encode(["status" => "success", "data" => $customers]);
?>
