<?php
/**
 * API: Consultar solicitudes de archivos grandes de un usuario
 * 
 * GET /api/get_file_requests.php?user_id=123
 * GET /api/get_file_requests.php?user_id=123&status=pending
 * 
 * Respuesta: { success: bool, requests: [...], uploads: [...] }
 */

require_once __DIR__ . '/../config/config.php';

error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', 0);

requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

try {
    $userId = intval($_GET['user_id'] ?? 0);
    $status = trim($_GET['status'] ?? '');

    if (!$userId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Se requiere user_id']);
        exit;
    }

    $db = Database::getInstance();

    // Obtener solicitudes
    $sql = "SELECT fr.*, 
                   CASE WHEN fr.expires_at < NOW() AND fr.status = 'pending' THEN 'expired' ELSE fr.status END as effective_status,
                   (SELECT COUNT(*) FROM file_request_uploads fru WHERE fru.request_id = fr.id) as upload_count
            FROM file_requests fr 
            WHERE fr.user_id = ?";
    $params = [$userId];

    if (!empty($status)) {
        if ($status === 'active') {
            $sql .= " AND fr.status IN ('pending','uploaded') AND fr.expires_at > NOW()";
        } else {
            $sql .= " AND fr.status = ?";
            $params[] = $status;
        }
    }

    $sql .= " ORDER BY fr.created_at DESC LIMIT 20";
    $requests = $db->fetchAll($sql, $params);

    // Obtener uploads de las solicitudes
    $uploads = [];
    $requestIds = array_column($requests, 'id');
    if (!empty($requestIds)) {
        $placeholders = implode(',', array_fill(0, count($requestIds), '?'));
        $uploads = $db->fetchAll(
            "SELECT fru.*, fr.token as request_token
             FROM file_request_uploads fru 
             JOIN file_requests fr ON fru.request_id = fr.id
             WHERE fru.request_id IN ({$placeholders}) 
             ORDER BY fru.created_at DESC",
            $requestIds
        );

        // Agregar URLs públicas
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $appUrl = $protocol . '://' . $_SERVER['HTTP_HOST'];
        foreach ($uploads as &$upload) {
            $upload['file_url'] = $appUrl . '/' . $upload['file_path'];
            $upload['thumb_url'] = $upload['thumbnail_path'] 
                ? $appUrl . '/' . $upload['thumbnail_path'] 
                : null;
        }
    }

    echo json_encode([
        'success' => true,
        'requests' => $requests,
        'uploads' => $uploads,
    ]);

} catch (Exception $e) {
    error_log('Error en get_file_requests: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno']);
}
