<?php
// /IAMarketing/api-db/project-proposals-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' => 'Error de conexión a la base de datos.']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$business_id = 1; // Asumiendo business_info_id = 1
$max_proposals = 3;

if (isset($data['proposal_name']) && isset($data['proposal_spanish']) && isset($data['proposal_english'])) {
    
    $proposal_name = trim($data['proposal_name']);
    $proposal_spanish = trim($data['proposal_spanish']);
    $proposal_english = trim($data['proposal_english']);

    if (empty($proposal_name)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'El nombre de la propuesta no puede estar vacío.']);
        exit;
    }

    try {
        // 1. Contar cuántas propuestas existen para este business_id
        $count_sql = "SELECT COUNT(id) FROM ia_project_proposals_results WHERE business_info_id = ?";
        $count_stmt = $pdo->prepare($count_sql);
        $count_stmt->execute([$business_id]);
        $current_count = $count_stmt->fetchColumn();
        
        if ($current_count >= $max_proposals) {
            http_response_code(409); // Conflicto
            echo json_encode(['success' => false, 'message' => 'Límite alcanzado. Solo puedes guardar un máximo de ' . $max_proposals . ' propuestas.']);
            exit;
        }
        
        // 2. Insertar el nuevo registro
        $sql = "INSERT INTO ia_project_proposals_results (business_info_id, proposal_name, proposal_spanish, proposal_english) VALUES (?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$business_id, $proposal_name, $proposal_spanish, $proposal_english]);
        
        echo json_encode(['success' => true, 'message' => 'Propuesta guardada exitosamente.']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error de base de datos al crear la propuesta: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Datos incompletos. Se requiere nombre, propuesta en español e inglés.']);
}
?>