<?php
/**
 * PWA API - Get User Assignments (cached for offline access)
 * 
 * GET /api/get-assignments
 * Returns all assignments 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 assignments
        $assignments = $db->fetchAll(
            "SELECT a.*, u.full_name as assigned_user, i.name as item_name
             FROM assignments a
             LEFT JOIN users u ON a.user_id = u.id
             LEFT JOIN items i ON a.item_id = i.id
             ORDER BY a.created_at DESC
             LIMIT 500"
        );
    } elseif ($userRole === ROLE_CONTROLLER) {
        // Controllers see assignments they manage
        $assignments = $db->fetchAll(
            "SELECT a.*, u.full_name as assigned_user, i.name as item_name
             FROM assignments a
             LEFT JOIN users u ON a.user_id = u.id
             LEFT JOIN items i ON a.item_id = i.id
             WHERE a.controller_id = ? OR a.created_by = ?
             ORDER BY a.created_at DESC
             LIMIT 500",
            [$userId, $userId]
        );
    } else {
        // Counters and checkers see only their assignments
        $assignments = $db->fetchAll(
            "SELECT a.*, u.full_name as assigned_user, i.name as item_name
             FROM assignments a
             LEFT JOIN users u ON a.user_id = u.id
             LEFT JOIN items i ON a.item_id = i.id
             WHERE a.user_id = ?
             ORDER BY a.status, a.created_at DESC
             LIMIT 500",
            [$userId]
        );
    }

    // 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($assignments ?? []);

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