<?php
/**
 * AI Remedy Suggestions
 * Get AI-powered remedy recommendations based on symptoms
 */

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

requireLogin();

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

// Get top remedies from repertorization if symptoms provided
$suggestions = [];
$repertorizationResults = null;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header('Content-Type: application/json');
    
    $symptoms = $_POST['symptoms'] ?? '';
    $rubricIds = $_POST['rubric_ids'] ?? [];
    
    if (empty($symptoms) && empty($rubricIds)) {
        echo json_encode(['success' => false, 'error' => 'Please provide symptoms or select rubrics']);
        exit;
    }
    
    // Get repertorization results if rubric IDs provided
    if (!empty($rubricIds)) {
        $rubricsWithWeights = [];
        foreach ($rubricIds as $id) {
            $rubricsWithWeights[$id] = ['weight' => 1];
        }
        $scores = repertorize($rubricsWithWeights);
        $repertorizationResults = array_slice($scores, 0, 10, true);
    }
    
    // Get AI suggestions
    $aiResult = getRemedySuggestionAI(['symptoms' => $symptoms, 'rubrics' => $rubricIds], array_keys($repertorizationResults ?? []));
    
    // Save to history
    $stmt = $pdo->prepare("INSERT INTO ai_remedy_suggestions (user_id, symptoms, suggestion_result, created_at) 
                          VALUES (?, ?, ?, NOW())");
    $stmt->execute([$userId, $symptoms, json_encode($aiResult)]);
    
    echo json_encode([
        'success' => true,
        'ai_suggestion' => $aiResult,
        'repertorization' => $repertorizationResults ? array_values($repertorizationResults) : null
    ]);
    exit;
}

// Get remedy list for dropdown
$remedies = $pdo->query("SELECT id, name FROM remedies ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Remedy Suggestions</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);
        }
        .card-custom {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .remedy-card {
            border-left: 4px solid #2ecc71;
            transition: all 0.2s;
        }
        .remedy-card:hover { transform: translateX(5px); }
        @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="suggest-remedy.php"><i class="fas fa-lightbulb"></i> <span>Remedy Suggestions</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-lightbulb"></i> AI Remedy Suggestions</h4>
        </div>
        
        <div class="row">
            <div class="col-md-5">
                <div class="card-custom">
                    <h5><i class="fas fa-notes-medical"></i> Enter Symptoms</h5>
                    <form id="suggestionForm">
                        <div class="mb-3">
                            <label class="form-label">Symptoms Description</label>
                            <textarea name="symptoms" id="symptoms" class="form-control" rows="8" 
                                      placeholder="Describe the case in detail...&#10;&#10;Example:&#10;Patient has anxiety about future, worse at night.&#10;Digestive issues with bloating after eating.&#10;Craves sweets and warm food." required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Or Select Rubrics (Optional)</label>
                            <select name="rubric_ids[]" id="rubricSelect" class="form-control" multiple>
                                <!-- Will be populated via AJAX -->
                            </select>
                            <small class="text-muted">Select relevant rubrics for repertorization alongside AI analysis</small>
                        </div>
                        <button type="submit" class="btn btn-primary w-100" id="suggestBtn">
                            <i class="fas fa-magic"></i> Get Suggestions
                        </button>
                    </form>
                </div>
            </div>
            
            <div class="col-md-7">
                <div class="card-custom">
                    <h5><i class="fas fa-chart-line"></i> Suggestions</h5>
                    <div id="results">
                        <p class="text-muted text-center mt-5">
                            <i class="fas fa-lightbulb fa-3x mb-3 d-block"></i>
                            Enter symptoms to get AI-powered remedy suggestions.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </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>
        $('#rubricSelect').select2({
            ajax: {
                url: '../../api/search-rubrics.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return { query: params.term };
                },
                processResults: function(data) {
                    return { results: data.results.map(r => ({ id: r.id, text: r.full_path })) };
                }
            },
            placeholder: 'Search rubrics...',
            allowClear: true
        });
        
        $('#suggestionForm').on('submit', function(e) {
            e.preventDefault();
            
            const symptoms = $('#symptoms').val();
            const rubricIds = $('#rubricSelect').val() || [];
            
            if (!symptoms.trim() && rubricIds.length === 0) {
                alert('Please enter symptoms or select rubrics');
                return;
            }
            
            $('#suggestBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Analyzing...');
            $('#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: 'suggest-remedy.php',
                method: 'POST',
                data: {
                    symptoms: symptoms,
                    rubric_ids: rubricIds
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        let html = '';
                        
                        // AI Suggestion
                        if (response.ai_suggestion && response.ai_suggestion.suggested_remedy) {
                            html += `<div class="alert alert-success">
                                        <h5><i class="fas fa-robot"></i> AI Recommended Remedy</h5>
                                        <h3 class="text-success">${response.ai_suggestion.suggested_remedy}</h3>
                                        <p><strong>Confidence:</strong> ${response.ai_suggestion.confidence || 'Medium'}</p>
                                        <p><strong>Reasoning:</strong> ${response.ai_suggestion.reasoning || 'Based on symptom analysis'}</p>
                                        <p><strong>Suggested Potency:</strong> ${response.ai_suggestion.potency || '30C'}</p>
                                        <a href="../materia-medica/view.php?name=${encodeURIComponent(response.ai_suggestion.suggested_remedy)}" class="btn btn-sm btn-info" target="_blank">View Materia Medica</a>
                                        <a href="../cases/new.php?remedy=${encodeURIComponent(response.ai_suggestion.suggested_remedy)}" class="btn btn-sm btn-success">Create Case</a>
                                    </div>`;
                        }
                        
                        // Repertorization Results
                        if (response.repertorization && response.repertorization.length > 0) {
                            html += `<div class="mt-3">
                                        <h5><i class="fas fa-chart-bar"></i> Repertorization Results</h5>
                                        <div class="list-group">
                                            ${response.repertorization.map((r, i) => `
                                                <div class="list-group-item d-flex justify-content-between align-items-center">
                                                    <div>
                                                        <strong>${r.name}</strong>
                                                        <small class="text-muted ms-2">Score: ${r.score}</small>
                                                    </div>
                                                    <a href="../materia-medica/view.php?name=${encodeURIComponent(r.name)}" class="btn btn-sm btn-outline-info" target="_blank">View</a>
                                                </div>
                                            `).join('')}
                                        </div>
                                    </div>`;
                        }
                        
                        $('#results').html(html || '<div class="alert alert-info">No suggestions generated</div>');
                    } else {
                        $('#results').html(`<div class="alert alert-danger">${response.error || 'Failed to get suggestions'}</div>`);
                    }
                },
                error: function() {
                    $('#results').html('<div class="alert alert-danger">Connection error. Please try again.</div>');
                },
                complete: function() {
                    $('#suggestBtn').prop('disabled', false).html('<i class="fas fa-magic"></i> Get Suggestions');
                }
            });
        });
    </script>
</body>
</html>