<?php
/**
 * Doctor Reports Dashboard
 * Overview of practice statistics and analytics
 */

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

requireLogin();

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

// Get summary statistics
$stmt = $pdo->prepare("SELECT 
                      COUNT(*) as total_cases,
                      SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_cases,
                      SUM(CASE WHEN status = 'follow-up' THEN 1 ELSE 0 END) as follow_up_cases,
                      SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_cases,
                      COUNT(DISTINCT patient_mobile) as unique_patients,
                      SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_cases,
                      SUM(CASE WHEN WEEK(created_at) = WEEK(CURDATE()) THEN 1 ELSE 0 END) as week_cases,
                      SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) THEN 1 ELSE 0 END) as month_cases,
                      SUM(CASE WHEN prescribed_remedy_id IS NOT NULL THEN 1 ELSE 0 END) as total_prescriptions
                      FROM cases WHERE user_id = ?");
$stmt->execute([$userId]);
$summary = $stmt->fetch();

// Get monthly trend data
$stmt = $pdo->prepare("SELECT 
                      DATE_FORMAT(created_at, '%Y-%m') as month,
                      COUNT(*) as case_count,
                      SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed_count
                      FROM cases 
                      WHERE user_id = ? 
                      AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
                      GROUP BY DATE_FORMAT(created_at, '%Y-%m')
                      ORDER BY month ASC");
$stmt->execute([$userId]);
$monthlyTrend = $stmt->fetchAll();

// Get cases by status for pie chart
$statusData = [
    'active' => $summary['active_cases'],
    'follow-up' => $summary['follow_up_cases'],
    'closed' => $summary['closed_cases']
];

// Get recent activity
$stmt = $pdo->prepare("SELECT * FROM cases 
                      WHERE user_id = ? 
                      ORDER BY created_at DESC 
                      LIMIT 5");
$stmt->execute([$userId]);
$recentCases = $stmt->fetchAll();

// Get follow-ups due
$stmt = $pdo->prepare("SELECT COUNT(*) as due_count 
                      FROM cases 
                      WHERE user_id = ? 
                      AND follow_up_date IS NOT NULL 
                      AND follow_up_date >= CURDATE() 
                      AND follow_up_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)");
$stmt->execute([$userId]);
$followUpsDue = $stmt->fetch()['due_count'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports 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>
        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;
            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; }
        .report-link {
            text-decoration: none;
            display: block;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-bottom: 10px;
            transition: all 0.2s;
        }
        .report-link:hover {
            background: #e8f5e9;
            transform: translateX(5px);
        }
        @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="../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-chart-line"></i> Practice Reports</h4>
                <div>
                    <a href="export.php" class="btn btn-success btn-sm">
                        <i class="fas fa-download"></i> Export Data
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Period Filter -->
        <div class="stats-card">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label>Report 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>
        
        <!-- Statistics Cards -->
        <div class="row">
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number"><?php echo $summary['total_cases']; ?></div>
                    <div class="text-muted">Total Cases</div>
                    <small><?php echo $summary['unique_patients']; ?> unique patients</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number text-success"><?php echo $summary['active_cases']; ?></div>
                    <div class="text-muted">Active Cases</div>
                    <small><?php echo $followUpsDue; ?> follow-ups due</small>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stats-card text-center">
                    <div class="stats-number text-warning"><?php echo $summary['follow_up_cases']; ?></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 $summary['closed_cases']; ?></div>
                    <div class="text-muted">Closed Cases</div>
                    <small><?php echo $summary['total_prescriptions']; ?> prescriptions</small>
                </div>
            </div>
        </div>
        
        <!-- Charts Row -->
        <div class="row">
            <div class="col-md-8">
                <div class="stats-card">
                    <h5><i class="fas fa-chart-line"></i> Monthly Case Trend (Last 6 Months)</h5>
                    <canvas id="trendChart" height="250"></canvas>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stats-card">
                    <h5><i class="fas fa-chart-pie"></i> Case Status Distribution</h5>
                    <canvas id="statusChart" height="250"></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 $summary['today_cases']; ?></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 $summary['week_cases']; ?></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 $summary['month_cases']; ?></h2>
                    <small>cases this month</small>
                </div>
            </div>
        </div>
        
        <!-- Report Links -->
        <div class="stats-card">
            <h5><i class="fas fa-file-alt"></i> Detailed Reports</h5>
            <div class="row">
                <div class="col-md-4">
                    <a href="cases.php" class="report-link">
                        <i class="fas fa-folder-open fa-2x float-end text-primary"></i>
                        <strong>Case Statistics</strong><br>
                        <small>Detailed case analysis and outcomes</small>
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="remedies.php" class="report-link">
                        <i class="fas fa-capsules fa-2x float-end text-success"></i>
                        <strong>Remedy Analytics</strong><br>
                        <small>Most prescribed remedies and success rates</small>
                    </a>
                </div>
                <div class="col-md-4">
                    <a href="monthly.php" class="report-link">
                        <i class="fas fa-chart-line fa-2x float-end text-info"></i>
                        <strong>Monthly Trends</strong><br>
                        <small>Monthly case volume and patterns</small>
                    </a>
                </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-sm">
                    <thead>
                        <tr><th>Date</th><th>Patient</th><th>Mobile</th><th>Status</th><th>Prescribed</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach($recentCases as $case): ?>
                        <tr>
                            <td><?php echo date('d-m-Y', strtotime($case['created_at'])); ?></td>
                            <td><strong><?php echo escape($case['patient_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><?php 
                                if($case['prescribed_remedy_id']) {
                                    $rem = $pdo->prepare("SELECT name FROM remedies WHERE id = ?");
                                    $rem->execute([$case['prescribed_remedy_id']]);
                                    $r = $rem->fetch();
                                    echo $r ? $r['name'] : '-';
                                } else { echo '-'; }
                            ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Monthly Trend Chart
        const trendCtx = document.getElementById('trendChart').getContext('2d');
        new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_column($monthlyTrend, 'month')); ?>,
                datasets: [{
                    label: 'Total Cases',
                    data: <?php echo json_encode(array_column($monthlyTrend, 'case_count')); ?>,
                    borderColor: '#2ecc71',
                    backgroundColor: 'rgba(46,204,113,0.1)',
                    tension: 0.3,
                    fill: true
                }, {
                    label: 'Closed Cases',
                    data: <?php echo json_encode(array_column($monthlyTrend, 'closed_count')); ?>,
                    borderColor: '#6c757d',
                    backgroundColor: 'rgba(108,117,125,0.1)',
                    tension: 0.3,
                    fill: true
                }]
            },
            options: { responsive: true, maintainAspectRatio: true }
        });
        
        // Status Distribution Chart
        const statusCtx = document.getElementById('statusChart').getContext('2d');
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Follow-up', 'Closed'],
                datasets: [{
                    data: [<?php echo $statusData['active']; ?>, <?php echo $statusData['follow-up']; ?>, <?php echo $statusData['closed']; ?>],
                    backgroundColor: ['#28a745', '#ffc107', '#6c757d']
                }]
            },
            options: { responsive: true, plugins: { legend: { position: 'bottom' } } }
        });
    </script>
</body>
</html>