<?php
/**
 * Advanced Rubric Search
 * Search and filter rubrics with multiple criteria
 */

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

requireLogin();

$pdo = getDB();
$query = $_GET['q'] ?? '';
$chapter = $_GET['chapter'] ?? '';
$level = $_GET['level'] ?? '';
$hasRemedies = $_GET['has_remedies'] ?? '';

// Get all chapters for filter
$chapters = $pdo->query("SELECT DISTINCT chapter_name FROM rubrics WHERE level = 1 ORDER BY chapter_name")->fetchAll();

// Build search query
$whereConditions = ["1=1"];
$params = [];

if (!empty($query)) {
    $whereConditions[] = "(rubric_name LIKE ? OR full_path LIKE ?)";
    $searchTerm = "%$query%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if (!empty($chapter)) {
    $whereConditions[] = "chapter_name = ?";
    $params[] = $chapter;
}

if (!empty($level)) {
    $whereConditions[] = "level = ?";
    $params[] = $level;
}

if ($hasRemedies == 'yes') {
    $whereConditions[] = "EXISTS (SELECT 1 FROM rubric_remedy WHERE rubric_id = rubrics.id)";
} elseif ($hasRemedies == 'no') {
    $whereConditions[] = "NOT EXISTS (SELECT 1 FROM rubric_remedy WHERE rubric_id = rubrics.id)";
}

$whereClause = implode(" AND ", $whereConditions);

// Execute search
$sql = "SELECT r.*, 
        (SELECT COUNT(*) FROM rubric_remedy WHERE rubric_id = r.id) as remedy_count
        FROM rubrics r
        WHERE $whereClause
        ORDER BY r.full_path
        LIMIT 100";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll();

// Get statistics for search results
$stats = [
    'total' => count($results),
    'with_remedies' => count(array_filter($results, function($r) { return $r['remedy_count'] > 0; })),
    'without_remedies' => count(array_filter($results, function($r) { return $r['remedy_count'] == 0; }))
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Rubrics - <?php echo APP_NAME; ?></title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #f0f2f5; }
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a472a 0%, #0d2818 100%);
            position: fixed;
            left: 0;
            top: 0;
            width: 260px;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); }
        .sidebar .nav-link.active { background: #2ecc71; }
        .sidebar .nav-link i { margin-right: 10px; }
        .main-content { margin-left: 260px; padding: 20px; }
        .top-navbar {
            background: white;
            border-radius: 12px;
            padding: 15px 25px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .search-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .result-item {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            transition: all 0.2s;
            border-left: 4px solid #2ecc71;
        }
        .result-item:hover { transform: translateX(5px); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .grade-1, .grade-2, .grade-3, .grade-4 { display: inline-block; margin: 2px; }
        @media (max-width: 768px) { .sidebar { width: 70px; } .sidebar .nav-link span { display: none; } .main-content { margin-left: 70px; } }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="text-center py-4"><h4 class="text-white mb-0">🏥</h4></div>
        <nav class="nav flex-column">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link" href="../cases/index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link" href="search.php"><i class="fas fa-search"></i> <span>Search</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr><a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-search"></i> Advanced Rubric Search</h4>
                <a href="index.php" class="btn btn-secondary btn-sm">Back to Browser</a>
            </div>
        </div>
        
        <!-- Search Form -->
        <div class="search-card">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Search Keywords</label>
                        <input type="text" name="q" class="form-control" placeholder="Enter rubric name or path..." value="<?php echo escape($query); ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Chapter</label>
                        <select name="chapter" class="form-control">
                            <option value="">All Chapters</option>
                            <?php foreach($chapters as $c): ?>
                                <option value="<?php echo escape($c['chapter_name']); ?>" <?php echo $chapter == $c['chapter_name'] ? 'selected' : ''; ?>>
                                    <?php echo escape($c['chapter_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Level</label>
                        <select name="level" class="form-control">
                            <option value="">All Levels</option>
                            <option value="1" <?php echo $level == '1' ? 'selected' : ''; ?>>Level 1 - Chapter</option>
                            <option value="2" <?php echo $level == '2' ? 'selected' : ''; ?>>Level 2 - Section</option>
                            <option value="3" <?php echo $level == '3' ? 'selected' : ''; ?>>Level 3 - Subsection</option>
                            <option value="4" <?php echo $level == '4' ? 'selected' : ''; ?>>Level 4 - Rubric</option>
                            <option value="5" <?php echo $level == '5' ? 'selected' : ''; ?>>Level 5 - Sub-rubric</option>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Has Remedies</label>
                        <select name="has_remedies" class="form-control">
                            <option value="">All</option>
                            <option value="yes" <?php echo $hasRemedies == 'yes' ? 'selected' : ''; ?>>With Remedies</option>
                            <option value="no" <?php echo $hasRemedies == 'no' ? 'selected' : ''; ?>>Without Remedies</option>
                        </select>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
                <a href="search.php" class="btn btn-secondary">Reset</a>
            </form>
        </div>
        
        <!-- Results -->
        <?php if ($query || $chapter || $level): ?>
            <div class="search-card">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="fas fa-list"></i> Search Results (<?php echo $stats['total']; ?> found)</h5>
                    <div>
                        <span class="badge bg-success">With Remedies: <?php echo $stats['with_remedies']; ?></span>
                        <span class="badge bg-secondary">Without Remedies: <?php echo $stats['without_remedies']; ?></span>
                    </div>
                </div>
                
                <?php if (empty($results)): ?>
                    <div class="alert alert-info">No rubrics found matching your criteria.</div>
                <?php else: ?>
                    <?php foreach($results as $rubric): ?>
                        <div class="result-item">
                            <div class="row">
                                <div class="col-md-8">
                                    <a href="rubric.php?id=<?php echo $rubric['id']; ?>" class="text-decoration-none">
                                        <strong><?php echo escape($rubric['full_path']); ?></strong>
                                    </a>
                                    <div class="mt-1">
                                        <span class="badge bg-secondary">Level <?php echo $rubric['level']; ?></span>
                                        <span class="badge bg-info">Chapter: <?php echo escape($rubric['chapter_name']); ?></span>
                                        <span class="badge bg-primary"><?php echo $rubric['remedy_count']; ?> remedies</span>
                                    </div>
                                    <?php 
                                    // Get remedies for preview
                                    $remedies = getRubricRemedies($rubric['id']);
                                    if (!empty($remedies)):
                                    ?>
                                        <div class="mt-2">
                                            <small class="text-muted">Remedies: </small>
                                            <?php foreach(array_slice($remedies, 0, 10) as $rem): ?>
                                                <span class="<?php echo $rem['css_class']; ?>"><?php echo escape($rem['name']); ?></span>
                                            <?php endforeach; ?>
                                            <?php if(count($remedies) > 10): ?>
                                                <span class="text-muted">+<?php echo count($remedies) - 10; ?> more</span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-4 text-end">
                                    <a href="rubric.php?id=<?php echo $rubric['id']; ?>" class="btn btn-sm btn-primary">
                                        <i class="fas fa-eye"></i> View Details
                                    </a>
                                    <button class="btn btn-sm btn-success" onclick="window.location.href='../cases/new.php?rubric_id=<?php echo $rubric['id']; ?>'">
                                        <i class="fas fa-plus-circle"></i> Use in Case
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="search-card">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-search fa-3x mb-3"></i>
                    <p>Enter search criteria above to find rubrics in Kent's Repertory.</p>
                    <small>You can search by rubric name, full path, or filter by chapter and level.</small>
                </div>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>