<?php
/**
 * AI Analysis History
 * View all previous AI analyses
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$type = $_GET['type'] ?? 'all';

// Get history based on type
$history = [];
if ($type == 'all' || $type == 'analysis') {
    $stmt = $pdo->prepare("SELECT * FROM ai_analysis_history WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$userId]);
    $analysisHistory = $stmt->fetchAll();
} else {
    $analysisHistory = [];
}

if ($type == 'all' || $type == 'remedy') {
    $stmt = $pdo->prepare("SELECT * FROM ai_remedy_suggestions WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$userId]);
    $remedyHistory = $stmt->fetchAll();
} else {
    $remedyHistory = [];
}

if ($type == 'all' || $type == 'rubrics') {
    $stmt = $pdo->prepare("SELECT * FROM ai_rubric_extractions WHERE user_id = ? ORDER BY created_at DESC LIMIT 50");
    $stmt->execute([$userId]);
    $rubricHistory = $stmt->fetchAll();
} else {
    $rubricHistory = [];
}

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

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM ai_remedy_suggestions WHERE user_id = ?");
$stmt->execute([$userId]);
$totalSuggestions = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COUNT(*) as total FROM ai_rubric_extractions WHERE user_id = ?");
$stmt->execute([$userId]);
$totalExtractions = $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 Analysis History</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.datatables.net/1.11.5/css/dataTables.bootstrap5.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);
        }
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .stats-number { font-size: 32px; font-weight: bold; }
        .history-item {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            border-left: 4px solid #2ecc71;
        }
        @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="../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-history"></i> AI Analysis History</h4>
        </div>
        
        <!-- Statistics -->
        <div class="row">
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number"><?php echo $totalAnalysis; ?></div>
                    <div class="text-muted">Case Analyses</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number"><?php echo $totalSuggestions; ?></div>
                    <div class="text-muted">Remedy Suggestions</div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <div class="stats-number"><?php echo $totalExtractions; ?></div>
                    <div class="text-muted">Rubric Extractions</div>
                </div>
            </div>
        </div>
        
        <!-- Type Tabs -->
        <ul class="nav nav-tabs mb-3">
            <li class="nav-item"><a class="nav-link <?php echo $type == 'all' ? 'active' : ''; ?>" href="?type=all">All</a></li>
            <li class="nav-item"><a class="nav-link <?php echo $type == 'analysis' ? 'active' : ''; ?>" href="?type=analysis">Case Analyses</a></li>
            <li class="nav-item"><a class="nav-link <?php echo $type == 'remedy' ? 'active' : ''; ?>" href="?type=remedy">Remedy Suggestions</a></li>
            <li class="nav-item"><a class="nav-link <?php echo $type == 'rubrics' ? 'active' : ''; ?>" href="?type=rubrics">Rubric Extractions</a></li>
        </ul>
        
        <!-- Case Analysis History -->
        <?php if (!empty($analysisHistory) && ($type == 'all' || $type == 'analysis')): ?>
            <h5><i class="fas fa-chart-line"></i> Case Analyses</h5>
            <?php foreach($analysisHistory as $item): ?>
                <div class="history-item">
                    <div class="d-flex justify-content-between">
                        <small class="text-muted"><?php echo date('d-m-Y H:i:s', strtotime($item['created_at'])); ?></small>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewAnalysis(<?php echo $item['id']; ?>, 'analysis')">View Details</button>
                    </div>
                    <p class="mt-2"><strong>Case Preview:</strong> <?php echo substr($item['case_text'], 0, 200); ?>...</p>
                    <?php if($item['remedy_name']): ?>
                        <span class="badge bg-info">Remedy: <?php echo $item['remedy_name']; ?></span>
                    <?php endif; ?>
                    <div id="analysis-<?php echo $item['id']; ?>" style="display: none;" class="mt-3">
                        <hr>
                        <strong>Full Analysis:</strong>
                        <div class="bg-light p-3 rounded mt-2"><?php echo nl2br(htmlspecialchars($item['analysis_result'])); ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <!-- Remedy Suggestions History -->
        <?php if (!empty($remedyHistory) && ($type == 'all' || $type == 'remedy')): ?>
            <h5 class="mt-4"><i class="fas fa-lightbulb"></i> Remedy Suggestions</h5>
            <?php foreach($remedyHistory as $item): ?>
                <div class="history-item">
                    <div class="d-flex justify-content-between">
                        <small class="text-muted"><?php echo date('d-m-Y H:i:s', strtotime($item['created_at'])); ?></small>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewAnalysis(<?php echo $item['id']; ?>, 'remedy')">View Details</button>
                    </div>
                    <p class="mt-2"><strong>Symptoms Preview:</strong> <?php echo substr($item['symptoms'], 0, 200); ?>...</p>
                    <?php 
                    $suggestion = json_decode($item['suggestion_result'], true);
                    if($suggestion && isset($suggestion['suggested_remedy'])):
                    ?>
                        <span class="badge bg-success">Suggested: <?php echo $suggestion['suggested_remedy']; ?></span>
                        <span class="badge bg-secondary">Confidence: <?php echo $suggestion['confidence'] ?? 'Medium'; ?></span>
                    <?php endif; ?>
                    <div id="remedy-<?php echo $item['id']; ?>" style="display: none;" class="mt-3">
                        <hr>
                        <strong>Full Suggestion:</strong>
                        <div class="bg-light p-3 rounded mt-2">
                            <?php 
                            if($suggestion) {
                                echo "<strong>Remedy:</strong> " . ($suggestion['suggested_remedy'] ?? 'N/A') . "<br>";
                                echo "<strong>Confidence:</strong> " . ($suggestion['confidence'] ?? 'N/A') . "<br>";
                                echo "<strong>Reasoning:</strong> " . ($suggestion['reasoning'] ?? 'N/A') . "<br>";
                                echo "<strong>Potency:</strong> " . ($suggestion['potency'] ?? '30C');
                            }
                            ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <!-- Rubric Extractions History -->
        <?php if (!empty($rubricHistory) && ($type == 'all' || $type == 'rubrics')): ?>
            <h5 class="mt-4"><i class="fas fa-tree"></i> Rubric Extractions</h5>
            <?php foreach($rubricHistory as $item): ?>
                <div class="history-item">
                    <div class="d-flex justify-content-between">
                        <small class="text-muted"><?php echo date('d-m-Y H:i:s', strtotime($item['created_at'])); ?></small>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewAnalysis(<?php echo $item['id']; ?>, 'rubrics')">View Details</button>
                    </div>
                    <p class="mt-2"><strong>Case Preview:</strong> <?php echo substr($item['case_text'], 0, 200); ?>...</p>
                    <div id="rubrics-<?php echo $item['id']; ?>" style="display: none;" class="mt-3">
                        <hr>
                        <strong>Extracted Rubrics:</strong>
                        <div class="bg-light p-3 rounded mt-2">
                            <?php 
                            $rubrics = json_decode($item['extracted_rubrics'], true);
                            if($rubrics) {
                                echo "<ul>";
                                foreach($rubrics as $rubric) {
                                    echo "<li><strong>{$rubric['full_path']}</strong> - Relevance: {$rubric['relevance']}</li>";
                                }
                                echo "</ul>";
                            } else {
                                echo "No rubrics extracted";
                            }
                            ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
        
        <?php if(empty($analysisHistory) && empty($remedyHistory) && empty($rubricHistory)): ?>
            <div class="card-custom text-center text-muted py-5">
                <i class="fas fa-history fa-3x mb-3"></i>
                <p>No AI analysis history found.</p>
                <a href="analyze.php" class="btn btn-primary">Start New Analysis</a>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function viewAnalysis(id, type) {
            const element = $(`#${type}-${id}`);
            if (element.is(':visible')) {
                element.hide();
            } else {
                element.show();
            }
        }
    </script>
</body>
</html>