<?php
/**
 * Browse Repertory Tree
 * Interactive tree view of Kent's Repertory
 */

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

requireLogin();

$pdo = getDB();

// Get repertory statistics
$stmt = $pdo->query("SELECT 
                    COUNT(*) as total_rubrics,
                    SUM(CASE WHEN level = 1 THEN 1 ELSE 0 END) as chapters,
                    SUM(CASE WHEN level >= 2 AND level <= 3 THEN 1 ELSE 0 END) as sections,
                    SUM(CASE WHEN level >= 4 THEN 1 ELSE 0 END) as rubrics,
                    (SELECT COUNT(*) FROM remedies) as total_remedies
                    FROM rubrics");
$stats = $stmt->fetch();

// Get featured/random remedies for sidebar
$stmt = $pdo->query("SELECT id, name, abbreviation 
                    FROM remedies 
                    ORDER BY RAND() 
                    LIMIT 10");
$randomRemedies = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Repertory Browser - <?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;
            z-index: 100;
        }
        .sidebar .nav-link {
            color: rgba(255,255,255,0.8);
            padding: 12px 20px;
            margin: 5px 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover { background: rgba(255,255,255,0.1); transform: translateX(5px); }
        .sidebar .nav-link.active { background: #2ecc71; color: white; }
        .sidebar .nav-link i { margin-right: 10px; width: 20px; }
        .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);
        }
        .rubric-tree-container {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            max-height: 75vh;
            overflow-y: auto;
        }
        .rubric-node { margin: 2px 0; }
        .rubric-children { margin-left: 25px; }
        .rubric-item {
            padding: 8px 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .rubric-item:hover { background: #e8f5e9; }
        .rubric-name { font-size: 14px; }
        .chapter-name { font-size: 16px; font-weight: bold; color: #2c3e50; }
        .toggle-icon {
            cursor: pointer;
            margin-right: 10px;
            font-size: 12px;
            width: 20px;
            display: inline-block;
        }
        .remedy-list { display: inline-block; margin-left: 10px; }
        .remedy-list span { margin-right: 5px; font-size: 11px; white-space: nowrap; }
        .grade-1 { font-weight: normal; color: #000; }
        .grade-2 { font-style: italic; color: #0066cc; }
        .grade-3 { font-weight: bold; color: #cc0000; }
        .grade-4 { font-weight: bold; text-decoration: underline; color: #000; }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        .stats-number { font-size: 28px; font-weight: bold; }
        .search-box {
            position: sticky;
            top: 0;
            background: white;
            padding: 10px;
            border-bottom: 1px solid #eee;
            z-index: 10;
        }
        @media (max-width: 768px) {
            .sidebar { width: 70px; }
            .sidebar .nav-link span { display: none; }
            .main-content { margin-left: 70px; }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="text-center py-4">
            <h4 class="text-white mb-0">🏥 Homoeopathy</h4>
            <small class="text-white-50">Kent's Repertory</small>
        </div>
        <nav class="nav flex-column mt-3">
            <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="../materia-medica/index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> <span>Profile</span></a>
            <hr class="bg-secondary my-3">
            <a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
        </nav>
    </div>
    
    <!-- Main Content -->
    <div class="main-content">
        <div class="top-navbar">
            <div class="d-flex justify-content-between align-items-center">
                <h4 class="mb-0"><i class="fas fa-book"></i> Kent's Repertory Browser</h4>
                <div>
                    <a href="search.php" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-search"></i> Advanced Search
                    </a>
                    <a href="../cases/new.php" class="btn btn-success btn-sm ms-2">
                        <i class="fas fa-plus-circle"></i> New Case
                    </a>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-9">
                <div class="rubric-tree-container">
                    <div class="search-box">
                        <div class="input-group">
                            <input type="text" id="rubricSearch" class="form-control" placeholder="Search rubrics by name or path...">
                            <button class="btn btn-primary" onclick="searchRubrics()">
                                <i class="fas fa-search"></i> Search
                            </button>
                            <button class="btn btn-outline-secondary" onclick="expandAll()">
                                <i class="fas fa-expand-alt"></i> Expand All
                            </button>
                            <button class="btn btn-outline-secondary" onclick="collapseAll()">
                                <i class="fas fa-compress-alt"></i> Collapse All
                            </button>
                        </div>
                    </div>
                    <div id="rubricTree">
                        <?php echo getRubricTreeHTML(); ?>
                    </div>
                    <div id="searchResults" style="display: none;"></div>
                </div>
            </div>
            
            <div class="col-md-3">
                <!-- Statistics Card -->
                <div class="stats-card">
                    <div class="stats-number"><?php echo $stats['total_rubrics']; ?></div>
                    <div class="text-muted">Total Rubrics</div>
                    <hr>
                    <div class="row">
                        <div class="col-6"><small>Chapters</small><br><strong><?php echo $stats['chapters']; ?></strong></div>
                        <div class="col-6"><small>Sections</small><br><strong><?php echo $stats['sections']; ?></strong></div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-6"><small>Rubrics</small><br><strong><?php echo $stats['rubrics']; ?></strong></div>
                        <div class="col-6"><small>Remedies</small><br><strong><?php echo $stats['total_remedies']; ?></strong></div>
                    </div>
                </div>
                
                <!-- Grade Legend -->
                <div class="stats-card">
                    <h6><i class="fas fa-palette"></i> Grade Legend</h6>
                    <div class="mt-2">
                        <div><span class="grade-4">Grade 4</span> - Bold Underline (Most indicated)</div>
                        <div><span class="grade-3">Grade 3</span> - Bold Red</div>
                        <div><span class="grade-2">Grade 2</span> - Blue Italic</div>
                        <div><span class="grade-1">Grade 1</span> - Normal (Least indicated)</div>
                    </div>
                </div>
                
                <!-- Random Remedies -->
                <div class="stats-card">
                    <h6><i class="fas fa-random"></i> Random Remedies</h6>
                    <div class="mt-2">
                        <?php foreach($randomRemedies as $remedy): ?>
                            <a href="../materia-medica/view.php?id=<?php echo $remedy['id']; ?>" class="d-block mb-1 text-decoration-none">
                                <i class="fas fa-capsules"></i> <?php echo escape($remedy['name']); ?>
                                <?php if($remedy['abbreviation']): ?>
                                    <small class="text-muted">(<?php echo $remedy['abbreviation']; ?>)</small>
                                <?php endif; ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                
                <!-- Quick Links -->
                <div class="stats-card">
                    <h6><i class="fas fa-link"></i> Quick Links</h6>
                    <div class="mt-2">
                        <a href="compare.php" class="d-block mb-2">
                            <i class="fas fa-chart-line"></i> Compare Rubrics
                        </a>
                        <a href="rubric.php" class="d-block mb-2">
                            <i class="fas fa-info-circle"></i> View Specific Rubric
                        </a>
                        <a href="search.php" class="d-block">
                            <i class="fas fa-search"></i> Advanced Search
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle rubric children
        $(document).on('click', '.toggle-icon', function(e) {
            e.stopPropagation();
            const node = $(this).closest('.rubric-node');
            node.find('.rubric-children').slideToggle();
            const icon = $(this);
            icon.text(icon.text() === '▼' ? '▶' : '▼');
        });
        
        // Click on rubric name to view details
        $(document).on('click', '.rubric-name', function() {
            const rubricId = $(this).closest('.rubric-node').data('id');
            if (rubricId) {
                window.location.href = `rubric.php?id=${rubricId}`;
            }
        });
        
        // Expand all rubrics
        function expandAll() {
            $('.rubric-children').show();
            $('.toggle-icon').text('▼');
        }
        
        // Collapse all rubrics
        function collapseAll() {
            $('.rubric-children').hide();
            $('.toggle-icon').text('▶');
        }
        
        // Search rubrics
        function searchRubrics() {
            const query = $('#rubricSearch').val();
            if (query.length < 2) {
                $('#rubricTree').show();
                $('#searchResults').hide();
                return;
            }
            
            $.ajax({
                url: 'search.php',
                method: 'POST',
                data: { query: query },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.results.length > 0) {
                        $('#rubricTree').hide();
                        let html = '<div class="list-group">';
                        response.results.forEach(function(rubric) {
                            html += `<div class="list-group-item">
                                        <strong>${rubric.full_path}</strong><br>
                                        <small class="text-muted">Chapter: ${rubric.chapter || '-'}</small>
                                        <div class="mt-2">
                                            <a href="rubric.php?id=${rubric.id}" class="btn btn-sm btn-primary">View Details</a>
                                            <button class="btn btn-sm btn-success" onclick="selectForCase(${rubric.id}, '${rubric.full_path}')">Select for Case</button>
                                        </div>
                                     </div>`;
                        });
                        html += '</div>';
                        $('#searchResults').html(html).show();
                    } else {
                        $('#searchResults').html('<div class="alert alert-info">No rubrics found</div>').show();
                    }
                }
            });
        }
        
        // Select rubric for case (redirects to new case page)
        function selectForCase(id, path) {
            window.location.href = `../cases/new.php?rubric_id=${id}`;
        }
        
        // Enter key search
        $('#rubricSearch').on('keypress', function(e) {
            if (e.which === 13) searchRubrics();
        });
        
        // Initial collapse state - collapse all deeper levels
        $(document).ready(function() {
            $('.rubric-children').hide();
            $('.toggle-icon').text('▶');
            // Show top level
            $('.rubric-children').each(function() {
                if ($(this).closest('.rubric-node').find('> .rubric-item .chapter-name').length) {
                    $(this).show();
                    $(this).siblings('.rubric-item').find('.toggle-icon').text('▼');
                }
            });
        });
    </script>
</body>
</html>