<?php
require_once 'db/config.php';

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

$profile_id = $_POST['id'] ?? null;
$kpi_data_json = $_POST['kpi_data'] ?? null;

if (!$profile_id || !$kpi_data_json) {
    echo json_encode(['error' => 'Profile ID or KPI data is missing.']);
    exit;
}

try {
    $kpi_data = json_decode($kpi_data_json, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON format for KPI data.');
    }

    $pdo = db();
    
    // Fetch existing data to merge, preserving the chart data
    $stmt = $pdo->prepare("SELECT kpi_data FROM gtm_profiles WHERE id = ?");
    $stmt->execute([$profile_id]);
    $existing_data_row = $stmt->fetch(PDO::FETCH_ASSOC);
    $existing_data = $existing_data_row ? json_decode($existing_data_row['kpi_data'], true) : [];

    // We only want to update the 'kpis' part, not the chart data
    $existing_data['kpis'] = $kpi_data['kpis'];
    
    $updated_kpi_data_json = json_encode($existing_data);

    $update_stmt = $pdo->prepare("UPDATE gtm_profiles SET kpi_data = ? WHERE id = ?");
    $update_stmt->execute([$updated_kpi_data_json, $profile_id]);

    echo json_encode(['success' => true, 'message' => 'KPIs updated successfully.', 'updated_kpi_data' => $existing_data]);

} catch (Exception $e) {
    error_log('KPI Save Error: ' . $e->getMessage());
    echo json_encode(['error' => 'Error saving KPIs: ' . $e->getMessage()]);
}
