<?php
/**
 * View Case Details
 * Display complete case information with repertorization results
 */

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

requireLogin();

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

$stmt = $pdo->prepare("SELECT c.*, r.name as remedy_name 
                      FROM cases c
                      LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                      WHERE c.id = ? AND c.user_id = ?");
$stmt->execute([$caseId, $userId]);
$case = $stmt->fetch();

if (!$case) { header('Location: list.php?error=Case not found'); exit; }

$selectedRubrics = json_decode($case['selected_rubrics'], true) ?: [];
$repertorizationResult = json_decode($case['repertorization_result'], true) ?: [];

// Get follow-ups
$stmt = $pdo->prepare("SELECT * FROM follow_ups WHERE case_id = ? ORDER BY follow_up_date DESC");
$stmt->execute([$caseId]);
$followUps = $stmt->fetchAll();

// Get rubric details
$rubricNames = [];
if (!empty($selectedRubrics)) {
    $placeholders = implode(',', array_fill(0, count($selectedRubrics), '?'));
    $stmt = $pdo->prepare("SELECT id, full_path FROM rubrics WHERE id IN ($placeholders)");
    $stmt->execute($selectedRubrics);
    $rubricNames = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>View Case - <?php echo escape($case['patient_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>
        .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); }
        .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); }
        @media print { .sidebar, .top-navbar, .btn, .no-print { display: none !important; } .main-content { margin-left: 0; } }
    </style>
