<?php
// /IAMarketing/api-db/ia-value-propositions-create.php
ob_start();
require_once __DIR__ . '/../client-information.php'; 
ob_clean();

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

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection error.']);
    exit;
}

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

if (isset($data['value_proposition'])) {
    $business_id = 1; // Assuming business_info_id = 1
    $vp_content = $data['value_proposition'];

    try {
        // 1. Check if a record already exists for business_info_id = 1
        $check_sql = "SELECT id FROM ia_value_propositions WHERE business_info_id = ?";
        $check_stmt = $pdo->prepare($check_sql);
        $check_stmt->execute([$business_id]);
        
        if ($check_stmt->fetch(PDO::FETCH_ASSOC)) {
            http_response_code(409); // Conflict
            echo json_encode(['success' => false, 'message' => 'A value proposition already exists. Please use the update or delete function.']);
            exit;
        }
        
        // 2. Insert the new record into the dedicated table
        $sql = "INSERT INTO ia_value_propositions (business_info_id, value_proposition) VALUES (?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$business_id, $vp_content]);
        
        echo json_encode(['success' => true, 'message' => 'Value proposition created successfully.']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error while creating VP: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Value proposition content not received.']);
}
?>