<?php
/**
 * AJAX: Search Rubrics
 * Search rubrics by name or path
 * Method: POST/GET
 */

require_once '../config/config.php';
require_once '../includes/functions.php';
require_once '../includes/rubric-tree.php';

session_start();
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

$query = $_POST['query'] ?? $_GET['query'] ?? '';

if (strlen($query) < 2) {
    echo json_encode(['success' => true, 'results' => []]);
    exit;
}

$pdo = getDB();

// Search rubrics
$searchTerm = '%' . $query . '%';
$stmt = $pdo->prepare("SELECT id, rubric_name, full_path, level, chapter_name,
                      (SELECT COUNT(*) FROM rubric_remedy WHERE rubric_id = rubrics.id) as remedy_count
                      FROM rubrics 
                      WHERE rubric_name LIKE ? OR full_path LIKE ?
                      ORDER BY level, rubric_name
                      LIMIT 50");
$stmt->execute([$searchTerm, $searchTerm]);
$results = $stmt->fetchAll();

$formatted = [];
foreach ($results as $rubric) {
    $formatted[] = [
        'id' => $rubric['id'],
        'name' => $rubric['rubric_name'],
        'full_path' => $rubric['full_path'],
        'level' => $rubric['level'],
        'chapter' => $rubric['chapter_name'],
        'remedy_count' => $rubric['remedy_count']
    ];
}

echo json_encode(['success' => true, 'results' => $formatted]);
?>