<?php
ob_start();
header('Content-Type: application/json');
ini_set('display_errors', 0);
error_reporting(E_ALL);

$response = ['success' => false];

try {
    require_once '../core/api.php';

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // LECTURA
        $id = filter_var($_GET['id'] ?? 0, FILTER_VALIDATE_INT);
        $type = $_GET['type'] ?? 'lead';
        
        $table = ($type === 'client') ? 'client_notes' : 'lead_notes';
        $col = ($type === 'client') ? 'client_id' : 'lead_id';
        
        $stmt = $pdo->prepare("SELECT content, created_at FROM $table WHERE $col = ? ORDER BY created_at DESC");
        $stmt->execute([$id]);
        $response['notes'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $response['success'] = true;
    } 
    else {
        // ESCRITURA
        $input = json_decode(file_get_contents('php://input'), true);
        $id = filter_var($input['lead_id'] ?? 0, FILTER_VALIDATE_INT); // ID del contacto real
        $type = $input['contact_type'] ?? 'lead';
        $content = trim($input['content'] ?? '');
        $taskDate = !empty($input['next_task_date']) ? $input['next_task_date'] : null;

        if (!$id || !$content) throw new Exception('Faltan datos');

        $pdo->beginTransaction();

        // Insertar Nota (Tablas client_notes o lead_notes)
        $table = ($type === 'client') ? 'client_notes' : 'lead_notes';
        $col = ($type === 'client') ? 'client_id' : 'lead_id';
        
        $stmt = $pdo->prepare("INSERT INTO $table ($col, content, created_at) VALUES (?, ?, NOW())");
        $stmt->execute([$id, $content]);

        // Insertar Tarea (Si aplica - Tabla tasks)
        if ($taskDate) {
            $clientId = ($type === 'client') ? $id : null;
            $leadId = ($type === 'lead') ? $id : null;
            
            $stmtTask = $pdo->prepare("INSERT INTO tasks (lead_id, client_id, title, description, due_date, status, created_at) VALUES (?, ?, 'Seguimiento Cotizaci¨Žn', ?, ?, 'pending', NOW())");
            $stmtTask->execute([$leadId, $clientId, $content, $taskDate]);
        }

        $pdo->commit();
        $response['success'] = true;
    }

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $response['message'] = $e->getMessage();
}

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