<?php
/**
 * Doctor Activity Report
 * Detailed report of doctor performance and case statistics
 */

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

requireAdmin();

$pdo = getDB();
$period = $_GET['period'] ?? 'month';
$dateRange = getDateRange($period);

// Get doctors with their statistics
$sql = "SELECT u.id, u.full_name, u.email, u.username, u.is_active, u.created_at as joined_date,
        COUNT(DISTINCT c.id) as total_cases,
        COUNT(DISTINCT CASE WHEN c.status = 'active' THEN c.id END) as active_cases,
        COUNT(DISTINCT CASE WHEN c.status = 'follow-up' THEN c.id END) as followup_cases,
        COUNT(DISTINCT CASE WHEN c.status = 'closed' THEN c.id END) as closed_cases,
        COUNT(DISTINCT f.id) as total_followups,
        COUNT(DISTINCT CASE WHEN c.created_at BETWEEN '{$dateRange['start']}' AND '{$dateRange['end']}' THEN c.id END) as period_cases,
        COUNT(DISTINCT CASE WHEN c.prescribed_remedy_id IS NOT NULL THEN c.id END) as prescriptions,
        (SELECT COUNT(*) FROM subscriptions WHERE user_id = u.id AND is_active = 1) as has_subscription
        FROM users u
        LEFT JOIN cases c ON u.id = c.user_id
        LEFT JOIN follow_ups f ON c.id = f.case_id
        WHERE u.role = 'doctor'
        GROUP BY u.id
        ORDER BY total_cases DESC";

$doctors = $pdo->query($sql)->fetchAll();

// Calculate averages
$totalCases = array_sum(array_column($doctors, 'total_cases'));
$totalFollowups = array_sum(array_column($doctors, 'total_followups'));
$avgCasesPerDoctor = count($doctors) > 0 ? round($totalCases / count($doctors), 1) : 0;
$avgFollowupsPerDoctor = count($doctors) > 0 ? round($totalFollowups / count($doctors), 1) : 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doctor Activity Report - Admin Panel</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>
        .sidebar {
            min-height: 100vh;
            background: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
        }
        .sidebar .nav-link:hover { background: #34495e; }
        .sidebar .nav-link.active { background: #3498db; }
        .main-content { background: #f8f9fa; min-height: 100vh; }
        .top-navbar { background: white; padding: 15px 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .stats-card { background: white; border-radius: 10px; padding: 15px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
        .stats-number { font-size: 28px; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4"><h4 class="text-white">🏥 Admin</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="../doctors/index.php"><i class="fas fa-user-md"></i> Doctors</a>
                    <a class="nav-link" href="../subscriptions/index.php"><i class="fas fa-credit-card"></i> Subscriptions</a>
                    <a class="nav-link" href="../rubrics/index.php"><i class="fas fa-tree"></i> Rubrics</a>
                    <a class="nav-link" href="../remedies/index.php"><i class="fas fa-capsules"></i> Remedies</a>
                    <a class="nav-link" href="../settings/index.php"><i class="fas fa-cog"></i> Settings</a>
                    <a class="nav-link active" href="index.php"><i class="fas fa-chart-line"></i> Reports</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="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between">
                        <h4 class="mb-0"><i class="fas fa-user-md"></i> Doctor Activity Report</h4>
                        <div>
                            <a href="?export=csv&<?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 to Reports</a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <!-- Period Filter -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label>Period</label>
                                    <select name="period" class="form-control" onchange="this.form.submit()">
                                        <option value="week" <?php echo $period == 'week' ? 'selected' : ''; ?>>Last 7 Days</option>
                                        <option value="month" <?php echo $period == 'month' ? 'selected' : ''; ?>>Last 30 Days</option>
                                        <option value="year" <?php echo $period == 'year' ? 'selected' : ''; ?>>Last 12 Months</option>
                                        <option value="all" <?php echo $period == 'all' ? 'selected' : ''; ?>>All Time</option>
                                    </select>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Summary Stats -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card"><div class="stats-number"><?php echo count($doctors); ?></div><div>Total Doctors</div></div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card"><div class="stats-number"><?php echo $totalCases; ?></div><div>Total Cases</div></div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card"><div class="stats-number"><?php echo $avgCasesPerDoctor; ?></div><div>Avg Cases/Doctor</div></div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card"><div class="stats-number"><?php echo $totalFollowups; ?></div><div>Total Follow-ups</div></div>
                        </div>
                    </div>
                    
                    <!-- Doctors Table -->
                    <div class="card">
                        <div class="card-header"><h5 class="mb-0">Doctor Performance Metrics</h5></div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="doctorsTable" class="table table-bordered table-hover">
                                    <thead>
                                        <tr><th>Doctor</th><th>Email</th><th>Status</th><th>Joined</th>
                                            <th>Total Cases</th><th>Active</th><th>Follow-ups</th><th>Closed</th>
                                            <th>Period Cases</th><th>Prescriptions</th><th>Follow-ups/Case</th><th>Subscription</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($doctors as $doctor): ?>
                                        <tr>
                                            <td><strong><?php echo escape($doctor['full_name']); ?></strong><br><small>@<?php echo $doctor['username']; ?></small></td>
                                            <td><?php echo $doctor['email']; ?></td>
                                            <td><span class="badge bg-<?php echo $doctor['is_active'] ? 'success' : 'danger'; ?>"><?php echo $doctor['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                                            <td><?php echo date('d-m-Y', strtotime($doctor['joined_date'])); ?></td>
                                            <td><?php echo $doctor['total_cases']; ?></td>
                                            <td><?php echo $doctor['active_cases']; ?></td>
                                            <td><?php echo $doctor['followup_cases']; ?></td>
                                            <td><?php echo $doctor['closed_cases']; ?></td>
                                            <td><?php echo $doctor['period_cases']; ?> <small>(this period)</small></td>
                                            <td><?php echo $doctor['prescriptions']; ?> <?php echo $doctor['total_cases'] > 0 ? '(' . round(($doctor['prescriptions']/$doctor['total_cases'])*100) . '%)' : ''; ?></td>
                                            <td><?php echo $doctor['total_cases'] > 0 ? number_format($doctor['total_followups'] / $doctor['total_cases'], 1) : 0; ?></td>
                                            <td><?php echo $doctor['has_subscription'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-danger">None</span>'; ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </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() { $('#doctorsTable').DataTable(); });</script>
</body>
</html>