<?php
/**
 * Cases Dashboard Overview
 * Summary of all cases with statistics
 */

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

requireLogin();

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

// Get case statistics
$stmt = $pdo->prepare("SELECT 
                      COUNT(*) as total,
                      SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                      SUM(CASE WHEN status = 'follow-up' THEN 1 ELSE 0 END) as follow_up,
                      SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed,
                      SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today,
                      SUM(CASE WHEN WEEK(created_at) = WEEK(CURDATE()) THEN 1 ELSE 0 END) as this_week,
                      SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) THEN 1 ELSE 0 END) as this_month
                      FROM cases WHERE user_id = ?");
$stmt->execute([$userId]);
$stats = $stmt->fetch();

// Get cases by remedy
$stmt = $pdo->prepare("SELECT r.name, COUNT(c.id) as count
                      FROM cases c
                      LEFT JOIN remedies r ON c.prescribed_remedy_id = r.id
                      WHERE c.user_id = ? AND c.prescribed_remedy_id IS NOT NULL
                      GROUP BY c.prescribed_remedy_id
                      ORDER BY count DESC
                      LIMIT 10");
$stmt->execute([$userId]);
$topRemedies = $stmt->fetchAll();

// Get cases by month for chart
$stmt = $pdo->prepare("SELECT 
                      DATE_FORMAT(created_at, '%M') as month,
                      COUNT(*) as count
                      FROM cases 
                      WHERE user_id = ? 
                      AND YEAR(created_at) = YEAR(CURDATE())
                      GROUP BY MONTH(created_at)
                      ORDER BY MONTH(created_at)");
$stmt->execute([$userId]);
$monthlyCases = $stmt->fetchAll();

// Fill missing months
$months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
$caseData = array_fill(0, 12, 0);
foreach ($monthlyCases as $mc) {
    $index = array_search($mc['month'], $months);
    if ($index !== false) $caseData[$index] = $mc['count'];
}

// Get recent activity
$stmt = $pdo->prepare("SELECT 'case' as type, id, patient_name as name, created_at, status
                      FROM cases WHERE user_id = ?
                      ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$userId]);
$recentActivities = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cases Dashboard - <?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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <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;
            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);
        }
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            transition: transform 0.2s;
        }
        .stats-card:hover { transform: translateY(-5px); }
        .stats-number { font-size: 32px; font-weight: bold; }
        @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">🏥 Homoeopathy</h4><small class="text-white-50">Kent's Repertory</small></div>
        <nav class="nav flex-column mt-3">
            <a class="nav-link" href="../dashboard.php"><i class="fas fa-tachometer-alt"></i> <span>Dashboard</span></a>
            <a class="nav-link active" href="index.php"><i class="fas fa-folder-open"></i> <span>Cases</span></a>
            <a class="nav-link" href="list.php"><i class="fas fa-list"></i> <span>All Cases</span></a>
            <a class="nav-link" href="new.php"><i class="fas fa-plus-circle"></i> <span>New Case</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" 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">
            <div class="d-flex justify-content-between">
                <h4 class="mb-0"><i class="fas fa-folder-open"></i> Cases Dashboard</h4>
                <a href="new.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Case</a>
            </div>
        </div>
        
        <!-- Statistics Cards -->
        <div class="row">
            <div class="col-md-3"><div class="stats-card text-center"><div class="stats-number"><?php echo $stats['total']; ?></div><div class="text-muted">Total Cases</div></div></div>
            <div class="col-md-3"><div class="stats-card text-center"><div class="stats-number text-success"><?php echo $stats['active']; ?></div><div class="text-muted">Active</div></div></div>
            <div class="col-md-3"><div class="stats-card text-center"><div class="stats-number text-warning"><?php echo $stats['follow_up']; ?></div><div class="text-muted">Follow-up Required</div></div></div>
            <div class="col-md-3"><div class="stats-card text-center"><div class="stats-number text-secondary"><?php echo $stats['closed']; ?></div><div class="text-muted">Closed</div></div></div>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <div class="stats-card"><h5><i class="fas fa-chart-line"></i> Cases by Month (<?php echo date('Y'); ?>)</h5><canvas id="casesChart" height="250"></canvas></div>
            </div>
            <div class="col-md-4">
                <div class="stats-card"><h5><i class="fas fa-capsules"></i> Top Remedies</h5>
                    <?php if(empty($topRemedies)): ?>
                        <p class="text-muted text-center mt-4">No prescriptions yet</p>
                    <?php else: ?>
                        <?php foreach($topRemedies as $remedy): ?>
                            <div class="d-flex justify-content-between mb-2"><span><?php echo escape($remedy['name']); ?></span><span class="badge bg-primary"><?php echo $remedy['count']; ?></span></div>
                            <div class="progress mb-3"><div class="progress-bar bg-primary" style="width: <?php echo ($remedy['count'] / $topRemedies[0]['count']) * 100; ?>%"></div></div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <div class="stats-card"><h5><i class="fas fa-chart-pie"></i> Case Distribution</h5>
                    <canvas id="statusChart" height="200"></canvas>
                </div>
            </div>
        </div>
        
        <!-- Quick Stats Row -->
        <div class="row">
            <div class="col-md-4"><div class="stats-card"><h6><i class="fas fa-calendar-day"></i> Today</h6><h2><?php echo $stats['today']; ?></h2><small>cases created today</small></div></div>
            <div class="col-md-4"><div class="stats-card"><h6><i class="fas fa-calendar-week"></i> This Week</h6><h2><?php echo $stats['this_week']; ?></h2><small>cases this week</small></div></div>
            <div class="col-md-4"><div class="stats-card"><h6><i class="fas fa-calendar-alt"></i> This Month</h6><h2><?php echo $stats['this_month']; ?></h2><small>cases this month</small></div></div>
        </div>
        
        <!-- Recent Cases -->
        <div class="stats-card"><h5><i class="fas fa-history"></i> Recent Cases</h5>
            <div class="table-responsive"><table class="table table-hover">
                <thead><tr><th>Date</th><th>Patient</th><th>Mobile</th><th>Status</th><th>Action</th></tr></thead>
                <tbody>
                    <?php foreach($recentActivities as $case): ?>
                    <tr>
                        <td><?php echo date('d-m-Y', strtotime($case['created_at'])); ?></td>
                        <td><strong><?php echo escape($case['name']); ?></strong></td>
                        <td><?php echo $case['patient_mobile'] ?? '-'; ?></td>
                        <td><span class="badge bg-<?php echo $case['status'] == 'active' ? 'success' : ($case['status'] == 'follow-up' ? 'warning' : 'secondary'); ?>"><?php echo ucfirst($case['status']); ?></span></td>
                        <td><a href="view.php?id=<?php echo $case['id']; ?>" class="btn btn-sm btn-info">View</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table></div>
            <div class="text-center mt-3"><a href="list.php" class="btn btn-outline-primary">View All Cases</a></div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        new Chart(document.getElementById('casesChart'), { type: 'line', data: { labels: <?php echo json_encode($months); ?>, datasets: [{ label: 'Cases', data: <?php echo json_encode($caseData); ?>, borderColor: '#2ecc71', tension: 0.3, fill: true, backgroundColor: 'rgba(46,204,113,0.1)' }] }, options: { responsive: true } });
        new Chart(document.getElementById('statusChart'), { type: 'doughnut', data: { labels: ['Active', 'Follow-up', 'Closed'], datasets: [{ data: [<?php echo $stats['active']; ?>, <?php echo $stats['follow_up']; ?>, <?php echo $stats['closed']; ?>], backgroundColor: ['#28a745', '#ffc107', '#6c757d'] }] }, options: { responsive: true } });
    </script>
</body>
</html>