<?php
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

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

// Auth guard
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit();
}

// Inputs
$pricing_id  = isset($_POST['pricing_id'])  ? (int)$_POST['pricing_id']  : 0;
$provider_id = isset($_POST['provider_id']) ? (int)$_POST['provider_id'] : 0;
$rate_id     = isset($_POST['rate_id'])     ? (int)$_POST['rate_id']     : 0;
$agreed_rate = isset($_POST['agreed_rate']) ? round((float)$_POST['agreed_rate'], 2) : 0.00;

if (!$pricing_id || !$provider_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit();
}
if ($agreed_rate < 0) {
    echo json_encode(['success' => false, 'message' => 'Rate cannot be negative']);
    exit();
}

// Validate pricing_id and provider_id exist
$chk = $conn->prepare("SELECT 1 FROM service_pricing WHERE pricing_id=? AND is_active=1 LIMIT 1");
$chk->bind_param('i', $pricing_id);
$chk->execute();
if (!$chk->get_result()->fetch_row()) {
    echo json_encode(['success' => false, 'message' => 'Service not found']);
    exit();
}

$chk2 = $conn->prepare("SELECT 1 FROM insurance_providers WHERE provider_id=? AND is_active=1 LIMIT 1");
$chk2->bind_param('i', $provider_id);
$chk2->execute();
if (!$chk2->get_result()->fetch_row()) {
    echo json_encode(['success' => false, 'message' => 'Provider not found']);
    exit();
}

// UPSERT — use INSERT … ON DUPLICATE KEY UPDATE so it works whether or not
// the row was pre-seeded by the migration script.
$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),
        updated_at  = current_timestamp()"
);
$stmt->bind_param('iid', $provider_id, $pricing_id, $agreed_rate);

if ($stmt->execute()) {
    $new_id = $conn->insert_id ?: $rate_id; // insert_id is 0 on UPDATE
    echo json_encode([
        'success'  => true,
        'message'  => 'Rate saved successfully',
        'rate_id'  => $new_id,
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'DB error: ' . $conn->error]);
}

$stmt->close();
$conn->close();