<?php
header('Content-Type: application/json');
require 'db_connect.php';

$data = json_decode(file_get_contents("php://input"));
$action = $data->action ?? '';

// --- FUNCIÓN PARA CALCULAR RANGO SEGÚN XP ---
function getRankData($xp) {
    if ($xp < 500) return ["Novato Crafter", "#a16633", "fas fa-leaf"];
    if ($xp < 2000) return ["Maestro Piñatero", "#95a5a6", "fas fa-cut"];
    if ($xp < 5000) return ["Leyenda del Papel", "#f1c40f", "fas fa-crown"];
    return ["Divinidad Espacial", "#3498db", "fas fa-gem"];
}

// --- OBTENER TODA LA INFO DEL PERFIL ---
if ($action === 'get_user_info') {
    $id = $conn->real_escape_string($data->id);

    // 1. Info básica del usuario (incluyendo campos avanzados)
    $sql = "SELECT name, picture_url, custom_pic, cover_pic, theme_color, mood, credits, xp, fb_url, ig_url, tt_url FROM users WHERE google_id = '$id'";
    $res = $conn->query($sql);
    
    if ($res->num_rows === 0) { 
        echo json_encode(["success" => false, "msg" => "Usuario no encontrado"]); 
        exit; 
    }
    
    $user = $res->fetch_assoc();
    $rankInfo = getRankData($user['xp'] ?? 0);

    // 2. Traer saludos principales (los que no son respuestas de otros)
    $sql_g = "SELECT g.*, u.name as sender_name, u.picture_url as sender_pic, u.custom_pic as sender_custom_pic 
              FROM profile_greetings g 
              JOIN users u ON g.sender_user_id = u.google_id 
              WHERE g.target_user_id = '$id' AND g.parent_id IS NULL 
              ORDER BY g.created_at DESC LIMIT 15";
    $res_g = $conn->query($sql_g);
    $greetings = [];

    while($row = $res_g->fetch_assoc()) {
        $gid = $row['id'];
        // Buscar respuestas para este saludo específico
        $sql_rep = "SELECT g.*, u.name as sender_name, u.picture_url as sender_pic, u.custom_pic as sender_custom_pic 
                    FROM profile_greetings g 
                    JOIN users u ON g.sender_user_id = u.google_id 
                    WHERE g.parent_id = $gid ORDER BY g.created_at ASC";
        $res_rep = $conn->query($sql_rep);
        $row['replies'] = [];
        while($rep = $res_rep->fetch_assoc()) {
            $row['replies'][] = $rep;
        }
        $greetings[] = $row;
    }

    // 3. Traer moldes públicos
    $sql_m = "SELECT id, title, image_data, category FROM projects WHERE user_id = '$id' AND visibility = 'public' ORDER BY id DESC LIMIT 6";
    $res_m = $conn->query($sql_m);
    $molds = [];
    while($row = $res_m->fetch_assoc()) { $molds[] = $row; }

    echo json_encode([
        "success" => true,
        "user" => $user, 
        "rank_name" => $rankInfo[0],
        "rank_color" => $rankInfo[1],
        "rank_icon" => $rankInfo[2],
        "greetings" => $greetings,
        "molds" => $molds
    ]);
}

// --- ACTUALIZACIÓN DE PERFIL AVANZADA ---
if ($action === 'update_advanced_profile' || $action === 'update_profile') {
    $uid = $conn->real_escape_string($data->user_id);
    $mood = $conn->real_escape_string($data->mood);
    $color = isset($data->theme_color) ? $conn->real_escape_string($data->theme_color) : '#ff0080';
    $pic = isset($data->image) ? $conn->real_escape_string($data->image) : null;
    $cover = isset($data->cover) ? $conn->real_escape_string($data->cover) : null;
    
    $sql = "UPDATE users SET mood = '$mood', theme_color = '$color'";
    if($pic) $sql .= ", custom_pic = '$pic'";
    if($cover) $sql .= ", cover_pic = '$cover'";
    $sql .= " WHERE google_id = '$uid'";
    
    echo json_encode(["success" => $conn->query($sql)]);
}

// --- ENVIAR SALUDO O RESPUESTA ---
if ($action === 'send_greeting') {
    $target = $conn->real_escape_string($data->target_id);
    $sender = $conn->real_escape_string($data->sender_id);
    $msg = $conn->real_escape_string($data->message);
    // Capturamos el parent_id si es una respuesta, de lo contrario es NULL
    $parent = isset($data->parent_id) ? (int)$data->parent_id : "NULL";

    $sql = "INSERT INTO profile_greetings (target_user_id, sender_user_id, message, parent_id) 
            VALUES ('$target', '$sender', '$msg', $parent)";
    
    if($conn->query($sql)) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "error" => $conn->error]);
    }
}

$conn->close();
?>
