<?php
/**
 * ajax/cigna_rates_save.php
 * Receives: JSON { rates: [{ pricing_id, provider_id, new_rate }, …] }
 * Returns:  JSON { success, inserted, updated, provider_name, message? }
 */
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['rates']) || !is_array($input['rates'])) {
    echo json_encode(['success' => false, 'message' => 'No rates provided']); exit();
}

$rates = $input['rates'];

// Basic validation
foreach ($rates as $r) {
    if (empty($r['pricing_id']) || empty($r['provider_id']) || !isset($r['new_rate'])) {
        echo json_encode(['success' => false, 'message' => 'Malformed rate entry in payload']); exit();
    }
}

// Look up provider name for response
$provider_id   = (int)$rates[0]['provider_id'];
$provider_name = 'Selected Provider';
$pres = $conn->prepare("SELECT provider_name FROM insurance_providers WHERE provider_id = ? LIMIT 1");
$pres->bind_param('i', $provider_id);
$pres->execute();
$pres->bind_result($provider_name_val);
if ($pres->fetch()) $provider_name = $provider_name_val;
$pres->close();

// ─── Upsert ───────────────────────────────────────────────────────────────
/**
 * insurance_service_rates has UNIQUE KEY uq_provider_service (provider_id, pricing_id)
 * So INSERT … ON DUPLICATE KEY UPDATE is safe and atomic.
 */
$stmt = $conn->prepare(
    "INSERT INTO insurance_service_rates (provider_id, pricing_id, agreed_rate, is_active)
     VALUES (?, ?, ?, 1)
     ON DUPLICATE KEY UPDATE agreed_rate = VALUES(agreed_rate), is_active = 1"
);

$inserted = 0;
$updated  = 0;
$errors   = [];

$conn->begin_transaction();

try {
    foreach ($rates as $r) {
        $pid      = (int)$r['pricing_id'];
        $provid   = (int)$r['provider_id'];
        $new_rate = round((float)$r['new_rate'], 2);

        if ($pid <= 0 || $provid <= 0 || $new_rate < 0) continue;

        // Check if a row already exists to distinguish insert vs update in the summary
        $exists = false;
        $chk = $conn->prepare("SELECT rate_id FROM insurance_service_rates WHERE provider_id = ? AND pricing_id = ? LIMIT 1");
        $chk->bind_param('ii', $provid, $pid);
        $chk->execute();
        $chk->store_result();
        $exists = $chk->num_rows > 0;
        $chk->close();

        $stmt->bind_param('iid', $provid, $pid, $new_rate);
        if (!$stmt->execute()) {
            $errors[] = "pricing_id=$pid: " . $stmt->error;
            continue;
        }

        if ($exists) {
            $updated++;
        } else {
            $inserted++;
        }
    }

    if (!empty($errors)) {
        $conn->rollback();
        $stmt->close();
        echo json_encode(['success' => false, 'message' => 'Errors during save: ' . implode('; ', array_slice($errors, 0, 3))]); exit();
    }

    $conn->commit();
} catch (Exception $e) {
    $conn->rollback();
    $stmt->close();
    echo json_encode(['success' => false, 'message' => 'Transaction failed: ' . $e->getMessage()]); exit();
}

$stmt->close();

echo json_encode([
    'success'       => true,
    'inserted'      => $inserted,
    'updated'       => $updated,
    'provider_name' => $provider_name,
]);