<?php
/**
 * AI Extract Rubrics
 * Extract potential rubrics from case text using AI
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$extractedRubrics = [];

// Handle extraction request
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('Content-Type: application/json');
    
    $caseText = $_POST['case_text'] ?? '';
    
    if (empty($caseText)) {
        echo json_encode(['success' => false, 'error' => 'Case text is required']);
        exit;
    }
    
    // Get AI extraction
    $aiRubrics = extractRubricsWithAI($caseText);
    
    // Match with actual rubrics in database
    $matchedRubrics = [];
    foreach ($aiRubrics as $aiRubric) {
        $searchTerm = $aiRubric['rubric'] ?? '';
        if (!empty($searchTerm)) {
            $stmt = $pdo->prepare("SELECT id, rubric_name, full_path, level FROM rubrics WHERE full_path LIKE ? OR rubric_name LIKE ? LIMIT 1");
            $searchLike = "%$searchTerm%";
            $stmt->execute([$searchLike, $searchLike]);
            $matched = $stmt->fetch();
            if ($matched) {
                $matched['relevance'] = $aiRubric['relevance'] ?? 'medium';
                $matched['reason'] = $aiRubric['reason'] ?? '';
                $matchedRubrics[] = $matched;
            }
        }
    }
    
    // Save to history
    $stmt = $pdo->prepare("INSERT INTO ai_rubric_extractions (user_id, case_text, extracted_rubrics, created_at) 
                          VALUES (?, ?, ?, NOW())");
    $stmt->execute([$userId, $caseText, json_encode($matchedRubrics)]);
    
    echo json_encode(['success' => true, 'rubrics' => $matchedRubrics]);
    exit;
}

// Get recent extractions
$stmt = $pdo->prepare("SELECT * FROM ai_rubric_extractions WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$userId]);
$recentExtractions = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Rubric Extraction</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);
        }
        .card-custom {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .rubric-item {
            padding: 12px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: all 0.2s;
        }
        .rubric-item:hover { background: #e8f5e9; transform: translateX(5px); }
        .relevance-high { border-left: 4px solid #28a745; }
        .relevance-medium { border-left: 4px solid #ffc107; }
        .relevance-low { border-left: 4px solid #dc3545; }
        @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" href="../materia-medica/index.php"><i class="fas fa-capsules"></i> <span>Materia Medica</span></a>
            <a class="nav-link active" href="analyze.php"><i class="fas fa-robot"></i> <span>AI Analysis</span></a>
            <a class="nav-link" href="extract-rubrics.php"><i class="fas fa-magic"></i> <span>Extract Rubrics</span></a>
            <a class="nav-link" href="history.php"><i class="fas fa-history"></i> <span>History</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">
            <h4 class="mb-0"><i class="fas fa-magic"></i> AI Rubric Extraction</h4>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card-custom">
                    <h5><i class="fas fa-notes-medical"></i> Enter Case Text</h5>
                    <form id="extractForm">
                        <div class="mb-3">
                            <textarea name="case_text" id="caseText" class="form-control" rows="12" 
                                      placeholder="Paste patient case text here...&#10;&#10;The AI will analyze and suggest relevant Kent's Repertory rubrics." required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary w-100" id="extractBtn">
                            <i class="fas fa-magic"></i> Extract Rubrics
                        </button>
                    </form>
                </div>
                
                <div class="card-custom">
                    <h5><i class="fas fa-history"></i> Recent Extractions</h5>
                    <div class="list-group">
                        <?php foreach($recentExtractions as $ext): ?>
                            <a href="#" class="list-group-item list-group-item-action load-past" data-text="<?php echo htmlspecialchars($ext['case_text']); ?>">
                                <small class="text-muted"><?php echo date('d-m-Y H:i', strtotime($ext['created_at'])); ?></small>
                                <div class="small text-truncate"><?php echo substr($ext['case_text'], 0, 100); ?>...</div>
                            </a>
                        <?php endforeach; ?>
                        <?php if(empty($recentExtractions)): ?>
                            <div class="text-muted text-center py-3">No recent extractions</div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card-custom">
                    <h5><i class="fas fa-tree"></i> Extracted Rubrics</h5>
                    <div id="results">
                        <p class="text-muted text-center mt-5">
                            <i class="fas fa-magic fa-3x mb-3 d-block"></i>
                            Enter case text to extract potential rubrics.
                        </p>
                    </div>
                    <div class="mt-3 text-end">
                        <button class="btn btn-sm btn-success" onclick="selectAllRubrics()" style="display: none;" id="selectAllBtn">
                            <i class="fas fa-check-double"></i> Select All for Case
                        </button>
                    </div>
                </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>
        let extractedRubrics = [];
        
        $('#extractForm').on('submit', function(e) {
            e.preventDefault();
            
            const caseText = $('#caseText').val();
            if (!caseText.trim()) {
                alert('Please enter case text');
                return;
            }
            
            $('#extractBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Extracting...');
            $('#results').html('<div class="text-center p-5"><div class="spinner-border text-primary"></div><p class="mt-3">AI is analyzing...</p></div>');
            
            $.ajax({
                url: 'extract-rubrics.php',
                method: 'POST',
                data: { case_text: caseText },
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.rubrics.length > 0) {
                        extractedRubrics = response.rubrics;
                        let html = '<div class="list-group">';
                        response.rubrics.forEach((rubric, i) => {
                            html += `<div class="list-group-item rubric-item relevance-${rubric.relevance}" data-id="${rubric.id}" data-path="${rubric.full_path}">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <strong>${rubric.full_path}</strong>
                                                <div class="mt-1">
                                                    <span class="badge bg-${rubric.relevance === 'high' ? 'success' : (rubric.relevance === 'medium' ? 'warning' : 'danger')}">${rubric.relevance}</span>
                                                    <span class="badge bg-secondary">Level ${rubric.level}</span>
                                                </div>
                                                ${rubric.reason ? `<small class="text-muted d-block mt-1">${rubric.reason}</small>` : ''}
                                            </div>
                                            <div class="form-check">
                                                <input class="form-check-input rubric-checkbox" type="checkbox" value="${rubric.id}" data-path="${rubric.full_path}">
                                            </div>
                                        </div>
                                    </div>`;
                        });
                        html += '</div>';
                        $('#results').html(html);
                        $('#selectAllBtn').show();
                    } else {
                        $('#results').html('<div class="alert alert-info">No rubrics extracted. Try providing more detailed case description.</div>');
                    }
                },
                error: function() {
                    $('#results').html('<div class="alert alert-danger">Connection error. Please try again.</div>');
                },
                complete: function() {
                    $('#extractBtn').prop('disabled', false).html('<i class="fas fa-magic"></i> Extract Rubrics');
                }
            });
        });
        
        function selectAllRubrics() {
            const selected = [];
            $('.rubric-checkbox:checked').each(function() {
                selected.push($(this).val());
            });
            
            if (selected.length === 0) {
                alert('No rubrics selected');
                return;
            }
            
            // Store in session and redirect to new case
            $.post('../../api/save-temp-rubrics.php', { rubric_ids: selected }, function() {
                window.location.href = '../cases/new.php';
            });
        }
        
        $('.load-past').on('click', function(e) {
            e.preventDefault();
            $('#caseText').val($(this).data('text'));
            $('#extractForm').submit();
        });
        
        $(document).on('change', '.rubric-checkbox', function() {
            const count = $('.rubric-checkbox:checked').length;
            $('#selectAllBtn').html(`<i class="fas fa-check-double"></i> Add ${count} Rubric(s) to Case`);
        });
    </script>
</body>
</html>