<?php
/**
 * Manage Rubrics - Tree View
 * Display Kent's Repertory rubric hierarchy
 */

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

requireAdmin();

$pdo = getDB();
$message = '';
$error = '';

// Handle expand/collapse state
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['toggle_state'])) {
    $_SESSION['rubric_expanded'] = $_POST['expanded_nodes'] ?? [];
}

// Get rubric statistics
$stmt = $pdo->query("SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN level = 1 THEN 1 ELSE 0 END) as chapters,
                    SUM(CASE WHEN level = 2 THEN 1 ELSE 0 END) as sections,
                    SUM(CASE WHEN level = 3 THEN 1 ELSE 0 END) as sub_sections,
                    SUM(CASE WHEN level >= 4 THEN 1 ELSE 0 END) as rubrics,
                    (SELECT COUNT(DISTINCT remedy_id) FROM rubric_remedy) as remedies_linked
                    FROM rubrics");
$stats = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Rubrics - Admin Panel</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stats-number {
            font-size: 28px;
            font-weight: bold;
        }
        .rubric-tree-container {
            max-height: 70vh;
            overflow-y: auto;
            padding: 15px;
            background: white;
            border-radius: 8px;
        }
        .rubric-node {
            margin: 5px 0;
        }
        .rubric-children {
            margin-left: 30px;
        }
        .rubric-item {
            padding: 8px 12px;
            background: #f8f9fa;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        .rubric-item:hover {
            background: #e9ecef;
        }
        .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;
        }
        .remedy-list {
            display: inline-block;
            margin-left: 15px;
        }
        .remedy-list span {
            font-size: 11px;
            margin-right: 5px;
            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; }
        .rubric-actions {
            display: flex;
            gap: 5px;
        }
        .rubric-actions button {
            padding: 2px 8px;
            font-size: 12px;
        }
        .level-badge {
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 10px;
            margin-left: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </div>
                <nav class="nav flex-column">
                    <a class="nav-link" href="../dashboard.php">
                        <i class="fas fa-tachometer-alt"></i> Dashboard
                    </a>
                    <a class="nav-link" href="../doctors/index.php">
                        <i class="fas fa-user-md"></i> Doctors
                    </a>
                    <a class="nav-link" href="../subscriptions/index.php">
                        <i class="fas fa-credit-card"></i> Subscriptions
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link" href="../remedies/index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </a>
                    <a class="nav-link" href="../reports/index.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a class="nav-link" href="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-tree"></i> Manage Rubrics (Kent's Repertory)</h4>
                        <div>
                            <a href="add.php" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus"></i> Add Rubric
                            </a>
                            <a href="bulk-import.php" class="btn btn-info btn-sm">
                                <i class="fas fa-upload"></i> Bulk Import
                            </a>
                            <a href="export.php" class="btn btn-success btn-sm">
                                <i class="fas fa-download"></i> Export
                            </a>
                            <a href="reorder.php" class="btn btn-warning btn-sm">
                                <i class="fas fa-arrows-alt"></i> Reorder
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['total']; ?></div>
                                <div class="text-muted">Total Rubrics</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['chapters']; ?></div>
                                <div class="text-muted">Chapters</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['sections'] + $stats['sub_sections']; ?></div>
                                <div class="text-muted">Sections</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo $stats['remedies_linked']; ?></div>
                                <div class="text-muted">Remedies Linked</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Search Bar -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-10">
                                    <input type="text" id="rubricSearch" class="form-control" 
                                           placeholder="Search rubrics by name or path...">
                                </div>
                                <div class="col-md-2">
                                    <button class="btn btn-primary w-100" onclick="searchRubrics()">
                                        <i class="fas fa-search"></i> Search
                                    </button>
                                </div>
                            </div>
                            <div id="searchResults" class="mt-3" style="display: none;"></div>
                        </div>
                    </div>
                    
                    <!-- Rubric Tree -->
                    <div class="card">
                        <div class="card-header">
                            <div class="d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="fas fa-sitemap"></i> Repertory Hierarchy</h5>
                                <div>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="expandAll()">
                                        <i class="fas fa-plus-square"></i> Expand All
                                    </button>
                                    <button class="btn btn-sm btn-outline-secondary" onclick="collapseAll()">
                                        <i class="fas fa-minus-square"></i> Collapse All
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="rubric-tree-container">
                                <div id="rubricTree">
                                    <?php echo getRubricTreeHTML(); ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Legend -->
                    <div class="card mt-3">
                        <div class="card-body">
                            <h6 class="mb-2">Grade Legend:</h6>
                            <div class="d-flex gap-3">
                                <span class="grade-4">Grade 4 - Bold Underline</span>
                                <span class="grade-3">Grade 3 - Bold Red</span>
                                <span class="grade-2">Grade 2 - Blue Italic</span>
                                <span class="grade-1">Grade 1 - Normal</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.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() === '▼' ? '▶' : '▼');
            
            // Save expanded state
            saveExpandedState();
        });
        
        // Edit rubric
        window.editRubric = function(id) {
            window.location.href = `edit.php?id=${id}`;
        };
        
        // Add child rubric
        window.addChildRubric = function(parentId) {
            window.location.href = `add.php?parent_id=${parentId}`;
        };
        
        // Delete rubric
        window.deleteRubric = function(id, name) {
            if (confirm(`Delete rubric "${name}" and all its children? This action cannot be undone.`)) {
                window.location.href = `delete.php?id=${id}`;
            }
        };
        
        // Search rubrics
        window.searchRubrics = function() {
            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>
                                        <div class="mt-1">
                                            <button class="btn btn-sm btn-primary" onclick="editRubric(${rubric.id})">Edit</button>
                                            <button class="btn btn-sm btn-danger" onclick="deleteRubric(${rubric.id}, '${rubric.rubric_name}')">Delete</button>
                                        </div>
                                     </div>`;
                        });
                        html += '</div>';
                        $('#searchResults').html(html).show();
                    } else {
                        $('#searchResults').html('<div class="alert alert-info">No rubrics found</div>').show();
                    }
                }
            });
        };
        
        // Expand all
        window.expandAll = function() {
            $('.rubric-children').show();
            $('.toggle-icon').text('▼');
            saveExpandedState();
        };
        
        // Collapse all
        window.collapseAll = function() {
            $('.rubric-children').hide();
            $('.toggle-icon').text('▶');
            saveExpandedState();
        };
        
        // Save expanded state
        function saveExpandedState() {
            let expandedNodes = [];
            $('.rubric-children:visible').each(function() {
                const nodeId = $(this).closest('.rubric-node').data('id');
                if (nodeId) expandedNodes.push(nodeId);
            });
            
            $.ajax({
                url: 'index.php',
                method: 'POST',
                data: { toggle_state: 1, expanded_nodes: expandedNodes },
                async: false
            });
        }
        
        // Search on enter key
        $('#rubricSearch').on('keypress', function(e) {
            if (e.which === 13) searchRubrics();
        });
        
        // Clear search when input is cleared
        $('#rubricSearch').on('input', function() {
            if ($(this).val().length < 2) {
                $('#rubricTree').show();
                $('#searchResults').hide();
            }
        });
    </script>
</body>
</html>