<?php
// Endpoint: Crear Lead desde JSON (asistente guiado)
session_start();
define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

header('Content-Type: application/json; charset=utf-8');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

// Verificar permiso: leads.create
$db = getDB();
$pdo = $db->getConnection();
if (!function_exists('userHasPermissionByName')) {
    function userHasPermissionByName($pdo, $permName, $userId) {
        if (empty($userId)) return false;
        $stmt = $pdo->prepare("SELECT 1 FROM role_permissions rp INNER JOIN permissions p ON rp.permission_id = p.id INNER JOIN user_roles ur ON rp.role_id = ur.role_id WHERE ur.user_id = ? AND p.name = ? LIMIT 1");
        $stmt->execute([$userId, $permName]);
        return (bool)$stmt->fetchColumn();
    }
}
$current_user_id = (int)($_SESSION['user_id'] ?? 0);
if (!userHasPermissionByName($pdo, 'leads.create', $current_user_id)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Permiso requerido: leads.create']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

$raw = file_get_contents('php://input');
$payload = json_decode($raw, true);
if (!is_array($payload)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Body JSON inválido']);
    exit;
}

function sanitizeText($v) { return trim((string)$v); }

$first_name = sanitizeText($payload['first_name'] ?? '');
$last_name = sanitizeText($payload['last_name'] ?? '');
$email = sanitizeText($payload['email'] ?? '');
$phone = sanitizeText($payload['phone'] ?? '');
$country = sanitizeText($payload['country'] ?? '');
$status = sanitizeText($payload['status'] ?? 'new');
$desk_id = !empty($payload['desk_id']) ? intval($payload['desk_id']) : null;
$assigned_to = !empty($payload['assigned_to']) ? intval($payload['assigned_to']) : null;
$experience = sanitizeText($payload['experience'] ?? 'none');
$investment_amount = isset($payload['investment_amount']) ? floatval($payload['investment_amount']) : 0.0;

if (empty($email)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'El email es obligatorio']);
    exit;
}

$allowed_statuses = ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'];
if (!in_array($status, $allowed_statuses)) $status = 'new';

$allowed_experience = ['none','beginner','intermediate','advanced','professional'];
if (!in_array($experience, $allowed_experience)) $experience = 'none';


// ¿Existe ya un lead con este email?
$existing = $db->selectOne("SELECT id FROM leads WHERE email = ? LIMIT 1", [$email]);

if ($existing) {
    // Actualizar datos básicos si existe
    $db->execute(
        "UPDATE leads SET first_name = ?, last_name = ?, phone = ?, country = ?, status = ?, desk_id = ?, assigned_to = ?, trading_experience = ?, investment_amount = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
        [
            $first_name,
            $last_name,
            $phone,
            $country,
            $status,
            $desk_id,
            $assigned_to,
            $experience,
            $investment_amount,
            $existing['id']
        ]
    );
    echo json_encode(['success' => true, 'action' => 'updated', 'lead_id' => $existing['id']]);
    exit;
}

// Insertar nuevo lead
$db->execute(
    "INSERT INTO leads (first_name, last_name, email, phone, country, status, desk_id, assigned_to, trading_experience, investment_amount) VALUES (?,?,?,?,?,?,?,?,?,?)",
    [
        $first_name,
        $last_name,
        $email,
        $phone,
        $country,
        $status,
        $desk_id,
        $assigned_to,
        $experience,
        $investment_amount
    ]
);

$lead_id = $db->lastInsertId();
echo json_encode(['success' => true, 'action' => 'inserted', 'lead_id' => $lead_id]);
?>