<?php
/**
 * PWA API - Get Reports (cached for offline access)
 * 
 * GET /api/get-reports
 * Returns available reports for the current user
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

// Check authentication
if (!SessionManager::isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

try {
    $db = new Database();
    $userId = SessionManager::getUserId();
    $userRole = SessionManager::getUserRole();

    // Build query based on user role
    if ($userRole === ROLE_ADMIN) {
        // Admins see all reports
        $reports = $db->fetchAll(
            "SELECT id, title, description, type, status, created_at, created_by
             FROM reports
             ORDER BY created_at DESC
             LIMIT 100"
        );
    } elseif ($userRole === ROLE_CONTROLLER) {
        // Controllers see reports they created
        $reports = $db->fetchAll(
            "SELECT id, title, description, type, status, created_at, created_by
             FROM reports
             WHERE created_by = ?
             ORDER BY created_at DESC
             LIMIT 100",
            [$userId]
        );
    } else {
        // Other roles see publicly available reports
        $reports = $db->fetchAll(
            "SELECT id, title, description, type, status, created_at, created_by
             FROM reports
             WHERE status = 'published'
             ORDER BY created_at DESC
             LIMIT 100"
        );
    }

    // Return cached data
    header('Content-Type: application/json');
    header('Cache-Control: public, max-age=3600'); // Cache for 1 hour
    http_response_code(200);
    echo json_encode($reports ?? []);

} catch (Exception $e) {
    error_log('[PWA API] Get reports error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'error' => 'Failed to fetch reports',
        'message' => $e->getMessage(),
    ]);
}
