<?php
/**
 * Compare Two Rubrics
 * Compare remedies between two rubrics
 */

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

requireLogin();

$pdo = getDB();
$rubric1Id = (int)($_GET['rubric1'] ?? 0);
$rubric2Id = (int)($_GET['rubric2'] ?? 0);
$comparison = null;

if ($rubric1Id && $rubric2Id) {
    $remedies1 = getRubricRemedies($rubric1Id);
    $remedies2 = getRubricRemedies($rubric2Id);
    
    // Create associative arrays
    $remedies1Assoc = [];
    foreach ($remedies1 as $r) {
        $remedies1Assoc[$r['name']] = $r['grade'];
    }
    $remedies2Assoc = [];
    foreach ($remedies2 as $r) {
        $remedies2Assoc[$r['name']] = $r['grade'];
    }
    
    $common = [];
    $onlyIn1 = [];
    $onlyIn2 = [];
    
    foreach ($remedies1Assoc as $name => $grade) {
        if (isset($remedies2Assoc[$name])) {
            $common[] = ['name' => $name, 'grade1' => $grade, 'grade2' => $remedies2Assoc[$name]];
        } else {
            $onlyIn1[] = ['name' => $name, 'grade' => $grade];
        }
    }
    
    foreach ($remedies2Assoc as $name => $grade) {
        if (!isset($remedies1Assoc[$name])) {
            $onlyIn2[] = ['name' => $name, 'grade' => $grade];
        }
    }
    
    // Sort by grade (higher first)
    usort($common, function($a, $b) { return $b['grade1'] - $a['grade1']; });
    usort($onlyIn1, function($a, $b) { return $b['grade'] - $a['grade']; });
    usort($onlyIn2, function($a, $b) { return $b['grade'] - $a['grade']; });
    
    // Get rubric details
    $rubric1 = getRubric($rubric1Id);
    $rubric2 = getRubric($rubric2Id);
    
    $comparison = [
        'rubric1' => $rubric1,
        'rubric2' => $rubric2,
        'common' => $common,
        'onlyIn1' => $onlyIn1,
        'onlyIn2' => $onlyIn2,
        'count1' => count($remedies1),
        'count2' => count($remedies2)
    ];
}

