<?php
/**
 * AI Case Analysis
 * Analyze patient case using AI (Gemini/DeepSeek)
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$analysis = '';
$error = '';
$caseId = (int)($_GET['case_id'] ?? 0);

// Load case data if case_id provided
$caseData = null;
if ($caseId) {
    $stmt = $pdo->prepare("SELECT * FROM cases WHERE id = ? AND user_id = ?");
    $stmt->execute([$caseId, $userId]);
    $caseData = $stmt->fetch();
}

// Handle AJAX analysis request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    $caseText = $_POST['case_text'] ?? '';
    $remedyName = $_POST['remedy_name'] ?? null;
    
    if (empty($caseText)) {
        echo json_encode(['success' => false, 'error' => 'Case text is required']);
        exit;
    }
    
    $result = analyzeCaseWithAI(['chief_complaint' => $caseText], $remedyName);
    
    if ($result['success']) {
        // Save to history
        $stmt = $pdo->prepare("INSERT INTO ai_analysis_history (user_id, case_text, analysis_result, remedy_name, created_at) 
                              VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$userId, $caseText, $result['analysis'], $remedyName]);
        
        echo json_encode(['success' => true, 'analysis' => $result['analysis']]);
    } else {
        echo json_encode(['success' => false, 'error' => $result['error']]);
    }
    exit;
}

// Get AI usage statistics
$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM ai_analysis_history WHERE user_id = ?");
$stmt->execute([$userId]);
$totalAnalyses = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM ai_analysis_history WHERE user_id = ? AND DATE(created_at) = CURDATE()");
$stmt->execute([$userId]);
$todayAnalyses = $stmt->fetch()['total'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Case Analysis - <?php echo APP_NAME; ?></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;
            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);
        }
        .analysis-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .analysis-result {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            min-height: 400px;
            white-space: pre-wrap;
            line-height: 1.6;
        }
        .loading {
            text-align: center;
            padding: 50px;
        }
        .spinner-border {
            width: 3rem;
            height: 3rem;
        }
        @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="history.php"><i class="fas fa-history"></i> <span>History</span></a>
            <a class="nav-link" href="settings.php"><i class="fas fa-cog"></i> <span>AI Settings</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-robot"></i> AI Case Analysis</h4>
        </div>
        
        <div class="row">
            <div class="col-md-6">
                <div class="analysis-card">
                    <h5><i class="fas fa-notes-medical"></i> Case Input</h5>
                    <form id="analysisForm">
                        <div class="mb-3">
                            <label class="form-label">Case Details</label>
                            <textarea name="case_text" id="caseText" class="form-control" rows="12" 
                                      placeholder="Enter patient case details including:&#10;&#10;• Chief complaint&#10;• History&#10;• Physical generals&#10;• Mental/emotional state&#10;• Modalities (better/worse)&#10;• Any other relevant symptoms" required><?php echo $caseData ? htmlspecialchars($caseData['chief_complaint'] . "\n\n" . $caseData['case_history'] . "\n\n" . $caseData['physical_generals'] . "\n\n" . $caseData['mental_emotional'] . "\n\n" . $caseData['modalities']) : ''; ?></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Specific Remedy (Optional)</label>
                            <input type="text" name="remedy_name" id="remedyName" class="form-control" 
                                   placeholder="e.g., Sulphur, Lycopodium, Arsenicum Album">
                            <small class="text-muted">Leave empty for general analysis and remedy suggestion</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Analysis Type</label>
                            <select name="analysis_type" id="analysisType" class="form-control">
                                <option value="full">Full Case Analysis</option>
                                <option value="remedy">Remedy Selection Only</option>
                                <option value="rubrics">Rubric Extraction Only</option>
                            </select>
                        </div>
                        <?php if($caseId): ?>
                            <input type="hidden" name="case_id" value="<?php echo $caseId; ?>">
                        <?php endif; ?>
                        <button type="submit" class="btn btn-primary w-100" id="analyzeBtn">
                            <i class="fas fa-brain"></i> Analyze Case
                        </button>
                    </form>
                </div>
                
                <div class="analysis-card">
                    <h5><i class="fas fa-chart-bar"></i> Usage Statistics</h5>
                    <div class="row text-center">
                        <div class="col-6">
                            <h3><?php echo $totalAnalyses; ?></h3>
                            <small class="text-muted">Total Analyses</small>
                        </div>
                        <div class="col-6">
                            <h3><?php echo $todayAnalyses; ?></h3>
                            <small class="text-muted">Today</small>
                        </div>
                    </div>
                    <hr>
                    <div class="alert alert-info small mb-0">
                        <i class="fas fa-info-circle"></i> AI analysis uses Google Gemini or DeepSeek to assist with case interpretation. Always use clinical judgment.
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="analysis-card">
                    <h5><i class="fas fa-chart-line"></i> Analysis Result</h5>
                    <div id="analysisResult" class="analysis-result">
                        <p class="text-muted text-center mt-5">
                            <i class="fas fa-robot fa-3x mb-3 d-block"></i>
                            Enter case details and click "Analyze Case" to get AI-powered insights.
                        </p>
                    </div>
                    <div class="mt-3 text-end">
                        <button class="btn btn-sm btn-secondary" onclick="copyResult()" style="display: none;" id="copyBtn">
                            <i class="fas fa-copy"></i> Copy to Clipboard
                        </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>
        $('#analysisForm').on('submit', function(e) {
            e.preventDefault();
            
            const caseText = $('#caseText').val();
            const remedyName = $('#remedyName').val();
            const analysisType = $('#analysisType').val();
            
            if (!caseText.trim()) {
                alert('Please enter case details');
                return;
            }
            
            $('#analyzeBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Analyzing...');
            $('#analysisResult').html(`
                <div class="loading">
                    <div class="spinner-border text-primary"></div>
                    <p class="mt-3">AI is analyzing the case...</p>
                    <small class="text-muted">This may take a few seconds</small>
                </div>
            `);
            
            $.ajax({
                url: 'analyze.php',
                method: 'POST',
                data: {
                    ajax: 1,
                    case_text: caseText,
                    remedy_name: remedyName,
                    analysis_type: analysisType
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        let formattedResult = response.analysis.replace(/\n/g, '<br>');
                        $('#analysisResult').html(`
                            <div class="p-3">
                                ${formattedResult}
                            </div>
                        `);
                        $('#copyBtn').show();
                    } else {
                        $('#analysisResult').html(`
                            <div class="alert alert-danger m-3">
                                <i class="fas fa-exclamation-triangle"></i> 
                                ${response.error || 'Analysis failed. Please check API configuration.'}
                            </div>
                        `);
                    }
                },
                error: function(xhr, status, error) {
                    $('#analysisResult').html(`
                        <div class="alert alert-danger m-3">
                            <i class="fas fa-exclamation-triangle"></i> 
                            Connection error: ${error}. Please try again.
                        </div>
                    `);
                },
                complete: function() {
                    $('#analyzeBtn').prop('disabled', false).html('<i class="fas fa-brain"></i> Analyze Case');
                }
            });
        });
        
        function copyResult() {
            const text = $('#analysisResult').text();
            navigator.clipboard.writeText(text).then(() => {
                alert('Analysis copied to clipboard');
            });
        }
        
        // Load case from URL parameter
        <?php if($caseId && $caseData): ?>
        // Optionally auto-analyze if needed
        <?php endif; ?>
    </script>
</body>
</html>