<?php
/**
 * View Doctor Profile
 * Detailed view of a doctor's information and statistics
 */

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

requireAdmin();

$pdo = getDB();
$doctorId = (int)($_GET['id'] ?? 0);

// Get doctor details with subscription
$stmt = $pdo->prepare("SELECT u.*, 
                      s.id as subscription_id, s.plan_type, s.start_date, s.end_date, s.amount, s.is_active as sub_active,
                      DATEDIFF(s.end_date, CURDATE()) as days_remaining
                      FROM users u 
                      LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
                      WHERE u.id = ? AND u.role = 'doctor'");
$stmt->execute([$doctorId]);
$doctor = $stmt->fetch();

if (!$doctor) {
    header('Location: index.php?error=Doctor not found');
    exit;
}

// Get case 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
                      FROM cases WHERE user_id = ?");
$stmt->execute([$doctorId]);
$caseStats = $stmt->fetch();

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

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

// Get subscription history
$stmt = $pdo->prepare("SELECT * FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$doctorId]);
$subscriptionHistory = $stmt->fetchAll();

// Get monthly case trend
$stmt = $pdo->prepare("SELECT 
                      DATE_FORMAT(created_at, '%Y-%m') as month,
                      COUNT(*) as count
                      FROM cases 
                      WHERE user_id = ? 
                      GROUP BY DATE_FORMAT(created_at, '%Y-%m')
                      ORDER BY month DESC
                      LIMIT 6");
$stmt->execute([$doctorId]);
$monthlyTrend = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doctor Profile - <?php echo escape($doctor['full_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: #2c3e50;
        }
        .sidebar .nav-link {
            color: #ecf0f1;
            padding: 12px 20px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover {
            background: #34495e;
            padding-left: 25px;
        }
        .sidebar .nav-link.active {
            background: #3498db;
        }
        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .top-navbar {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px 20px;
        }
        .profile-header {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .profile-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: #3498db;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }
        .profile-avatar i {
            font-size: 50px;
            color: white;
        }
        .stat-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            text-align: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .stat-number {
            font-size: 28px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 p-0 sidebar">
                <div class="text-center py-4">
                    <h4 class="text-white">🏥 Admin Panel</h4>
                    <small class="text-muted"><?php echo APP_VERSION; ?></small>
                </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 active" href="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="../reports/index.php">
                        <i class="fas fa-chart-line"></i> Reports
                    </a>
                    <a class="nav-link" href="../settings/index.php">
                        <i class="fas fa-cog"></i> Settings
                    </a>
                    <a class="nav-link" href="../profile.php">
                        <i class="fas fa-user"></i> My Profile
                    </a>
                    <hr class="bg-secondary">
                    <a class="nav-link" href="../../logout.php">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </nav>
            </div>
            
            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <div class="top-navbar">
                    <div class="d-flex justify-content-between align-items-center">
                        <h4 class="mb-0"><i class="fas fa-user-md"></i> Doctor Profile</h4>
                        <div>
                            <a href="edit.php?id=<?php echo $doctorId; ?>" class="btn btn-primary btn-sm">
                                <i class="fas fa-edit"></i> Edit Profile
                            </a>
                            <a href="index.php" class="btn btn-secondary btn-sm">
                                <i class="fas fa-arrow-left"></i> Back to List
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="p-4">
                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="row">
                            <div class="col-md-2 text-center">
                                <div class="profile-avatar">
                                    <i class="fas fa-user-md"></i>
                                </div>
                                <div class="mt-2">
                                    <span class="badge <?php echo $doctor['is_active'] ? 'bg-success' : 'bg-danger'; ?>">
                                        <?php echo $doctor['is_active'] ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-5">
                                <h3><?php echo escape($doctor['full_name']); ?></h3>
                                <p class="text-muted">@<?php echo $doctor['username']; ?></p>
                                <p><i class="fas fa-envelope"></i> <?php echo $doctor['email']; ?></p>
                                <p><i class="fas fa-calendar-alt"></i> Joined: <?php echo date(DISPLAY_DATE_FORMAT, strtotime($doctor['created_at'])); ?></p>
                                <?php if($doctor['last_login']): ?>
                                <p><i class="fas fa-sign-in-alt"></i> Last Login: <?php echo date(DISPLAY_DATE_TIME_FORMAT, strtotime($doctor['last_login'])); ?></p>
                                <?php endif; ?>
                            </div>
                            <div class="col-md-5">
                                <div class="card">
                                    <div class="card-body">
                                        <h6>Current Subscription</h6>
                                        <?php if($doctor['plan_type']): ?>
                                            <h4><?php echo ucfirst($doctor['plan_type']); ?></h4>
                                            <?php if($doctor['plan_type'] != 'unlimited'): ?>
                                                <p>Expires: <?php echo date(DISPLAY_DATE_FORMAT, strtotime($doctor['end_date'])); ?></p>
                                                <?php if($doctor['days_remaining'] > 0): ?>
                                                    <span class="badge bg-warning"><?php echo $doctor['days_remaining']; ?> days remaining</span>
                                                <?php else: ?>
                                                    <span class="badge bg-danger">Expired</span>
                                                <?php endif; ?>
                                            <?php else: ?>
                                                <span class="badge bg-info">Lifetime Access</span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <p class="text-muted">No active subscription</p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-number"><?php echo $caseStats['total_cases']; ?></div>
                                <div class="text-muted">Total Cases</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-number text-success"><?php echo $caseStats['active_cases']; ?></div>
                                <div class="text-muted">Active Cases</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-number text-warning"><?php echo $caseStats['follow_up_cases']; ?></div>
                                <div class="text-muted">Follow-up Required</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-card">
                                <div class="stat-number text-secondary"><?php echo $caseStats['closed_cases']; ?></div>
                                <div class="text-muted">Closed Cases</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <!-- Recent Cases -->
                        <div class="col-md-7">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-history"></i> Recent Cases</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead class="table-light">
                                                <tr><th>Date</th><th>Patient</th><th>Mobile</th><th>Remedy</th><th>Status</th><th>Action</th></tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach($recentCases as $case): ?>
                                                <tr>
                                                    <td><?php echo date('d-m-Y', strtotime($case['created_at'])); ?></td>
                                                    <td><?php echo escape($case['patient_name']); ?></td>
                                                    <td><?php echo $case['patient_mobile']; ?></td>
                                                    <td>
                                                        <?php 
                                                        if($case['prescribed_remedy_id']) {
                                                            $stmt = $pdo->prepare("SELECT name FROM remedies WHERE id = ?");
                                                            $stmt->execute([$case['prescribed_remedy_id']]);
                                                            $rem = $stmt->fetch();
                                                            echo $rem ? $rem['name'] : '-';
                                                        } else {
                                                            echo '-';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?php 
                                                            echo $case['status'] == 'active' ? 'success' : 
                                                                ($case['status'] == 'follow-up' ? 'warning' : 'secondary'); 
                                                        ?>">
                                                            <?php echo $case['status']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <a href="../../doctor/cases/view.php?id=<?php echo $case['id']; ?>" 
                                                           class="btn btn-sm btn-info" target="_blank">View</a>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php if(empty($recentCases)): ?>
                                                <tr><td colspan="6" class="text-center text-muted">No cases yet</td></tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Top Prescribed Remedies -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-capsules"></i> Top Prescribed Remedies</h5>
                                </div>
                                <div class="card-body">
                                    <?php if(!empty($topRemedies)): ?>
                                        <canvas id="remediesChart" height="200"></canvas>
                                    <?php else: ?>
                                        <p class="text-muted text-center">No prescriptions yet</p>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Subscription History & Monthly Trend -->
                        <div class="col-md-5">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-history"></i> Subscription History</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="list-group list-group-flush">
                                        <?php foreach($subscriptionHistory as $sub): ?>
                                            <div class="list-group-item">
                                                <div class="d-flex justify-content-between">
                                                    <strong><?php echo ucfirst($sub['plan_type']); ?></strong>
                                                    <span class="badge <?php echo $sub['is_active'] ? 'bg-success' : 'bg-secondary'; ?>">
                                                        <?php echo $sub['is_active'] ? 'Active' : 'Expired'; ?>
                                                    </span>
                                                </div>
                                                <small class="text-muted">
                                                    <?php echo date(DISPLAY_DATE_FORMAT, strtotime($sub['start_date'])); ?> - 
                                                    <?php echo $sub['end_date'] ? date(DISPLAY_DATE_FORMAT, strtotime($sub['end_date'])) : 'Unlimited'; ?>
                                                </small><br>
                                                <small>Amount: <?php echo formatCurrency($sub['amount']); ?></small>
                                            </div>
                                        <?php endforeach; ?>
                                        <?php if(empty($subscriptionHistory)): ?>
                                            <div class="list-group-item text-muted text-center">No subscription history</div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Monthly Case Trend -->
                            <?php if(!empty($monthlyTrend)): ?>
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-chart-line"></i> Monthly Case Trend</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="trendChart" height="200"></canvas>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        <?php if(!empty($topRemedies)): ?>
        // Remedies Chart
        const remediesCtx = document.getElementById('remediesChart').getContext('2d');
        new Chart(remediesCtx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode(array_column($topRemedies, 'name')); ?>,
                datasets: [{
                    label: 'Prescriptions',
                    data: <?php echo json_encode(array_column($topRemedies, 'count')); ?>,
                    backgroundColor: '#3498db',
                    borderRadius: 5
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: { display: false }
                }
            }
        });
        <?php endif; ?>
        
        <?php if(!empty($monthlyTrend)): ?>
        // Trend Chart
        const trendCtx = document.getElementById('trendChart').getContext('2d');
        new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode(array_reverse(array_column($monthlyTrend, 'month'))); ?>,
                datasets: [{
                    label: 'Cases',
                    data: <?php echo json_encode(array_reverse(array_column($monthlyTrend, 'count'))); ?>,
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.3,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true
            }
        });
        <?php endif; ?>
    </script>
</body>
</html>