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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        // Borrar fotos de la galería que tengan más de 5 segundos
        $stOld = db()->prepare("SELECT image_url FROM gallery WHERE created_at < DATE_SUB(NOW(), INTERVAL 5 SECOND)");
        $stOld->execute();
        $imagesToDelete = $stOld->fetchAll(PDO::FETCH_ASSOC);
        foreach ($imagesToDelete as $img) {
            $path = __DIR__ . '/../' . $img['image_url'];
            if (file_exists($path) && is_file($path)) {
                // unlink($path); // Opcional: borrar el archivo físico. 
                // Pero si viene del chat, el chat ya lo borra si habilitamos lo mismo ahí.
            }
        }
        db()->query("DELETE FROM gallery WHERE created_at < DATE_SUB(NOW(), INTERVAL 5 SECOND)");

        $stmt = db()->prepare("SELECT * FROM gallery ORDER BY created_at DESC LIMIT 50");
        $stmt->execute();
        $images = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'images' => $images]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
} elseif ($method === 'POST') {
    // This endpoint will be used by admin to promote an image
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    if ($action === 'promote') {
        $messageId = $input['message_id'] ?? 0;
        $caption = $input['caption'] ?? '';
        
        try {
            // Get the image message
            $stmt = db()->prepare("SELECT * FROM messages WHERE id = ? AND type = 'image'");
            $stmt->execute([$messageId]);
            $msg = $stmt->fetch();
            
            if (!$msg) {
                echo json_encode(['success' => false, 'error' => 'Imagen no encontrada']);
                exit;
            }
            
            // Insert into gallery
            $stmt = db()->prepare("INSERT INTO gallery (image_url, username, caption) VALUES (?, ?, ?)");
            $stmt->execute([$msg['message'], $msg['username'], $caption]);
            
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } elseif ($action === 'like') {
        $id = $input['id'] ?? 0;
        try {
            db()->prepare("UPDATE gallery SET likes = likes + 1 WHERE id = ?")->execute([$id]);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    }
}
