<?php
/**
 * Módulo Leads - Crear Nuevo Lead
 */

// Identificar módulo actual para el sidebar
$current_module = 'leads';

if (!isLoggedIn()) {
    header('Location: ' . get_base_path() . '/index.php?module=auth&action=login');
    exit;
}

$db = getDB();
$error = '';
$success = '';

// Obtener escritorios y usuarios para los selects
$desks = $db->select("SELECT id, name FROM desks WHERE status = 'active' ORDER BY name");
$users = $db->select("SELECT id, username, first_name, last_name FROM users WHERE status = 'active' ORDER BY first_name, last_name");

// Procesar formulario
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $city = trim($_POST['city'] ?? '');
    $company = trim($_POST['company'] ?? '');
    $position = trim($_POST['position'] ?? '');
    $source = trim($_POST['source'] ?? '');
    $status = $_POST['status'] ?? 'new';
    $priority = $_POST['priority'] ?? 'medium';
    $value = floatval($_POST['value'] ?? 0);
    $assigned_to = !empty($_POST['assigned_to']) ? intval($_POST['assigned_to']) : null;
    $desk_id = !empty($_POST['desk_id']) ? intval($_POST['desk_id']) : null;
    $notes = trim($_POST['notes'] ?? '');
    
    // Validaciones
    if (empty($first_name) || empty($last_name)) {
        $error = 'El nombre y apellido son obligatorios';
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'El email no tiene un formato válido';
    } else {
        // Verificar si el email ya existe
        if (!empty($email)) {
            $existing = $db->selectOne("SELECT id FROM leads WHERE email = ?", [$email]);
            if ($existing) {
                $error = 'Ya existe un lead con este email';
            }
        }
        
        if (empty($error)) {
            // Validar estado según el desk seleccionado
            if (empty($desk_id)) {
                // Si no hay desk, no se muestran estados; forzar estado por defecto
                $status = 'new';
            } else {
                $allowedRows = $db->select("SELECT status FROM desk_allowed_statuses WHERE desk_id = ?", [$desk_id]);
                $allowed = array_map(function($r){ return $r['status']; }, $allowedRows ?: []);
                if (empty($allowed) || !in_array($status, $allowed, true)) {
                    $error = 'El estado seleccionado no está permitido para el desk elegido';
                }
            }
        }

        if (empty($error)) {
            // Insertar lead (mapear 'position' del formulario a columna real 'job_title')
            $result = $db->execute(
                "INSERT INTO leads (first_name, last_name, email, phone, country, city, company, job_title, source, status, priority, assigned_to, desk_id, notes, created_at) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())",
                [$first_name, $last_name, $email, $phone, $country, $city, $company, $position, $source, $status, $priority, $assigned_to, $desk_id, $notes]
            );
            
            if ($result) {
                $lead_id = $db->lastInsertId();
                
                // Registrar actividad
                $db->execute(
                    "INSERT INTO lead_activities (lead_id, created_by, type, subject, description, status, created_at) 
                     VALUES (?, ?, 'note', 'Lead creado', 'Lead creado en el sistema', 'completed', NOW())",
                    [$lead_id, $_SESSION['user_id']]
                );
                
                $success = 'Lead creado exitosamente';
                
                // Redirigir después de 2 segundos
                header("refresh:2;url=?module=leads&action=view&id=$lead_id");
            } else {
                $error = 'Error al crear el lead';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nuevo Lead - <?php echo APP_NAME; ?></title>
    <link rel="stylesheet" href="/test/simple_crm/public/style.css">
</head>
<body>
    <?php include BASE_PATH . '/modules/shared/header.php'; ?>
    
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h1 class="card-title">Crear Nuevo Lead</h1>
                <a href="?module=leads" class="btn btn-warning">Volver a Leads</a>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>
            
            <form method="POST" id="leadForm">
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="first_name">Nombre *</label>
                            <input 
                                type="text" 
                                id="first_name" 
                                name="first_name" 
                                class="form-control" 
                                required
                                value="<?php echo htmlspecialchars($_POST['first_name'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="last_name">Apellido *</label>
                            <input 
                                type="text" 
                                id="last_name" 
                                name="last_name" 
                                class="form-control" 
                                required
                                value="<?php echo htmlspecialchars($_POST['last_name'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="email">Email</label>
                            <input 
                                type="email" 
                                id="email" 
                                name="email" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="phone">Teléfono</label>
                            <input 
                                type="tel" 
                                id="phone" 
                                name="phone" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="country">País</label>
                            <input 
                                type="text" 
                                id="country" 
                                name="country" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['country'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="city">Ciudad</label>
                            <input 
                                type="text" 
                                id="city" 
                                name="city" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['city'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="company">Empresa</label>
                            <input 
                                type="text" 
                                id="company" 
                                name="company" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['company'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="position">Cargo</label>
                            <input 
                                type="text" 
                                id="position" 
                                name="position" 
                                class="form-control"
                                value="<?php echo htmlspecialchars($_POST['position'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="source">Fuente</label>
                            <input 
                                type="text" 
                                id="source" 
                                name="source" 
                                class="form-control"
                                placeholder="Ej: Web, Referido, Llamada..."
                                value="<?php echo htmlspecialchars($_POST['source'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="value">Valor Estimado</label>
                            <input 
                                type="number" 
                                id="value" 
                                name="value" 
                                class="form-control"
                                step="0.01"
                                min="0"
                                value="<?php echo htmlspecialchars($_POST['value'] ?? ''); ?>"
                            >
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="status">Estado</label>
                            <select id="status" name="status" class="form-control" disabled>
                                <option value="">-- Selecciona un desk primero --</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="priority">Prioridad</label>
                            <select id="priority" name="priority" class="form-control">
                                <option value="low" <?php echo ($_POST['priority'] ?? '') === 'low' ? 'selected' : ''; ?>>Baja</option>
                                <option value="medium" <?php echo ($_POST['priority'] ?? 'medium') === 'medium' ? 'selected' : ''; ?>>Media</option>
                                <option value="high" <?php echo ($_POST['priority'] ?? '') === 'high' ? 'selected' : ''; ?>>Alta</option>
                                <option value="urgent" <?php echo ($_POST['priority'] ?? '') === 'urgent' ? 'selected' : ''; ?>>Urgente</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="desk_id">Escritorio</label>
                            <select id="desk_id" name="desk_id" class="form-control">
                                <option value="">Sin asignar</option>
                                <?php foreach ($desks as $desk): ?>
                                    <option value="<?php echo $desk['id']; ?>" 
                                            <?php echo ($_POST['desk_id'] ?? '') == $desk['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($desk['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="form-col">
                        <div class="form-group">
                            <label class="form-label" for="assigned_to">Asignado a</label>
                            <select id="assigned_to" name="assigned_to" class="form-control">
                                <option value="">Sin asignar</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" 
                                            <?php echo ($_POST['assigned_to'] ?? '') == $user['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name'] . ' (' . $user['username'] . ')'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="notes">Notas</label>
                    <textarea 
                        id="notes" 
                        name="notes" 
                        class="form-control" 
                        rows="4"
                        placeholder="Información adicional sobre el lead..."
                    ><?php echo htmlspecialchars($_POST['notes'] ?? ''); ?></textarea>
                </div>
                
                <div class="d-flex gap-1">
                    <button type="submit" class="btn btn-success">Crear Lead</button>
                    <a href="?module=leads" class="btn btn-warning">Cancelar</a>
                </div>
            </form>
        </div>
    </div>
    
    <script src="/public/script.js"></script>
    <script>
    (function(){
        const deskSel = document.getElementById('desk_id');
        const statusSel = document.getElementById('status');
        async function loadStatuses(deskId){
            statusSel.innerHTML = '<option value="">-- Selecciona estado del desk --</option>';
            if (!deskId) { statusSel.disabled = true; return; }
            try {
                const resp = await fetch(`/modules/leads/get_desk_statuses.php?desk_id=${encodeURIComponent(deskId)}`);
                const data = await resp.json();
                if (data.success && Array.isArray(data.statuses)) {
                    statusSel.innerHTML = '';
                    data.statuses.forEach(s=>{
                        const opt = document.createElement('option');
                        opt.value = s; opt.textContent = String(s).replace('_',' ');
                        statusSel.appendChild(opt);
                    });
                    statusSel.disabled = data.statuses.length === 0;
                    if (!data.statuses.length) {
                        const opt = document.createElement('option');
                        opt.value = '';
                        opt.textContent = '-- Sin estados configurados en este desk --';
                        statusSel.appendChild(opt);
                    }
                } else {
                    statusSel.disabled = true;
                }
            } catch (e) { statusSel.disabled = true; }
        }
        deskSel.addEventListener('change', function(){ loadStatuses(deskSel.value); });
        // Inicializar si existe valor precargado
        if (deskSel.value) { loadStatuses(deskSel.value); }
    })();
    </script>
</body>
</html>
// Definir BASE_PATH si no está definido y cargar helpers para rutas
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/modules/shared/helpers.php';