<?php
/**
 * PRODIGY NOTES Item #5: Update service pricing with history tracking
 */
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$user_id = $_SESSION['user_id'];

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

$pricing_id = isset($data['pricing_id']) ? intval($data['pricing_id']) : 0;
$old_base_price = isset($data['old_base_price']) ? floatval($data['old_base_price']) : 0;
$new_base_price = isset($data['new_base_price']) ? floatval($data['new_base_price']) : 0;
$old_insurance_price = isset($data['old_insurance_price']) ? floatval($data['old_insurance_price']) : null;
$new_insurance_price = isset($data['new_insurance_price']) ? floatval($data['new_insurance_price']) : null;
$change_reason = isset($data['change_reason']) ? trim($data['change_reason']) : '';

if (!$pricing_id || !$new_base_price || !$change_reason) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Get current service info
$sql = "SELECT service_name, service_type, base_price, insurance_price FROM service_pricing WHERE pricing_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $pricing_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Service not found']);
    exit();
}

$service = $result->fetch_assoc();
$service_name = $service['service_name'];
$service_type = $service['service_type'];
$current_base_price = floatval($service['base_price']);
$current_insurance_price = $service['insurance_price'] ? floatval($service['insurance_price']) : null;

mysqli_begin_transaction($conn);

try {
    // Update service pricing
    $update_sql = "UPDATE service_pricing
                   SET base_price = ?,
                       insurance_price = ?,
                       updated_at = NOW()
                   WHERE pricing_id = ?";

    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ddi", $new_base_price, $new_insurance_price, $pricing_id);

    if (!$stmt->execute()) {
        throw new Exception("Failed to update service pricing");
    }

    // Record price change in history
    $history_sql = "INSERT INTO service_pricing_history
                    (pricing_id, service_name, service_type,
                     old_base_price, new_base_price,
                     old_insurance_price, new_insurance_price,
                     change_reason, changed_by, changed_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

    $stmt = $conn->prepare($history_sql);
    $stmt->bind_param("issddddsi",
        $pricing_id, $service_name, $service_type,
        $current_base_price, $new_base_price,
        $current_insurance_price, $new_insurance_price,
        $change_reason, $user_id
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to record price history");
    }

    mysqli_commit($conn);

    echo json_encode([
        'success' => true,
        'message' => 'Service price updated successfully'
    ]);

} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

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