<?php
require_once '../config.php';

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

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

if (!isset($_POST['age_limit'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing age_limit']);
    exit;
}

$age_limit = (int)$_POST['age_limit'];

try {
    $stmt = $pdo->prepare("SELECT DISTINCT category FROM content WHERE status = 'approved' AND category IS NOT NULL AND category != '' ORDER BY category ASC");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    $content_by_category = [];
    
    foreach ($categories as $category) {
        $stmt = $pdo->prepare("SELECT * FROM content WHERE status = 'approved' AND age_rating <= ? AND category = ? ORDER BY created_at DESC LIMIT 12");
        $stmt->execute([$age_limit, $category]);
        $content = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($content)) {
            $content_by_category[$category] = $content;
        }
    }
    
    echo json_encode($content_by_category);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
?>