prepare("SELECT message FROM messages WHERE type = 'image' AND created_at < DATE_SUB(NOW(), INTERVAL 6 HOUR)"); $oldImages->execute(); $filesToDelete = $oldImages->fetchAll(PDO::FETCH_ASSOC); foreach ($filesToDelete as $fileRow) { $filePath = __DIR__ . '/../' . $fileRow['message']; if (file_exists($filePath) && is_file($filePath)) { unlink($filePath); } } db()->query("DELETE FROM messages WHERE created_at < DATE_SUB(NOW(), INTERVAL 6 HOUR)"); $stmt = db()->prepare("SELECT m.*, ul.custom_color FROM messages m LEFT JOIN user_likes ul ON m.username = ul.username ORDER BY m.created_at DESC LIMIT 50"); $stmt->execute(); $messages = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode(array_reverse($messages)); } catch (Exception $e) { echo json_encode(['error' => $e->getMessage()]); } } elseif ($method === 'POST') { $input = json_decode(file_get_contents('php://input'), true); $username = $input['username'] ?? 'Anónimo'; $message = $input['message'] ?? ''; $type = $input['type'] ?? 'text'; $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR']; $ip = explode(',', $ip)[0]; if (empty($message)) { echo json_encode(['error' => 'Mensaje vacío']); exit; } try { $stmt = db()->prepare("INSERT INTO messages (username, ip_address, message, type) VALUES (?, ?, ?, ?)"); $stmt->execute([$username, $ip, $message, $type]); // Award points to the fan based on chat activity $fanStmt = db()->prepare("SELECT id, points FROM fans WHERE name = ?"); $fanStmt->execute([$username]); $fan = $fanStmt->fetch(); if ($fan) { $newPoints = $fan['points'] + 10; db()->prepare("UPDATE fans SET points = ? WHERE id = ?")->execute([$newPoints, $fan['id']]); } else { // Check if photo exists for this user in user_likes or elsewhere (optional enhancement) db()->prepare("INSERT INTO fans (name, points) VALUES (?, ?)")->execute([$username, 10]); $newPoints = 10; } // Auto-update Fan of the Month if this user has the highest points $maxPointsStmt = db()->query("SELECT MAX(points) as max_p FROM fans"); $maxPoints = $maxPointsStmt->fetch()['max_p']; if ($newPoints >= $maxPoints) { db()->query("UPDATE fans SET is_fan_of_month = 0"); db()->prepare("UPDATE fans SET is_fan_of_month = 1 WHERE name = ?")->execute([$username]); } echo json_encode(['success' => true]); } catch (Exception $e) { echo json_encode(['error' => $e->getMessage()]); } }