</head>
<body>
    <div class="sidebar"><div class="text-center py-4"><h4 class="text-white mb-0">🏥 Homoeopathy</h4></div>
        <nav class="nav flex-column">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a class="nav-link" href="index.php"><i class="fas fa-folder-open"></i> Cases</a>
            <a class="nav-link" href="list.php"><i class="fas fa-list"></i> All Cases</a>
            <a class="nav-link" href="../profile.php"><i class="fas fa-user"></i> Profile</a>
            <hr><a class="nav-link" href="../../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </div>
    
    <div class="main-content">
        <div class="top-navbar no-print"><div class="d-flex justify-content-between"><h4><i class="fas fa-folder-open"></i> Case: <?php echo escape($case['patient_name']); ?></h4>
            <div><a href="edit.php?id=<?php echo $caseId; ?>" class="btn btn-primary"><i class="fas fa-edit"></i> Edit</a>
            <a href="prescribe.php?id=<?php echo $caseId; ?>" class="btn btn-success"><i class="fas fa-prescription"></i> Prescribe</a>
            <a href="follow-up.php?id=<?php echo $caseId; ?>" class="btn btn-warning"><i class="fas fa-calendar-plus"></i> Follow-up</a>
            <a href="print.php?id=<?php echo $caseId; ?>" class="btn btn-info" target="_blank"><i class="fas fa-print"></i> Print</a>
            <a href="list.php" class="btn btn-secondary">Back</a></div>
        </div></div>
        
        <?php if(isset($_GET['msg'])): ?><div class="alert alert-success"><?php echo $_GET['msg']; ?></div><?php endif; ?>
        
        <div class="row">
            <div class="col-md-6">
                <div class="card mb-3"><div class="card-header bg-primary text-white"><h5><i class="fas fa-user"></i> Patient Details</h5></div>
                    <div class="card-body"><table class="table table-bordered">
                        <tr><th width="40%">Name:</th><td><?php echo escape($case['patient_name']); ?></td></tr>
                        <tr><th>Mobile:</th><td><?php echo $case['patient_mobile']; ?></td></tr>
                        <tr><th>Age:</th><td><?php echo $case['patient_age']; ?></td></tr>
                        <tr><th>Gender:</th><td><?php echo $case['patient_gender']; ?></td></tr>
                        <tr><th>Created:</th><td><?php echo date('d-m-Y H:i', strtotime($case['created_at'])); ?></td></tr>
                        <tr><th>Status:</th><td><span class="badge bg-<?php echo $case['status']=='active'?'success':($case['status']=='follow-up'?'warning':'secondary'); ?>"><?php echo ucfirst($case['status']); ?></span></td></tr>
                    </table></div>
                </div>
                
                <div class="card"><div class="card-header bg-info text-white"><h5><i class="fas fa-notes-medical"></i> Case History</h5></div>
                    <div class="card-body"><strong>Chief Complaint:</strong><p><?php echo nl2br(escape($case['chief_complaint'])); ?></p>
                    <strong>Case History:</strong><p><?php echo nl2br(escape($case['case_history'])); ?></p>
                    <strong>Physical Generals:</strong><p><?php echo nl2br(escape($case['physical_generals'])); ?></p>
                    <strong>Mental/Emotional:</strong><p><?php echo nl2br(escape($case['mental_emotional'])); ?></p>
                    <strong>Modalities:</strong><p><?php echo nl2br(escape($case['modalities'])); ?></p></div>
                </div>
            </div>
            
            <div class="col-md-6">
                <?php if($case['prescribed_remedy_id']): ?>
                <div class="card mb-3"><div class="card-header bg-success text-white"><h5><i class="fas fa-prescription"></i> Prescription</h5></div>
                    <div class="card-body"><h4><?php echo $case['remedy_name']; ?></h4><p>Potency: <strong><?php echo $case['prescription_potency']; ?></strong></p>
                    <?php if($case['follow_up_date']): ?><p>Follow-up Date: <?php echo date('d-m-Y', strtotime($case['follow_up_date'])); ?></p><?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="card mb-3"><div class="card-header bg-secondary text-white"><h5><i class="fas fa-list"></i> Selected Rubrics</h5></div>
                    <div class="card-body" style="max-height: 250px; overflow-y: auto;">
                        <?php if(empty($rubricNames)): ?><p class="text-muted">No rubrics selected</p>
                        <?php else: ?><ul><?php foreach($rubricNames as $rubric): ?><li><?php echo escape($rubric['full_path']); ?></li><?php endforeach; ?></ul><?php endif; ?>
                    </div>
                </div>
                
                <div class="card mb-3"><div class="card-header bg-warning"><h5><i class="fas fa-chart-bar"></i> Repertorization Results</h5></div>
                    <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                        <?php if(empty($repertorizationResult)): ?><p class="text-muted">No repertorization results</p>
                        <?php else: ?><table class="table table-sm"><thead><tr><th>Remedy</th><th>Score</th><th>Action</th></tr></thead>
                            <tbody><?php foreach($repertorizationResult as $r): ?><tr><td><strong><?php echo $r['remedy_name']; ?></strong></td><td><?php echo $r['score']; ?></td>
                            <td><a href="../materia-medica/view.php?name=<?php echo urlencode($r['remedy_name']); ?>" target="_blank" class="btn btn-sm btn-info">View MM</a></td></tr><?php endforeach; ?></tbody>
                        </table><?php endif; ?>
                    </div>
                </div>
                
                <?php if(!empty($followUps)): ?>
                <div class="card"><div class="card-header bg-dark text-white"><h5><i class="fas fa-history"></i> Follow-up History</h5></div>
                    <div class="card-body"><?php foreach($followUps as $fu): ?>
                        <div class="border-bottom mb-2 pb-2"><strong><?php echo date('d-m-Y', strtotime($fu['follow_up_date'])); ?></strong>
                        <p><?php echo nl2br(escape($fu['progress'])); ?></p>
                        <?php if($fu['new_symptoms']): ?><small><strong>New Symptoms:</strong> <?php echo escape($fu['new_symptoms']); ?></small><br><?php endif; ?>
                        <?php if($fu['remedy_repeated']): ?><span class="badge bg-info">Remedy Repeated</span><?php endif; ?></div>
                    <?php endforeach; ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</body>
</html>