<?php
/**
 * Compare Remedies
 * Compare two remedies side by side
 */

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

requireLogin();

$pdo = getDB();
$remedy1Id = (int)($_GET['remedy1'] ?? 0);
$remedy2Id = (int)($_GET['remedy2'] ?? 0);
$singleRemedy = (int)($_GET['remedy'] ?? 0);

if ($singleRemedy && !$remedy1Id) {
    $remedy1Id = $singleRemedy;
}

// Get all remedies for dropdown
$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();

$comparison = null;
$aiAnalysis = null;

if ($remedy1Id && $remedy2Id) {
    // Get remedy details
    $stmt = $pdo->prepare("SELECT * FROM remedies WHERE id = ?");
    $stmt->execute([$remedy1Id]);
    $remedy1 = $stmt->fetch();
    $stmt->execute([$remedy2Id]);
    $remedy2 = $stmt->fetch();
    
    if ($remedy1 && $remedy2) {
        // Get rubric counts
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM rubric_remedy WHERE remedy_id = ?");
        $stmt->execute([$remedy1Id]);
        $rubricCount1 = $stmt->fetch()['count'];
        $stmt->execute([$remedy2Id]);
        $rubricCount2 = $stmt->fetch()['count'];
        
        // Get prescription counts
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM cases WHERE prescribed_remedy_id = ?");
        $stmt->execute([$remedy1Id]);
        $prescCount1 = $stmt->fetch()['count'];
        $stmt->execute([$remedy2Id]);
        $prescCount2 = $stmt->fetch()['count'];
        
        // Get grade distribution
        $stmt = $pdo->prepare("SELECT grade, COUNT(*) as count FROM rubric_remedy WHERE remedy_id = ? GROUP BY grade");
        $stmt->execute([$remedy1Id]);
        $grades1 = $stmt->fetchAll();
        $stmt->execute([$remedy2Id]);
        $grades2 = $stmt->fetchAll();
        
        $gradeMap1 = [1=>0,2=>0,3=>0,4=>0];
        $gradeMap2 = [1=>0,2=>0,3=>0,4=>0];
        foreach($grades1 as $g) $gradeMap1[$g['grade']] = $g['count'];
        foreach($grades2 as $g) $gradeMap2[$g['grade']] = $g['count'];
        
        // Parse modalities
        $modalities1 = json_decode($remedy1['modalities'], true);
        $modalities2 = json_decode($remedy2['modalities'], true);
        
        // Get common rubrics
        $stmt = $pdo->prepare("SELECT r.full_path, rr1.grade as grade1, rr2.grade as grade2
                              FROM rubric_remedy rr1
                              JOIN rubric_remedy rr2 ON rr1.rubric_id = rr2.rubric_id
                              JOIN rubrics r ON rr1.rubric_id = r.id
                              WHERE rr1.remedy_id = ? AND rr2.remedy_id = ?");
        $stmt->execute([$remedy1Id, $remedy2Id]);
        $commonRubrics = $stmt->fetchAll();
        
        $comparison = [
            'remedy1' => $remedy1,
            'remedy2' => $remedy2,
            'rubricCount1' => $rubricCount1,
            'rubricCount2' => $rubricCount2,
            'prescCount1' => $prescCount1,
            'prescCount2' => $prescCount2,
            'grades1' => $gradeMap1,
            'grades2' => $gradeMap2,
            'modalities1' => $modalities1,
            'modalities2' => $modalities2,
            'commonRubrics' => $commonRubrics
        ];
        
        // Get AI analysis if enabled
        if (USE_AI) {
            $aiAnalysis = compareRemediesAI($remedy1['name'], $remedy2['name']);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compare Remedies - 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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.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;
            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);
        }
        .compare-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            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: 10px;
            padding: 20px;
            text-align: center;
            height: 100%;
        }
        .remedy-header h3 { margin-bottom: 5px; }
        .stat-box {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            text-align: center;
        }
        .modality-box {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 10px;
        }
        .grade-badge {
            display: inline-block;
            width: 30px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border-radius: 50%;
            font-weight: bold;
            font-size: 12px;
        }
        .grade-4-badge { background: #ffeb3b; text-decoration: underline; }
        .grade-3-badge { background: #ffcdd2; color: #c62828; font-weight: bold; }
        .grade-2-badge { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1-badge { background: #e0e0e0; }
        .common-rubric-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            font-size: 13px;
        }
        .common-rubric-item:hover { background: #f8f9fa; }
        @media (max-width: 768px) { 
            .sidebar { width: 70px; } 
            .sidebar .nav-link span { display: none; } 
            .main-content { margin-left: 70px; } 
        }
        @media print {
            .sidebar, .top-navbar, .no-print { display: none !important; }
            .main-content { margin-left: 0; }
        }
    </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="compare.php"><i class="fas fa-chart-line"></i> <span>Compare</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-chart-line"></i> Compare Remedies</h4>
                <button onclick="window.print()" class="btn btn-secondary btn-sm">
                    <i class="fas fa-print"></i> Print Comparison
                </button>
            </div>
        </div>
        
        <!-- Selection Form -->
        <div class="compare-card no-print">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-5">
                        <label class="form-label">Remedy 1</label>
                        <select name="remedy1" class="form-control remedy-select" required>
                            <option value="">Select Remedy</option>
                            <?php foreach($remedies as $r): ?>
                                <option value="<?php echo $r['id']; ?>" <?php echo $remedy1Id == $r['id'] ? 'selected' : ''; ?>>
                                    <?php echo escape($r['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Remedy 2</label>
                        <select name="remedy2" class="form-control remedy-select" required>
                            <option value="">Select Remedy</option>
                            <?php foreach($remedies as $r): ?>
                                <option value="<?php echo $r['id']; ?>" <?php echo $remedy2Id == $r['id'] ? 'selected' : ''; ?>>
                                    <?php echo escape($r['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary w-100">Compare</button>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-md-12">
                        <small class="text-muted">Tip: You can also click "Compare" from any remedy page to auto-fill the first remedy.</small>
                    </div>
                </div>
            </form>
        </div>
        
        <?php if ($comparison): ?>
            <!-- Comparison Header -->
            <div class="row">
                <div class="col-md-6">
                    <div class="remedy-header">
                        <h3><?php echo escape($comparison['remedy1']['name']); ?></h3>
                        <?php if($comparison['remedy1']['abbreviation']): ?>
                            <small><?php echo escape($comparison['remedy1']['abbreviation']); ?></small>
                        <?php endif; ?>
                        <div class="mt-2">
                            <a href="view.php?id=<?php echo $comparison['remedy1']['id']; ?>" class="btn btn-light btn-sm" target="_blank">
                                <i class="fas fa-eye"></i> Full Monograph
                            </a>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="remedy-header">
                        <h3><?php echo escape($comparison['remedy2']['name']); ?></h3>
                        <?php if($comparison['remedy2']['abbreviation']): ?>
                            <small><?php echo escape($comparison['remedy2']['abbreviation']); ?></small>
                        <?php endif; ?>
                        <div class="mt-2">
                            <a href="view.php?id=<?php echo $comparison['remedy2']['id']; ?>" class="btn btn-light btn-sm" target="_blank">
                                <i class="fas fa-eye"></i> Full Monograph
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Statistics Comparison -->
            <div class="compare-card">
                <h5><i class="fas fa-chart-bar"></i> Statistics Overview</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="stat-box">
                            <strong>Rubrics:</strong> <?php echo $comparison['rubricCount1']; ?><br>
                            <strong>Prescriptions:</strong> <?php echo $comparison['prescCount1']; ?>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="stat-box">
                            <strong>Rubrics:</strong> <?php echo $comparison['rubricCount2']; ?><br>
                            <strong>Prescriptions:</strong> <?php echo $comparison['prescCount2']; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Grade Distribution -->
            <div class="compare-card">
                <h5><i class="fas fa-palette"></i> Grade Distribution</h5>
                <div class="row">
                    <div class="col-md-6">
                        <div class="d-flex justify-content-around">
                            <div><span class="grade-badge grade-4-badge">4</span> <?php echo $comparison['grades1'][4]; ?></div>
                            <div><span class="grade-badge grade-3-badge">3</span> <?php echo $comparison['grades1'][3]; ?></div>
                            <div><span class="grade-badge grade-2-badge">2</span> <?php echo $comparison['grades1'][2]; ?></div>
                            <div><span class="grade-badge grade-1-badge">1</span> <?php echo $comparison['grades1'][1]; ?></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="d-flex justify-content-around">
                            <div><span class="grade-badge grade-4-badge">4</span> <?php echo $comparison['grades2'][4]; ?></div>
                            <div><span class="grade-badge grade-3-badge">3</span> <?php echo $comparison['grades2'][3]; ?></div>
                            <div><span class="grade-badge grade-2-badge">2</span> <?php echo $comparison['grades2'][2]; ?></div>
                            <div><span class="grade-badge grade-1-badge">1</span> <?php echo $comparison['grades2'][1]; ?></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Modalities Comparison -->
            <div class="compare-card">
                <h5><i class="fas fa-chart-line"></i> Modalities</h5>
                <div class="row">
                    <div class="col-md-6">
                        <?php if(!empty($comparison['modalities1']['better'])): ?>
                            <div class="modality-box">
                                <strong class="text-success">Better:</strong>
                                <ul class="mb-0 mt-1">
                                    <?php foreach($comparison['modalities1']['better'] as $m): ?>
                                        <li><?php echo escape($m); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        <?php if(!empty($comparison['modalities1']['worse'])): ?>
                            <div class="modality-box">
                                <strong class="text-danger">Worse:</strong>
                                <ul class="mb-0 mt-1">
                                    <?php foreach($comparison['modalities1']['worse'] as $m): ?>
                                        <li><?php echo escape($m); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6">
                        <?php if(!empty($comparison['modalities2']['better'])): ?>
                            <div class="modality-box">
                                <strong class="text-success">Better:</strong>
                                <ul class="mb-0 mt-1">
                                    <?php foreach($comparison['modalities2']['better'] as $m): ?>
                                        <li><?php echo escape($m); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        <?php if(!empty($comparison['modalities2']['worse'])): ?>
                            <div class="modality-box">
                                <strong class="text-danger">Worse:</strong>
                                <ul class="mb-0 mt-1">
                                    <?php foreach($comparison['modalities2']['worse'] as $m): ?>
                                        <li><?php echo escape($m); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Common Rubrics -->
            <div class="compare-card">
                <h5><i class="fas fa-handshake"></i> Common Rubrics (<?php echo count($comparison['commonRubrics']); ?>)</h5>
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr><th>Rubric</th><th width="80">Grade in <?php echo escape($comparison['remedy1']['name']); ?></th><th width="80">Grade in <?php echo escape($comparison['remedy2']['name']); ?></th></tr>
                        </thead>
                        <tbody>
                            <?php if(empty($comparison['commonRubrics'])): ?>
                                <td><td colspan="3" class="text-center text-muted">No common rubrics found</td></tr>
                            <?php else: ?>
                                <?php foreach($comparison['commonRubrics'] as $rubric): ?>
                                    <tr>
                                        <td><a href="../repertory/rubric.php?id=<?php echo $rubric['id']; ?>" target="_blank"><?php echo escape($rubric['full_path']); ?></a></td>
                                        <td class="text-center"><span class="grade-badge grade-<?php echo $rubric['grade1']; ?>-badge"><?php echo $rubric['grade1']; ?></span></td>
                                        <td class="text-center"><span class="grade-badge grade-<?php echo $rubric['grade2']; ?>-badge"><?php echo $rubric['grade2']; ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- AI Analysis -->
            <?php if($aiAnalysis): ?>
            <div class="compare-card">
                <h5><i class="fas fa-robot"></i> AI Analysis</h5>
                <div class="alert alert-info">
                    <?php echo nl2br(escape($aiAnalysis)); ?>
                </div>
                <small class="text-muted">AI-generated comparison. Use clinically.</small>
            </div>
            <?php endif; ?>
            
            <!-- Quick Actions -->
            <div class="compare-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 $comparison['remedy1']['id']; ?>" class="btn btn-success w-100 mb-2">
                            <i class="fas fa-plus-circle"></i> New Case with <?php echo escape($comparison['remedy1']['name']); ?>
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="../cases/new.php?remedy=<?php echo $comparison['remedy2']['id']; ?>" class="btn btn-success w-100 mb-2">
                            <i class="fas fa-plus-circle"></i> New Case with <?php echo escape($comparison['remedy2']['name']); ?>
                        </a>
                    </div>
                    <div class="col-md-3">
                        <a href="compare.php?remedy1=<?php echo $remedy2Id; ?>&remedy2=<?php echo $remedy1Id; ?>" class="btn btn-info w-100 mb-2">
                            <i class="fas fa-exchange-alt"></i> Swap Remedies
                        </a>
                    </div>
                    <div class="col-md-3">
                        <button onclick="window.print()" class="btn btn-secondary w-100 mb-2">
                            <i class="fas fa-print"></i> Print Comparison
                        </button>
                    </div>
                </div>
            </div>
            
        <?php else: ?>
            <div class="compare-card">
                <div class="text-center text-muted py-5">
                    <i class="fas fa-chart-line fa-3x mb-3"></i>
                    <p>Select two remedies from the dropdowns above to compare them side by side.</p>
                    <small>You can compare remedies to see differences in rubrics, grades, and modalities.</small>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            $('.remedy-select').select2({
                placeholder: 'Search for a remedy...',
                allowClear: true,
                width: '100%'
            });
        });
    </script>
</body>
</html>