<?php
/**
 * Case Statistics Report
 * Detailed analysis of cases with filters
 */

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

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$status = $_GET['status'] ?? 'all';
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');

// Build query
$where = "user_id = ?";
$params = [$userId];

if ($status != 'all') {
    $where .= " AND status = ?";
    $params[] = $status;
}
$where .= " AND DATE(created_at) BETWEEN ? AND ?";
$params[] = $dateFrom;
$params[] = $dateTo;

// Get cases
$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 $where
                      ORDER BY c.created_at DESC");
$stmt->execute($params);
$cases = $stmt->fetchAll();

// Calculate averages
$totalCases = count($cases);
$avgAge = 0;
$genderCount = ['M' => 0, 'F' => 0, 'Other' => 0];
$statusCount = ['active' => 0, 'follow-up' => 0, 'closed' => 0];
$remedyCount = [];

foreach ($cases as $case) {
    if ($case['patient_age']) $avgAge += $case['patient_age'];
    $genderCount[$case['patient_gender']]++;
    $statusCount[$case['status']]++;
    if ($case['remedy_name']) {
        $remedyCount[$case['remedy_name']] = ($remedyCount[$case['remedy_name']] ?? 0) + 1;
    }
}
$avgAge = $totalCases > 0 ? round($avgAge / $totalCases) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Case Statistics - Reports</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;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        .stats-number { font-size: 28px; 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">🏥</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="index.php"><i class="fas fa-chart-line"></i> <span>Reports</span></a>
            <a class="nav-link" href="cases.php"><i class="fas fa-folder-open"></i> <span>Case Stats</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> Case Statistics</h4>
                <div>
                    <a href="export.php?type=cases&<?php echo http_build_query($_GET); ?>" class="btn btn-success btn-sm">
                        <i class="fas fa-download"></i> Export CSV
                    </a>
                    <a href="index.php" class="btn btn-secondary btn-sm">Back</a>
                </div>
            </div>
        </div>
        
        <!-- Filter Form -->
        <div class="stats-card">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="all" <?php echo $status == 'all' ? 'selected' : ''; ?>>All Status</option>
                        <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="follow-up" <?php echo $status == 'follow-up' ? 'selected' : ''; ?>>Follow-up</option>
                        <option value="closed" <?php echo $status == 'closed' ? 'selected' : ''; ?>>Closed</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Date From</label>
                    <input type="date" name="date_from" class="form-control" value="<?php echo $dateFrom; ?>">
                </div>
                <div class="col-md-3">
                    <label>Date To</label>
                    <input type="date" name="date_to" class="form-control" value="<?php echo $dateTo; ?>">
                </div>
                <div class="col-md-3">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn btn-primary w-100">Apply Filter</button>
                </div>
            </form>
        </div>
        
        <!-- Summary Statistics -->
        <div class="row">
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?php echo $totalCases; ?></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"><?php echo $avgAge; ?></div>
                    <div class="text-muted">Average Age</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?php echo $genderCount['M']; ?> / <?php echo $genderCount['F']; ?></div>
                    <div class="text-muted">Male/Female Ratio</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?php echo count($remedyCount); ?></div>
                    <div class="text-muted">Unique Remedies Used</div>
                </div>
            </div>
        </div>
        
        <!-- Cases Table -->
        <div class="stats-card">
            <h5>Case Details</h5>
            <div class="table-responsive">
                <table class="table table-bordered" id="casesTable">
                    <thead>
                        <tr><th>ID</th><th>Date</th><th>Patient</th><th>Age/Gender</th><th>Status</th><th>Prescribed Remedy</th><th>Follow-up Date</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($cases as $case): ?>
                        <tr>
                            <td><?php echo $case['id']; ?></td>
                            <td><?php echo date('d-m-Y', strtotime($case['created_at'])); ?></td>
                            <td><strong><?php echo escape($case['patient_name']); ?></strong><br><small><?php echo $case['patient_mobile']; ?></small></td>
                            <td><?php echo $case['patient_age'] . ' / ' . $case['patient_gender']; ?></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><?php echo $case['remedy_name'] ?? '-'; ?></td>
                            <td><?php echo $case['follow_up_date'] ? date('d-m-Y', strtotime($case['follow_up_date'])) : '-'; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script>$(document).ready(function() { $('#casesTable').DataTable({ pageLength: 25 }); });</script>
</body>
</html>