<?php
declare(strict_types=1);

function find_customer_matches(mysqli $conn, string $phone = '', string $plateNumber = '', int $limit = 8): array
{
    ensure_customer_group_column($conn);

    $phoneDigits = normalize_phone($phone);
    $plateNumber = normalize_plate($plateNumber);
    if ($phoneDigits === '' && $plateNumber === '') {
        return array();
    }

    $params = array();
    $types = '';
    $whereParts = array();

    if ($phoneDigits !== '') {
        $whereParts[] = 'cust.normalized_phone = ?';
        $params[] = $phoneDigits;
        $types .= 's';
    }

    if ($plateNumber !== '') {
        $whereParts[] = 'car.plate_number = ?';
        $params[] = $plateNumber;
        $types .= 's';
    }

    $whereSql = '(' . implode(' OR ', $whereParts) . ')';

    $branchCondition = is_logged_in($conn) ? auth_branch_condition($conn, 'ord', $types, $params) : '';
    if ($branchCondition !== '') {
        $whereSql .= ' AND ' . $branchCondition;
    }

    $limit = max(1, min(20, $limit));
    $sql = "
        SELECT
            cust.customer_id,
            cust.name AS customer_name,
            cust.phone,
            cust.customer_group,
            car.car_id,
            car.plate_number,
            car.province,
            car.vehicle_type,
            car.brand,
            car.model,
            car.color,
            COALESCE(MAX(ord.order_date), car.updated_at, cust.updated_at) AS last_seen
        FROM customers cust
        LEFT JOIN cars car ON car.customer_id = cust.customer_id
        LEFT JOIN orders ord ON ord.car_id = car.car_id
        WHERE {$whereSql}
        GROUP BY
            cust.customer_id,
            cust.name,
            cust.phone,
            cust.customer_group,
            car.car_id,
            car.plate_number,
            car.province,
            car.vehicle_type,
            car.brand,
            car.model,
            car.color,
            car.updated_at,
            cust.updated_at
        ORDER BY
            last_seen DESC,
            car.car_id DESC
        LIMIT {$limit}
    ";

    $stmt = db_prepare($conn, $sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
    $matches = array();

    while ($row = $result->fetch_assoc()) {
        $matches[] = array(
            'customerId' => (int) $row['customer_id'],
            'carId' => isset($row['car_id']) ? (int) $row['car_id'] : 0,
            'customerName' => (string) ($row['customer_name'] ?? ''),
            'phone' => (string) ($row['phone'] ?? ''),
            'customerGroup' => customer_group_key((string) ($row['customer_group'] ?? 'member')),
            'plateNumber' => (string) ($row['plate_number'] ?? ''),
            'province' => (string) ($row['province'] ?? ''),
            'vehicleType' => (string) ($row['vehicle_type'] ?? ''),
            'brand' => (string) ($row['brand'] ?? ''),
            'model' => (string) ($row['model'] ?? ''),
            'color' => (string) ($row['color'] ?? ''),
        );
    }

    $stmt->close();

    return $matches;
}
