<?php
/**
 * View Single Rubric
 * Display rubric details with all remedies and grades
 */

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

requireLogin();

$pdo = getDB();
$rubricId = (int)($_GET['id'] ?? 0);

// Get rubric details
$stmt = $pdo->prepare("SELECT * FROM rubrics WHERE id = ?");
$stmt->execute([$rubricId]);
$rubric = $stmt->fetch();

if (!$rubric) {
    header('Location: index.php?error=Rubric not found');
    exit;
}

// Get breadcrumb path
$breadcrumb = getRubricBreadcrumbs($rubricId, ' > ');

// Get remedies with grades
$remedies = getRubricRemedies($rubricId);

// Get child rubrics if any
$stmt = $pdo->prepare("SELECT * FROM rubrics WHERE parent_id = ? ORDER BY sort_order, rubric_name");
$stmt->execute([$rubricId]);
$children = $stmt->fetchAll();

// Get similar rubrics (same chapter, similar name)
$stmt = $pdo->prepare("SELECT id, rubric_name, full_path 
                      FROM rubrics 
                      WHERE chapter_name = ? AND id != ? 
                      ORDER BY rubric_name 
                      LIMIT 10");
$stmt->execute([$rubric['chapter_name'], $rubricId]);
$similarRubrics = $stmt->fetchAll();

// Get statistics
$gradeCount = [1 => 0, 2 => 0, 3 => 0, 4 => 0];
foreach ($remedies as $rem) {
    $gradeCount[$rem['grade']]++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo escape($rubric['rubric_name']); ?> - Repertory</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);
        }
        .rubric-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .breadcrumb-nav {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .remedy-table td { padding: 10px; vertical-align: middle; }
        .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; }
        .grade-badge {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 50%;
            font-weight: bold;
        }
        .grade-4-badge { background: #ffeb3b; text-decoration: underline; }
        .grade-3-badge { background: #ffcdd2; color: #c62828; }
        .grade-2-badge { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1-badge { background: #e0e0e0; }
        @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="../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-tree"></i> Rubric Details</h4>
                <div>
                    <button class="btn btn-success btn-sm" onclick="window.location.href='../cases/new.php?rubric_id=<?php echo $rubricId; ?>'">
                        <i class="fas fa-plus-circle"></i> Use in Case
                    </button>
                    <a href="index.php" class="btn btn-secondary btn-sm">Back to Browser</a>
                </div>
            </div>
        </div>
        
        <!-- Breadcrumb -->
        <div class="breadcrumb-nav">
            <i class="fas fa-sitemap"></i> <?php echo $breadcrumb; ?>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <!-- Rubric Information -->
                <div class="rubric-card">
                    <h3><?php echo escape($rubric['rubric_name']); ?></h3>
                    <div class="mt-2">
                        <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 count($remedies); ?> Remedies</span>
                    </div>
                    <div class="mt-3">
                        <strong>Full Path:</strong><br>
                        <code><?php echo escape($rubric['full_path']); ?></code>
                    </div>
                </div>
                
                <!-- Remedies Table -->
                <div class="rubric-card">
                    <h5><i class="fas fa-capsules"></i> Remedies with Grades</h5>
                    <div class="table-responsive">
                        <table class="table table-hover remedy-table">
                            <thead class="table-light">
                                <tr>
                                    <th>#</th>
                                    <th>Remedy</th>
                                    <th>Grade</th>
                                    <th>Weight</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($remedies)): ?>
                                    <tr><td colspan="5" class="text-center text-muted">No remedies assigned to this rubric</td></tr>
                                <?php else: ?>
                                    <?php $count = 1; ?>
                                    <?php foreach($remedies as $remedy): ?>
                                    <tr>
                                        <td><?php echo $count++; ?></td>
                                        <td>
                                            <strong><?php echo escape($remedy['name']); ?></strong>
                                            <?php if($remedy['abbreviation'] ?? false): ?>
                                                <br><small class="text-muted"><?php echo $remedy['abbreviation']; ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="grade-badge grade-<?php echo $remedy['grade']; ?>-badge">
                                                <?php echo $remedy['grade']; ?>
                                            </span>
                                            <span class="grade-<?php echo $remedy['grade']; ?> ms-2">
                                                <?php echo $remedy['grade'] == 4 ? 'Bold Underline' : ($remedy['grade'] == 3 ? 'Bold Red' : ($remedy['grade'] == 2 ? 'Blue Italic' : 'Normal')); ?>
                                            </span>
                                        </td>
                                        <td><?php echo getGradeWeight($remedy['grade']); ?> points</td>
                                        <td>
                                            <a href="../materia-medica/view.php?name=<?php echo urlencode($remedy['name']); ?>" class="btn btn-sm btn-outline-info" target="_blank">
                                                <i class="fas fa-book"></i> Materia Medica
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Grade Distribution -->
                    <?php if(!empty($remedies)): ?>
                    <div class="mt-4">
                        <strong>Grade Distribution:</strong>
                        <div class="row mt-2">
                            <div class="col-3"><span class="grade-4">Grade 4:</span> <?php echo $gradeCount[4]; ?> remedies</div>
                            <div class="col-3"><span class="grade-3">Grade 3:</span> <?php echo $gradeCount[3]; ?> remedies</div>
                            <div class="col-3"><span class="grade-2">Grade 2:</span> <?php echo $gradeCount[2]; ?> remedies</div>
                            <div class="col-3"><span class="grade-1">Grade 1:</span> <?php echo $gradeCount[1]; ?> remedies</div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Child Rubrics -->
                <?php if(!empty($children)): ?>
                <div class="rubric-card">
                    <h5><i class="fas fa-sitemap"></i> Sub-rubrics</h5>
                    <div class="list-group">
                        <?php foreach($children as $child): ?>
                            <a href="rubric.php?id=<?php echo $child['id']; ?>" class="list-group-item list-group-item-action">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="fas fa-folder-open"></i> <?php echo escape($child['rubric_name']); ?>
                                        <small class="text-muted ms-2"><?php echo escape($child['full_path']); ?></small>
                                    </div>
                                    <i class="fas fa-chevron-right text-muted"></i>
                                </div>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="col-md-4">
                <!-- Quick Stats -->
                <div class="rubric-card">
                    <h6><i class="fas fa-chart-bar"></i> Quick Statistics</h6>
                    <table class="table table-sm">
                        <tr><th>Rubric ID:</th><td><?php echo $rubric['id']; ?></td></tr>
                        <tr><th>Level:</th><td><?php echo $rubric['level']; ?> - <?php echo REPERTORY_LEVELS[$rubric['level']] ?? 'Rubric'; ?></td></tr>
                        <tr><th>Chapter:</th><td><?php echo escape($rubric['chapter_name']); ?></td></tr>
                        <tr><th>Created:</th><td><?php echo date('d-m-Y', strtotime($rubric['created_at'])); ?></td></tr>
                        <tr><th>Last Updated:</th><td><?php echo date('d-m-Y', strtotime($rubric['updated_at'])); ?></td></tr>
                    </table>
                </div>
                
                <!-- Similar Rubrics -->
                <?php if(!empty($similarRubrics)): ?>
                <div class="rubric-card">
                    <h6><i class="fas fa-link"></i> Similar Rubrics</h6>
                    <div class="list-group">
                        <?php foreach($similarRubrics as $similar): ?>
                            <a href="rubric.php?id=<?php echo $similar['id']; ?>" class="list-group-item list-group-item-action">
                                <?php echo escape($similar['rubric_name']); ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Actions -->
                <div class="rubric-card">
                    <h6><i class="fas fa-tools"></i> Actions</h6>
                    <button class="btn btn-success w-100 mb-2" onclick="window.location.href='../cases/new.php?rubric_id=<?php echo $rubricId; ?>'">
                        <i class="fas fa-plus-circle"></i> Add to New Case
                    </button>
                    <button class="btn btn-info w-100" onclick="window.print()">
                        <i class="fas fa-print"></i> Print Rubric
                    </button>
                </div>
            </div>
        </div>
    </div>
</body>
</html>