<?php
require_once __DIR__ . '/../db/config.php';

header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);
$username = $input['username'] ?? '';
$song_title = $input['song_title'] ?? '';

if (empty($username) || empty($song_title)) {
    echo json_encode(['error' => 'Faltan datos']);
    exit;
}

try {
    $pdo = db();
    
    // 1. Update/Insert into song_likes
    $stmt = $pdo->prepare("INSERT INTO song_likes (song_title, likes_count) VALUES (?, 1) ON DUPLICATE KEY UPDATE likes_count = likes_count + 1");
    $stmt->execute([$song_title]);

    // 2. Update/Insert into user_likes
    $stmtUser = $pdo->prepare("INSERT INTO user_likes (username, total_likes) VALUES (?, 1) ON DUPLICATE KEY UPDATE total_likes = total_likes + 1");
    $stmtUser->execute([$username]);
    
    // Award points for like
    require_once __DIR__ . '/../includes/points_helper.php';
    awardPoints($username, 10);
    
    // 3. Post to chat
    $message = "¡Le dio un ❤️ a la canción: $song_title!";
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
    $ip = explode(',', $ip)[0];
    $stmtChat = $pdo->prepare("INSERT INTO messages (username, ip_address, message) VALUES (?, ?, ?)");
    $stmtChat->execute([$username, $ip, $message]);
    
    // 3. Get total likes for this song
    $stmtCount = $pdo->prepare("SELECT likes_count FROM song_likes WHERE song_title = ?");
    $stmtCount->execute([$song_title]);
    $count = $stmtCount->fetchColumn();

    echo json_encode(['success' => true, 'likes_count' => $count]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
