<?php

session_start();
header('Content-Type: application/json');
include '../../config/db.php';

if(!isset($_SESSION['user_id'])){
    echo json_encode(['success'=>false,'error'=>'No autenticado']);
    exit;
}

$user_id = intval($_SESSION['user_id']);
$lead_id = intval($_POST['lead_id'] ?? 0);
$note    = trim($_POST['note']      ?? '');

if(!$lead_id || empty($note)){
    echo json_encode(['success'=>false,'error'=>'Datos incompletos']);
    exit;
}

$note_escaped = mysqli_real_escape_string($conn, $note);

// Guardar en lead_notes (crear tabla si no existe)
$conn->query("
CREATE TABLE IF NOT EXISTS lead_notes (
    id         INT(11)      NOT NULL AUTO_INCREMENT,
    lead_id    INT(11)      NOT NULL,
    user_id    INT(11)      NOT NULL,
    note       TEXT         NOT NULL,
    created_at TIMESTAMP    DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$conn->query("
INSERT INTO lead_notes (lead_id, user_id, note, created_at)
VALUES ('$lead_id', '$user_id', '$note_escaped', NOW())
");

// También registrar en activity_logs
$desc = "Nota añadida al lead #$lead_id";
$conn->query("
INSERT INTO activity_logs (user_id, action_type, description, created_at)
VALUES ('$user_id', 'note_added', '".mysqli_real_escape_string($conn,$desc)."', NOW())
");

echo json_encode(['success'=>true]);