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

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

$ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
$ip = explode(',', $ip)[0];

try {
    $stmt = db()->prepare("SELECT COUNT(*) FROM messages WHERE ip_address = ? AND type = 'image' AND created_at > DATE_SUB(NOW(), INTERVAL 6 HOUR)");
    $stmt->execute([$ip]);
    $count = (int)$stmt->fetchColumn();
    
    $limit = 5;
    $remaining = max(0, $limit - $count);
    
    $reset_in_seconds = 0;
    if ($count >= $limit) {
        // Find the oldest message in the 6-hour window
        $stmt = db()->prepare("SELECT created_at FROM messages WHERE ip_address = ? AND type = 'image' AND created_at > DATE_SUB(NOW(), INTERVAL 6 HOUR) ORDER BY created_at ASC LIMIT 1");
        $stmt->execute([$ip]);
        $oldest = $stmt->fetchColumn();
        if ($oldest) {
            $oldest_time = strtotime($oldest);
            $reset_time = $oldest_time + (6 * 3600);
            $reset_in_seconds = max(0, $reset_time - time());
        }
    }
    
    echo json_encode([
        'count' => $count,
        'limit' => $limit,
        'remaining' => $remaining,
        'reset_in_seconds' => $reset_in_seconds
    ]);
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
