<?php
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $data = json_decode(file_get_contents('php://input'), true);
    $lead_id = isset($data['lead_id']) ? filter_var($data['lead_id'], FILTER_VALIDATE_INT) : 0;
    $content = isset($data['content']) ? filter_var(trim($data['content']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : '';
    $next_task_date = isset($data['next_task_date']) && !empty($data['next_task_date']) ? filter_var($data['next_task_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

    if ($lead_id === false || $lead_id === 0) {
        throw new Exception('ID PROSPECTO INVALIDO');
    }

    $pdo->beginTransaction();
    $new_note = null;

    if (!empty($content)) {
        $stmt_note = $pdo->prepare("INSERT INTO lead_notes (lead_id, content) VALUES (?, ?)");
        $stmt_note->execute([$lead_id, $content]);
        $new_note_id = $pdo->lastInsertId();
        
        $stmt_get_note = $pdo->prepare("SELECT id, content, created_at FROM lead_notes WHERE id = ?");
        $stmt_get_note->execute([$new_note_id]);
        $new_note = $stmt_get_note->fetch(PDO::FETCH_ASSOC);
    }

    $stmt_lead = $pdo->prepare("UPDATE leads SET next_task_date = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
    $stmt_lead->execute([$next_task_date, $lead_id]);

    $pdo->commit();
    
    $response = [
        'success' => true, 
        'message' => 'SEGUIMIENTO GUARDADO',
        'new_note' => $new_note, 
        'next_task_date' => $next_task_date
    ];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error PDO en quotes-add-note-task.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("General Error en quotes-add-note-task.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
?>