<?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['search']) || !isset($_POST['age_limit'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing search or age_limit']);
    exit;
}

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

try {
    $stmt = $pdo->prepare("SELECT * FROM content WHERE status = 'approved' AND age_rating <= ? AND (title LIKE ? OR description LIKE ? OR author LIKE ?) ORDER BY created_at DESC LIMIT 20");
    $search_term = "%$search%";
    $stmt->execute([$age_limit, $search_term, $search_term, $search_term]);
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($results);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error']);
}
?>