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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        // Limpiar mensajes y archivos de más de 6 horas
        $oldImages = db()->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]);
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
}
