<?php
/**
 * View Remedy Details
 * Complete Materia Medica with rubrics and modalities
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/ai-integration.php';

requireLogin();

$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);
$betterModalities = $modalities['better'] ?? [];
$worseModalities = $modalities['worse'] ?? [];

// 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();

// Check if bookmarked
$userId = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT id FROM remedy_bookmarks WHERE user_id = ? AND remedy_id = ?");
$stmt->execute([$userId, $remedy['id']]);
$isBookmarked = $stmt->fetch() ? true : false;

// Get AI summary (cached)
$aiSummary = null;
if (USE_AI) {
    $aiSummary = getRemedySummaryAI($remedy['name']);
}
?>
<!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>
        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);
        }
        .remedy-header {
            background: linear-gradient(135deg, #2ecc71 0%, #27ae60 100%);
            color: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
        }
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .modality-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .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; }
        .grade-1 { background: #e0e0e0; color: #333; }
        .grade-2 { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-3 { background: #ffcdd2; color: #c62828; font-weight: bold; }
        .grade-4 { background: #ffeb3b; font-weight: bold; text-decoration: underline; }
        .materia-medica-content {
            line-height: 1.8;
            font-size: 15px;
        }
        @media print {
            .sidebar, .top-navbar, .no-print { display: none !important; }
            .main-content { margin-left: 0; }
        }
        @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" href="../repertory/index.php"><i class="fas fa-book"></i> <span>Repertory</span></a>
            <a class="nav-link active" href="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><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 no-print">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-capsules"></i> Materia Medica</h4>
                <div>
                    <button onclick="window.print()" class="btn btn-secondary btn-sm">
                        <i class="fas fa-print"></i> Print
                    </button>
                    <button onclick="toggleBookmark(<?php echo $remedy['id']; ?>)" class="btn btn-warning btn-sm">
                        <i class="fas fa-bookmark"></i> <?php echo $isBookmarked ? 'Remove Bookmark' : 'Bookmark'; ?>
                    </button>
                    <a href="compare.php?remedy=<?php echo $remedy['id']; ?>" class="btn btn-info btn-sm">
                        <i class="fas fa-chart-line"></i> Compare
                    </a>
                    <a href="index.php" class="btn btn-secondary btn-sm">Back</a>
                </div>
            </div>
        </div>
        
        <!-- Remedy Header -->
        <div class="remedy-header">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="display-5"><?php echo escape($remedy['name']); ?></h1>
                    <?php if($remedy['abbreviation']): ?>
                        <p class="lead mb-0">Abbreviation: <?php echo escape($remedy['abbreviation']); ?></p>
                    <?php endif; ?>
                </div>
                <div class="text-end">
                    <div><span class="badge bg-light text-dark"><?php echo count($rubrics); ?> Rubrics</span></div>
                    <div><span class="badge bg-light text-dark mt-1"><?php echo $prescriptionStats['total']; ?> Prescriptions</span></div>
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <!-- Materia Medica Text -->
                <?php if($remedy['materia_medica_text']): ?>
                    <div class="info-card">
                        <h5><i class="fas fa-book-open"></i> Materia Medica</h5>
                        <div class="materia-medica-content">
                            <?php echo nl2br(escape($remedy['materia_medica_text'])); ?>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- AI Summary -->
                <?php if($aiSummary): ?>
                    <div class="info-card">
                        <h5><i class="fas fa-robot"></i> AI Summary</h5>
                        <div class="materia-medica-content">
                            <?php echo nl2br(escape($aiSummary)); ?>
                        </div>
                        <small class="text-muted">Generated by AI</small>
                    </div>
                <?php endif; ?>
                
                <!-- Clinical Indications -->
                <?php if($remedy['clinical_indications']): ?>
                    <div class="info-card">
                        <h5><i class="fas fa-stethoscope"></i> Clinical Indications</h5>
                        <p><?php echo nl2br(escape($remedy['clinical_indications'])); ?></p>
                    </div>
                <?php endif; ?>
            </div>
            
            <div class="col-md-4">
                <!-- Modalities -->
                <?php if(!empty($betterModalities) || !empty($worseModalities)): ?>
                    <div class="info-card">
                        <h5><i class="fas fa-chart-line"></i> Modalities</h5>
                        
                        <?php if(!empty($betterModalities)): ?>
                            <div class="modality-card">
                                <h6 class="text-success"><i class="fas fa-arrow-up"></i> Better (Amelioration)</h6>
                                <ul class="mb-0">
                                    <?php foreach($betterModalities as $mod): ?>
                                        <li><?php echo escape($mod); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        
                        <?php if(!empty($worseModalities)): ?>
                            <div class="modality-card">
                                <h6 class="text-danger"><i class="fas fa-arrow-down"></i> Worse (Aggravation)</h6>
                                <ul class="mb-0">
                                    <?php foreach($worseModalities as $mod): ?>
                                        <li><?php echo escape($mod); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                
                <!-- Statistics -->
                <div class="info-card">
                    <h5><i class="fas fa-chart-bar"></i> Statistics</h5>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Total Rubrics:</span>
                        <strong><?php echo count($rubrics); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span>Total Prescriptions:</span>
                        <strong><?php echo $prescriptionStats['total']; ?></strong>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span>Active Prescriptions:</span>
                        <strong><?php echo $prescriptionStats['active']; ?></strong>
                    </div>
                </div>
                
                <!-- Grade Distribution -->
                <div class="info-card">
                    <h5><i class="fas fa-palette"></i> Grade Distribution</h5>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="grade-4 px-2 py-1 rounded">Grade 4</span>
                        <strong><?php echo count($rubricsByGrade[4]); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="grade-3 px-2 py-1 rounded">Grade 3</span>
                        <strong><?php echo count($rubricsByGrade[3]); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between mb-2">
                        <span class="grade-2 px-2 py-1 rounded">Grade 2</span>
                        <strong><?php echo count($rubricsByGrade[2]); ?></strong>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="grade-1 px-2 py-1 rounded">Grade 1</span>
                        <strong><?php echo count($rubricsByGrade[1]); ?></strong>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Rubrics Section -->
        <div class="info-card">
            <h5><i class="fas fa-tree"></i> Rubrics (by Grade)</h5>
            <div class="row">
                <?php for($grade = 4; $grade >= 1; $grade--): ?>
                    <?php if(!empty($rubricsByGrade[$grade])): ?>
                        <div class="col-md-12 mb-3">
                            <h6 class="grade-<?php echo $grade; ?> d-inline-block px-2 py-1 rounded">Grade <?php echo $grade; ?></h6>
                            <div class="mt-2">
                                <?php foreach($rubricsByGrade[$grade] as $rubric): ?>
                                    <a href="../repertory/rubric.php?id=<?php echo $rubric['id']; ?>" 
                                       class="rubric-link grade-<?php echo $grade; ?>" target="_blank">
                                        <?php echo escape($rubric['full_path']); ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endfor; ?>
            </div>
        </div>
        
        <!-- Quick Actions -->
        <div class="info-card no-print">
            <h5><i class="fas fa-tools"></i> Quick Actions</h5>
            <div class="row">
                <div class="col-md-3">
                    <a href="../cases/new.php?remedy=<?php echo $remedy['id']; ?>" class="btn btn-success w-100">
                        <i class="fas fa-plus-circle"></i> New Case with <?php echo escape($remedy['name']); ?>
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="../repertory/search.php?remedy=<?php echo urlencode($remedy['name']); ?>" class="btn btn-info w-100">
                        <i class="fas fa-search"></i> Find in Repertory
                    </a>
                </div>
                <div class="col-md-3">
                    <a href="compare.php?remedy=<?php echo $remedy['id']; ?>" class="btn btn-primary w-100">
                        <i class="fas fa-chart-line"></i> Compare with Another
                    </a>
                </div>
                <div class="col-md-3">
                    <button onclick="window.print()" class="btn btn-secondary w-100">
                        <i class="fas fa-print"></i> Print Monograph
                    </button>
                </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>
        function toggleBookmark(remedyId) {
            $.post('bookmark.php', { action: 'toggle', remedy_id: remedyId }, function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('Failed to update bookmark');
                }
            }, 'json');
        }
    </script>
</body>
</html>