<?php
/**
 * Resources API Endpoint
 */

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

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

try {
    $pdo = getDBConnection();
    
    $type = $_GET['type'] ?? null;
    $category = $_GET['category'] ?? null;
    
    $query = "SELECT id, title, description, resource_type, category, file_url, external_url, icon
              FROM resources WHERE status = 'active'";
    
    if ($type) {
        $query .= " AND resource_type = :type";
    }
    if ($category) {
        $query .= " AND category = :category";
    }
    
    $query .= " ORDER BY display_order ASC, created_at DESC";
    
    $stmt = $pdo->prepare($query);
    $params = [];
    if ($type) $params[':type'] = $type;
    if ($category) $params[':category'] = $category;
    
    $stmt->execute($params);
    
    $resources = [];
    while ($row = $stmt->fetch()) {
        $resources[] = [
            'id' => $row['id'],
            'title' => $row['title'],
            'description' => $row['description'],
            'type' => $row['resource_type'],
            'category' => $row['category'],
            'file_url' => $row['file_url'] ? '/backend/uploads/resources/' . $row['file_url'] : null,
            'external_url' => $row['external_url'],
            'icon' => $row['icon']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'resources' => $resources
    ]);
    
} catch (Exception $e) {
    error_log("Resources API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'resources' => []
    ]);
}