// Get all rubrics for dropdown (limited to level 3+ for meaningful comparison)
$rubrics = $pdo->query("SELECT id, full_path, rubric_name, level 
                       FROM rubrics 
                       WHERE level >= 2 
                       ORDER BY full_path 
                       LIMIT 500")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Compare Rubrics - Repertory</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;
        }
        .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);
        }
        .compare-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .remedy-item { padding: 5px 0; border-bottom: 1px solid #eee; }
        .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: 28px;
            height: 28px;
            line-height: 28px;
            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; }
        .grade-2-badge { background: #bbdefb; color: #1565c0; font-style: italic; }
        .grade-1-badge { background: #e0e0e0; }
        .comparison-stats {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
        }
        @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="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">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-chart-line"></i> Compare Rubrics</h4>
                <a href="index.php" class="btn btn-secondary btn-sm">Back to Browser</a>
            </div>
        </div>
        
        <!-- Selection Form -->
        <div class="compare-card">
            <form method="GET" action="">
                <div class="row">
                    <div class="col-md-5">
                        <label class="form-label">Rubric 1</label>
                        <select name="rubric1" class="form-control rubric-select" required>
                            <option value="">Select Rubric</option>
                            <?php foreach($rubrics as $r): ?>
                                <option value="<?php echo $r['id']; ?>" <?php echo $rubric1Id == $r['id'] ? 'selected' : ''; ?>>
                                    <?php echo str_repeat('--', $r['level'] - 1) . ' ' . escape($r['full_path']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Rubric 2</label>
                        <select name="rubric2" class="form-control rubric-select" required>
                            <option value="">Select Rubric</option>
                            <?php foreach($rubrics as $r): ?>
                                <option value="<?php echo $r['id']; ?>" <?php echo $rubric2Id == $r['id'] ? 'selected' : ''; ?>>
                                    <?php echo str_repeat('--', $r['level'] - 1) . ' ' . escape($r['full_path']); ?>
                                </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>
            </form>
        </div>
        
        <?php if ($comparison): ?>
            <!-- Comparison Results -->
            <div class="row">
                <div class="col-md-6">
                    <div class="compare-card">
                        <h5><i class="fas fa-book"></i> <?php echo escape($comparison['rubric1']['full_path']); ?></h5>
                        <div class="comparison-stats mb-3">
                            <strong><?php echo $comparison['count1']; ?></strong> remedies
                        </div>
                        <div class="list-group">
                            <?php foreach($comparison['onlyIn1'] as $rem): ?>
                                <div class="remedy-item d-flex justify-content-between align-items-center">
                                    <span class="grade-<?php echo $rem['grade']; ?>"><?php echo escape($rem['name']); ?></span>
                                    <span class="grade-badge grade-<?php echo $rem['grade']; ?>-badge"><?php echo $rem['grade']; ?></span>
                                </div>
                            <?php endforeach; ?>
                            <?php if(empty($comparison['onlyIn1'])): ?>
                                <p class="text-muted text-center">No unique remedies</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="compare-card">
                        <h5><i class="fas fa-book"></i> <?php echo escape($comparison['rubric2']['full_path']); ?></h5>
                        <div class="comparison-stats mb-3">
                            <strong><?php echo $comparison['count2']; ?></strong> remedies
                        </div>
                        <div class="list-group">
                            <?php foreach($comparison['onlyIn2'] as $rem): ?>
                                <div class="remedy-item d-flex justify-content-between align-items-center">
                                    <span class="grade-<?php echo $rem['grade']; ?>"><?php echo escape($rem['name']); ?></span>
                                    <span class="grade-badge grade-<?php echo $rem['grade']; ?>-badge"><?php echo $rem['grade']; ?></span>
                                </div>
                            <?php endforeach; ?>
                            <?php if(empty($comparison['onlyIn2'])): ?>
                                <p class="text-muted text-center">No unique remedies</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Common Remedies -->
            <div class="compare-card">
                <h5><i class="fas fa-handshake"></i> Common Remedies (<?php echo count($comparison['common']); ?>)</h5>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>Remedy</th>
                                <th width="100">Grade in Rubric 1</th>
                                <th width="100">Grade in Rubric 2</th>
                                <th>Difference</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($comparison['common'] as $rem): ?>
                            <tr>
                                <td><span class="grade-<?php echo max($rem['grade1'], $rem['grade2']); ?>"><?php echo escape($rem['name']); ?></span></td>
                                <td class="text-center"><span class="grade-badge grade-<?php echo $rem['grade1']; ?>-badge"><?php echo $rem['grade1']; ?></span></td>
                                <td class="text-center"><span class="grade-badge grade-<?php echo $rem['grade2']; ?>-badge"><?php echo $rem['grade2']; ?></span></td>
                                <td>
                                    <?php if($rem['grade1'] > $rem['grade2']): ?>
                                        <span class="text-success">Stronger in Rubric 1</span>
                                    <?php elseif($rem['grade2'] > $rem['grade1']): ?>
                                        <span class="text-info">Stronger in Rubric 2</span>
                                    <?php else: ?>
                                        <span class="text-muted">Equal</span>
                                    <?php endif; ?>
                                 </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if(empty($comparison['common'])): ?>
                                <tr><td colspan="4" class="text-center text-muted">No common remedies</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- AI Analysis (Optional) -->
            <div class="compare-card">
                <h5><i class="fas fa-robot"></i> AI Analysis</h5>
                <div id="aiAnalysis">
                    <button class="btn btn-outline-primary" onclick="getAIAnalysis()">
                        <i class="fas fa-brain"></i> Get AI Comparison
                    </button>
                </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 rubrics from the dropdowns above to compare their remedies.</p>
                    <small>You can compare rubrics from different chapters to find remedy relationships.</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>
        $(document).ready(function() {
            $('.rubric-select').select2({
                placeholder: 'Search and select rubric...',
                allowClear: true,
                width: '100%'
            });
        });
        
        function getAIAnalysis() {
            $('#aiAnalysis').html('<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Analyzing...</div>');
            
            $.ajax({
                url: '../../api/ai-compare.php',
                method: 'POST',
                data: {
                    rubric1: <?php echo $rubric1Id; ?>,
                    rubric2: <?php echo $rubric2Id; ?>
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $('#aiAnalysis').html('<div class="alert alert-info">' + response.analysis + '</div>');
                    } else {
                        $('#aiAnalysis').html('<div class="alert alert-warning">AI analysis not available. Please configure API keys in admin panel.</div>');
                    }
                },
                error: function() {
                    $('#aiAnalysis').html('<div class="alert alert-danger">Error connecting to AI service</div>');
                }
            });
        }
    </script>
</body>
</html>