<?php 
declare(strict_types=1);

require_once __DIR__ . '/../core/api.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendJsonResponse(['success' => false, 'message' => 'msg_invalid_method'], 405);
}

// Validar Sesión
$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    sendJsonResponse(['success' => false, 'message' => 'msg_session_expired'], 401);
}

// Validar Permiso (Asumimos dashboard_view o un permiso general de uso)
if (!is_module_active('dashboard') || !can('dashboard_view')) {
    sendJsonResponse(['success' => false, 'message' => 'msg_access_denied'], 403);
}

$data = readJsonInput(); // Usando helper de api.php si existe, o json_decode estándar

if (empty($data['title']) || empty($data['due_date'])) {
    sendJsonResponse(['success' => false, 'message' => 'msg_missing_required_fields'], 400);
}

try {
    global $pdo;

    // Sanitización
    $title = sanitizeData($data['title']);
    $description = sanitizeData($data['description'] ?? '');
    $dueDate = sanitizeData($data['due_date']);
    $priority = sanitizeData($data['priority'] ?? 'Medium');
    $status = sanitizeData($data['status'] ?? 'pending');
    
    $clientId = !empty($data['client_id']) ? (int)$data['client_id'] : null;
    $leadId = !empty($data['lead_id']) ? (int)$data['lead_id'] : null;
    
    // Determinar nombre asociado (Snapshot para la tarea)
    $associatedName = null;
    if ($clientId) {
        $stmtC = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name, company FROM clients WHERE id = ? AND user_id = ?");
        $stmtC->execute([$clientId, $userId]);
        $client = $stmtC->fetch(PDO::FETCH_ASSOC);
        if ($client) {
            $associatedName = trim($client['name']) ?: $client['company'];
        }
    } elseif ($leadId) {
        $stmtL = $pdo->prepare("SELECT CONCAT(first_name, ' ', last_name) as name FROM leads WHERE id = ? AND user_id = ?");
        $stmtL->execute([$leadId, $userId]);
        $lead = $stmtL->fetch(PDO::FETCH_ASSOC);
        if ($lead) {
            $associatedName = trim($lead['name']);
        }
    } else {
        // Fallback si envían texto libre
        if (!empty($data['client_name'])) $associatedName = sanitizeData($data['client_name']);
        elseif (!empty($data['prospect_name'])) $associatedName = sanitizeData($data['prospect_name']);
    }

    $stmt = $pdo->prepare("
        INSERT INTO tasks (user_id, title, description, client_id, lead_id, client_name, due_date, priority, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $userId,
        $title,
        $description,
        $clientId,
        $leadId,
        $associatedName,
        $dueDate,
        $priority,
        $status
    ]);

    $lastId = $pdo->lastInsertId();
    sendJsonResponse(['success' => true, 'message' => 'msg_task_created', 'id' => (int)$lastId]);

} catch (PDOException $e) {
    error_log("DB Error (tasks-create): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_db'], 500);
} catch (Exception $e) {
    error_log("Error (tasks-create): " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'msg_error_internal'], 500);
}
?>