<?php
/**
 * ajax/cigna_rates_match.php
 * Receives: JSON { provider_id: int, names: string[] }
 * Returns:  JSON { success: true, matches: { "Service Name": { pricing_id, service_name, current_rate, match_type } } }
 */
ob_start();
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';
ob_end_clean();

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

// Auth
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthenticated']); exit();
}
$allowed = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed)) {
    echo json_encode(['success' => false, 'message' => 'Forbidden']); exit();
}

// Input
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || empty($input['names']) || !isset($input['provider_id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']); exit();
}

$provider_id = (int)$input['provider_id'];
$names       = array_map('trim', (array)$input['names']);
$names       = array_filter($names); // remove empty

if (!$names) {
    echo json_encode(['success' => false, 'message' => 'No service names provided']); exit();
}

// ─── Load all active services with their current rate for this provider ───
$all_services = [];
$stmt = $conn->prepare(
    "SELECT sp.pricing_id, sp.service_name,
            COALESCE(isr.agreed_rate, sp.base_price) AS current_rate
     FROM   service_pricing sp
     LEFT   JOIN insurance_service_rates isr
                ON isr.pricing_id  = sp.pricing_id
               AND isr.provider_id = ?
     WHERE  sp.is_active = 1"
);
$stmt->bind_param('i', $provider_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $all_services[] = $row;
}
$stmt->close();

// Build a normalised name → service map for fast exact lookup
$exact_map = [];
foreach ($all_services as $svc) {
    $key = normalise($svc['service_name']);
    $exact_map[$key] = $svc;
}

// ─── Match each incoming name ─────────────────────────────────────────────
$matches = [];

foreach ($names as $name) {
    $norm = normalise($name);

    // 1. Exact (after normalisation)
    if (isset($exact_map[$norm])) {
        $svc = $exact_map[$norm];
        $matches[$name] = [
            'pricing_id'   => (int)$svc['pricing_id'],
            'service_name' => $svc['service_name'],
            'current_rate' => (float)$svc['current_rate'],
            'match_type'   => 'exact',
        ];
        continue;
    }

    // 2. Fuzzy — find the best PHP similar_text() score among all services
    $best_score   = 0;
    $best_service = null;
    foreach ($all_services as $svc) {
        similar_text($norm, normalise($svc['service_name']), $pct);
        if ($pct > $best_score) {
            $best_score   = $pct;
            $best_service = $svc;
        }
    }

    // Accept fuzzy match only if similarity ≥ 65%
    if ($best_score >= 65 && $best_service) {
        $matches[$name] = [
            'pricing_id'   => (int)$best_service['pricing_id'],
            'service_name' => $best_service['service_name'],
            'current_rate' => (float)$best_service['current_rate'],
            'match_type'   => 'fuzzy',
        ];
    }
    // else: no entry → front-end treats as 'none'
}

echo json_encode(['success' => true, 'matches' => $matches]);

// ─── helpers ─────────────────────────────────────────────────────────────────
/**
 * Normalise a service name for comparison:
 *   lowercase, collapse spaces, strip punctuation artefacts.
 */
function normalise($s) {
    $s = strtolower(trim($s));
    // replace common punctuation variations
    $s = str_replace(['-', '–', '—', '/', '\\', ',', ';', ':', '.', '\'', '"', '(', ')', '{', '}', '&'], ' ', $s);
    // collapse multiple spaces
    $s = preg_replace('/\s+/', ' ', $s);
    return $s;
}