<?php
/**
 * View Remedy Materia Medica
 * Display complete remedy information with formatted Materia Medica
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireAdmin();

$pdo = getDB();
$remedyId = (int)($_GET['id'] ?? 0);
$remedyName = $_GET['name'] ?? '';

// Get remedy details
if ($remedyName) {
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE name = ?");
    $stmt->execute([$remedyName]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE id = ?");
    $stmt->execute([$remedyId]);
}
$remedy = $stmt->fetch();

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

// Parse modalities
$modalities = json_decode($remedy['modalities'], true);

// Get rubrics where this remedy appears with grades
$stmt = $pdo->prepare("SELECT r.id, r.full_path, r.level, rr.grade
                      FROM rubric_remedy rr
                      JOIN rubrics r ON rr.rubric_id = r.id
                      WHERE rr.remedy_id = ?
                      ORDER BY rr.grade DESC, r.full_path");
$stmt->execute([$remedy['id']]);
$rubrics = $stmt->fetchAll();

// Group rubrics by grade
$rubricsByGrade = [
    4 => [], 3 => [], 2 => [], 1 => []
];
foreach ($rubrics as $rubric) {
    $rubricsByGrade[$rubric['grade']][] = $rubric;
}

// Get prescription statistics
$stmt = $pdo->prepare("SELECT COUNT(*) as total, 
                      SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active
                      FROM cases WHERE prescribed_remedy_id = ?");
$stmt->execute([$remedy['id']]);
$prescriptionStats = $stmt->fetch();
?>
<!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($remedy['name']); ?> - Materia Medica</title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.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;
        }
        .materia-medica-content {
            line-height: 1.8;
            font-size: 15px;
        }
        .grade-4 { background: #ffeb3b; font-weight: bold; text-decoration: underline; }
        .grade-3 { background: #ffcdd2; color: #c62828; font-weight: bold; }
        .grade-2 { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1 { background: #e0e0e0; color: #333; }
        .rubric-link {
            text-decoration: none;
            padding: 2px 5px;
            border-radius: 3px;
            display: inline-block;
            margin: 2px;
            font-size: 12px;
        }
        .rubric-link:hover {
            opacity: 0.8;
        }
        @media print {
            .sidebar, .top-navbar, .no-print {
                display: none !important;
            }
            .main-content {
                margin-left: 0 !important;
                padding: 0 !important;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar no-print">
                <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" href="../rubrics/index.php">
                        <i class="fas fa-tree"></i> Rubrics
                    </a>
                    <a class="nav-link active" href="index.php">
                        <i class="fas fa-capsules"></i> Remedies
                    </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 no-print">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-capsules"></i> Materia Medica: <?php echo escape($remedy['name']); ?></h4>
                        <div>
                            <a href="edit.php?id=<?php echo $remedy['id']; ?>" class="btn btn-primary btn-sm">
                                <i class="fas fa-edit"></i> Edit
                            </a>
                            <button onclick="window.print()" class="btn btn-info btn-sm">
                                <i class="fas fa-print"></i> Print
                            </button>
                            <a href="index.php" class="btn btn-secondary btn-sm">
                                <i class="fas fa-arrow-left"></i> Back
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <div class="row">
                        <div class="col-md-8">
                            <!-- Materia Medica Content -->
                            <div class="card">
                                <div class="card-header">
                                    <h3 class="mb-0"><?php echo escape($remedy['name']); ?></h3>
                                    <?php if ($remedy['abbreviation']): ?>
                                        <small class="text-muted">Abbreviation: <?php echo escape($remedy['abbreviation']); ?></small>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body">
                                    <div class="materia-medica-content">
                                        <?php if ($remedy['materia_medica_text']): ?>
                                            <?php echo nl2br(escape($remedy['materia_medica_text'])); ?>
                                        <?php else: ?>
                                            <p class="text-muted">No Materia Medica text available for this remedy.</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Clinical Indications -->
                            <?php if ($remedy['clinical_indications']): ?>
                            <div class="card mt-3">
                                <div class="card-header bg-info text-white">
                                    <h5 class="mb-0"><i class="fas fa-stethoscope"></i> Clinical Indications</h5>
                                </div>
                                <div class="card-body">
                                    <?php echo nl2br(escape($remedy['clinical_indications'])); ?>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Modalities -->
                            <?php if (!empty($modalities['better']) || !empty($modalities['worse'])): ?>
                            <div class="card mt-3">
                                <div class="card-header bg-warning">
                                    <h5 class="mb-0"><i class="fas fa-chart-line"></i> Modalities</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php if (!empty($modalities['better'])): ?>
                                        <div class="col-md-6">
                                            <h6 class="text-success">Better (Amelioration)</h6>
                                            <ul>
                                                <?php foreach ($modalities['better'] as $modality): ?>
                                                    <li><?php echo escape($modality); ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                        <?php endif; ?>
                                        <?php if (!empty($modalities['worse'])): ?>
                                        <div class="col-md-6">
                                            <h6 class="text-danger">Worse (Aggravation)</h6>
                                            <ul>
                                                <?php foreach ($modalities['worse'] as $modality): ?>
                                                    <li><?php echo escape($modality); ?></li>
                                                <?php endforeach; ?>
                                            </ul>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-md-4">
                            <!-- Statistics Card -->
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-chart-bar"></i> Statistics</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-2">
                                        <strong>Total Rubrics:</strong> <?php echo count($rubrics); ?>
                                    </div>
                                    <div class="mb-2">
                                        <strong>Total Prescriptions:</strong> <?php echo $prescriptionStats['total']; ?>
                                    </div>
                                    <div class="mb-2">
                                        <strong>Active Prescriptions:</strong> <?php echo $prescriptionStats['active']; ?>
                                    </div>
                                    <hr>
                                    <div>
                                        <strong>Grade Distribution:</strong><br>
                                        <span class="grade-4 d-inline-block px-2 py-1 rounded">Grade 4: <?php echo count($rubricsByGrade[4]); ?></span><br>
                                        <span class="grade-3 d-inline-block px-2 py-1 rounded mt-1">Grade 3: <?php echo count($rubricsByGrade[3]); ?></span><br>
                                        <span class="grade-2 d-inline-block px-2 py-1 rounded mt-1">Grade 2: <?php echo count($rubricsByGrade[2]); ?></span><br>
                                        <span class="grade-1 d-inline-block px-2 py-1 rounded mt-1">Grade 1: <?php echo count($rubricsByGrade[1]); ?></span>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Rubrics by Grade -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0"><i class="fas fa-tree"></i> Rubrics by Grade</h6>
                                </div>
                                <div class="card-body">
                                    <?php for ($grade = 4; $grade >= 1; $grade--): ?>
                                        <?php if (!empty($rubricsByGrade[$grade])): ?>
                                            <h6 class="mt-2">
                                                <span class="grade-<?php echo $grade; ?> px-2 py-1 rounded">Grade <?php echo $grade; ?></span>
                                            </h6>
                                            <div class="mb-3">
                                                <?php foreach ($rubricsByGrade[$grade] as $rubric): ?>
                                                    <a href="../rubrics/index.php?search=<?php echo urlencode($rubric['full_path']); ?>" 
                                                       class="rubric-link grade-<?php echo $grade; ?>" target="_blank">
                                                        <?php echo escape($rubric['full_path']); ?>
                                                    </a>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    <?php endfor; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>