<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once 'db/config.php';

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

$response = ['success' => false, 'message' => 'An unknown error occurred.'];

try {
    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid JSON received. ' . json_last_error_msg());
    }

    if (isset($data['profile_id']) && isset($data['diagram_text'])) {
        $profileId = $data['profile_id'];
        $diagramText = $data['diagram_text'];

        $pdo = db();

        $stmt = $pdo->prepare("UPDATE gtm_profiles SET diagram_mermaid_text = :diagram_text WHERE id = :profile_id");

        $stmt->bindValue(':diagram_text', $diagramText, PDO::PARAM_STR);
        $stmt->bindValue(':profile_id', $profileId, PDO::PARAM_INT);

        if ($stmt->execute()) {
            $response['success'] = true;
            $response['message'] = 'Diagram saved successfully.';
        } else {
            $errorInfo = $stmt->errorInfo();
            $response['message'] = 'Failed to save diagram. DB Error: ' . ($errorInfo[2] ?? 'Unknown');
        }
    } else {
        $response['message'] = 'Invalid input.';
    }
} catch (Exception $e) {
    $response['message'] = 'Error: ' . $e->getMessage();
}

echo json_encode($response);