<?php
/**
 * PRODIGY NOTES Item #5: Get price change history for a service
 */
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

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

$pricing_id = isset($_GET['pricing_id']) ? intval($_GET['pricing_id']) : 0;

if (!$pricing_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid pricing ID']);
    exit();
}

// Get service name
$svc_sql = "SELECT service_name FROM service_pricing WHERE pricing_id = ?";
$stmt = $conn->prepare($svc_sql);
$stmt->bind_param("i", $pricing_id);
$stmt->execute();
$svc_result = $stmt->get_result();

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

$service_name = $svc_result->fetch_assoc()['service_name'];

// Get price history
$history_sql = "SELECT h.*,
                       u.full_name as changed_by_name
                FROM service_pricing_history h
                LEFT JOIN users u ON h.changed_by = u.user_id
                WHERE h.pricing_id = ?
                ORDER BY h.changed_at DESC";

$stmt = $conn->prepare($history_sql);
$stmt->bind_param("i", $pricing_id);
$stmt->execute();
$result = $stmt->get_result();

$history = [];
while ($row = $result->fetch_assoc()) {
    $history[] = [
        'history_id' => $row['history_id'],
        'old_base_price' => $row['old_base_price'],
        'new_base_price' => $row['new_base_price'],
        'old_insurance_price' => $row['old_insurance_price'],
        'new_insurance_price' => $row['new_insurance_price'],
        'change_reason' => $row['change_reason'],
        'changed_by_name' => $row['changed_by_name'] ?? 'Unknown',
        'changed_at' => date('Y-m-d H:i:s', strtotime($row['changed_at']))
    ];
}

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

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