<?php
require_once 'config.php';

function authenticateSession($user_id, $device_id, $session_token) {
    if (empty($device_id) || empty($session_token)) {
        sendResponse(400, 'Device-ID and Session-Token headers are required');
    }

    $conn = getDbConnection();
    $stmt = $conn->prepare("SELECT id FROM users WHERE id = ? AND device_id = ? AND is_blocked = 0");
    $stmt->bind_param("is", $user_id, $device_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        sendResponse(401, 'Invalid user or device');
    }

    // Fixed query: Use SELECT 1 instead of SELECT id
    $stmt = $conn->prepare("SELECT 1 FROM session_tokens WHERE user_id = ? AND device_id = ? AND session_token = ? AND expires_at > NOW()");
    $stmt->bind_param("iss", $user_id, $device_id, $session_token);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        sendResponse(401, 'Invalid or expired session token');
    }

    $stmt->close();
    $conn->close();
}

function generateNewSessionToken($user_id, $device_id) {
    $conn = getDbConnection();
    $new_session_token = bin2hex(random_bytes(32));
    $expires_at = date('Y-m-d H:i:s', strtotime('+30 days'));

    $stmt = $conn->prepare("INSERT INTO session_tokens (user_id, device_id, session_token, expires_at) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE session_token = ?, created_at = NOW(), expires_at = ?");
    $stmt->bind_param("isssss", $user_id, $device_id, $new_session_token, $expires_at, $new_session_token, $expires_at);
    $stmt->execute();

    $stmt->close();
    $conn->close();
    return $new_session_token;
}

function rateLimit($user_id) {
    $conn = getDbConnection();

    // Fetch rate limit count from app_settings
    $stmt = $conn->prepare("SELECT rate_limit_count FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->close();

    $request_limit = isset($settings['rate_limit_count']) ? (int)$settings['rate_limit_count'] : 100;
    $time_window = 3600; // 1 hour in seconds

    $current_time = time();
    $window_start = $current_time - $time_window;

    $stmt = $conn->prepare("DELETE FROM rate_limit WHERE timestamp < ?");
    $stmt->bind_param("i", $window_start);
    $stmt->execute();

    $stmt = $conn->prepare("SELECT COUNT(*) as request_count FROM rate_limit WHERE user_id = ? AND timestamp >= ?");
    $stmt->bind_param("ii", $user_id, $window_start);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    if ($row['request_count'] >= $request_limit) {
        sendResponse(429, 'Too many requests');
    }

    $stmt = $conn->prepare("INSERT INTO rate_limit (user_id, timestamp) VALUES (?, ?)");
    $stmt->bind_param("ii", $user_id, $current_time);
    $stmt->execute();

    $stmt->close();
    $conn->close();
}

function authenticateAdmin($token) {
    $valid_admin_token = 'admin_token_example'; // In production, use a proper auth system
    if ($token !== $valid_admin_token) {
        sendResponse(401, 'Invalid admin token');
    }
}
?>