<?php
/**
 * AJAX Rubric Search
 * Search rubrics for autocomplete and quick lookup
 */

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

session_start();
header('Content-Type: application/json');

// Allow access for logged-in users only
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    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();

// If admin, also search by ID
if (isAdmin() && is_numeric($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 id = ?");
    $stmt->execute([$query]);
    $idResult = $stmt->fetch();
    if ($idResult && !in_array($idResult, $results)) {
        array_unshift($results, $idResult);
    }
}

// Format results
$formattedResults = [];
foreach ($results as $rubric) {
    $formattedResults[] = [
        'id' => $rubric['id'],
        'name' => $rubric['rubric_name'],
        'full_path' => $rubric['full_path'],
        'level' => $rubric['level'],
        'chapter' => $rubric['chapter_name'],
        'remedy_count' => $rubric['remedy_count'],
        'breadcrumb' => str_replace(' - ', ' › ', $rubric['full_path'])
    ];
}

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