<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en tasks-create.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }

    if (empty($data['title']) || empty($data['due_date'])) {
        throw new Exception('TITULO Y FECHA REQUERIDOS');
    }

    $title = filter_var(trim($data['title']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $description = filter_var(trim($data['description'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $dueDate = filter_var($data['due_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $priority = filter_var($data['priority'] ?? 'Media', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $status = filter_var($data['status'] ?? 'pending', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    $clientId = null;
    $leadId = null;
    $associatedName = null;

    if (isset($data['client_id']) && filter_var($data['client_id'], FILTER_VALIDATE_INT)) {
        $clientId = (int)$data['client_id'];
        $associatedName = filter_var(trim($data['client_name'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    }
    else if (isset($data['lead_id']) && filter_var($data['lead_id'], FILTER_VALIDATE_INT)) {
        $leadId = (int)$data['lead_id'];
        $associatedName = filter_var(trim($data['prospect_name'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    }
    else if (!empty(trim($data['client_name'] ?? ''))) {
        $associatedName = filter_var(trim($data['client_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    }
    else if (!empty(trim($data['prospect_name'] ?? ''))) {
        $associatedName = filter_var(trim($data['prospect_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    }

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

    $lastId = $pdo->lastInsertId();
    $response = ['success' => true, 'message' => 'TAREA CREADA', 'id' => (int)$lastId];

} catch (PDOException $e) {
    error_log("PDO Error en tasks-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en tasks-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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