<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get doctor ID
$doctor_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// If no ID provided and user is a doctor, show their own profile
if (!$doctor_id && in_array($_SESSION['role_code'], ['ENT_DOCTOR', 'ENT_CONSULTANT'])) {
    $doctor_id = $_SESSION['user_id'];
}

if (!$doctor_id) {
    header('Location: list_doctors.php');
    exit();
}

// Non-admin users can only view their own profile
if (!in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN']) && $doctor_id !== $_SESSION['user_id']) {
    header('Location: dashboard.php');
    exit();
}

// Fetch doctor details with user information
$doctor_sql = "SELECT 
                    d.*,
                    u.full_name, u.email, u.phone_primary, u.phone_secondary,
                    u.gender, u.date_of_birth, u.national_id, u.address,
                    u.profile_picture, u.status as user_status, u.created_at as user_created,
                    TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
                FROM doctors d
                INNER JOIN users u ON d.user_id = u.user_id
                WHERE d.doctor_id = ?";

$stmt = $conn->prepare($doctor_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: list_doctors.php');
    exit();
}

$doctor = $result->fetch_assoc();

// Get appointment statistics
$appointment_stats_sql = "SELECT 
                            COUNT(*) as total_appointments,
                            SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_appointments,
                            SUM(CASE WHEN status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled_appointments,
                            SUM(CASE WHEN status = 'CANCELLED' THEN 1 ELSE 0 END) as cancelled_appointments,
                            COUNT(DISTINCT patient_id) as unique_patients
                        FROM appointments
                        WHERE doctor_id = ?";
$stmt = $conn->prepare($appointment_stats_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$appointment_stats = $stmt->get_result()->fetch_assoc();

// Get consultation statistics
$consultation_stats_sql = "SELECT 
                            COUNT(*) as total_consultations,
                            SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_consultations
                        FROM consultations
                        WHERE doctor_id = ?";
$stmt = $conn->prepare($consultation_stats_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$consultation_stats = $stmt->get_result()->fetch_assoc();

// Get procedure statistics
$procedure_stats_sql = "SELECT 
                            COUNT(*) as total_procedures,
                            SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed_procedures
                        FROM patient_procedures
                        WHERE performed_by = ?";
$stmt = $conn->prepare($procedure_stats_sql);
$stmt->bind_param('i', $doctor['user_id']);
$stmt->execute();
$procedure_stats = $stmt->get_result()->fetch_assoc();

// Get financial summary - Current Month
$current_month = date('Y-m');
$financial_sql = "SELECT 
                    COALESCE(SUM(c.consultation_fee), 0) as consultation_revenue,
                    COALESCE(SUM(c.consultation_fee * (d.commission_rate / 100)), 0) as consultation_commission,
                    COALESCE((SELECT SUM(pp.cost * (d.commission_rate / 100)) 
                             FROM patient_procedures pp 
                             WHERE pp.performed_by = d.user_id 
                             AND pp.status = 'COMPLETED'
                             AND DATE_FORMAT(pp.completed_at, '%Y-%m') = ?), 0) as procedure_commission
                FROM consultations c
                INNER JOIN doctors d ON c.doctor_id = d.doctor_id
                WHERE c.doctor_id = ? 
                AND c.status = 'COMPLETED'
                AND DATE_FORMAT(c.completed_at, '%Y-%m') = ?";
$stmt = $conn->prepare($financial_sql);
$stmt->bind_param('sis', $current_month, $doctor_id, $current_month);
$stmt->execute();
$financial = $stmt->get_result()->fetch_assoc();

$total_commission = $financial['consultation_commission'] + $financial['procedure_commission'];
$total_revenue = $financial['consultation_revenue'];

// Get commission history (last 6 months)
$commission_history_sql = "SELECT 
                            DATE_FORMAT(c.completed_at, '%Y-%m') as month,
                            COUNT(*) as consultations_count,
                            SUM(c.consultation_fee) as total_revenue,
                            SUM(c.consultation_fee * (d.commission_rate / 100)) as commission
                        FROM consultations c
                        INNER JOIN doctors d ON c.doctor_id = d.doctor_id
                        WHERE c.doctor_id = ? 
                        AND c.status = 'COMPLETED'
                        AND c.completed_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
                        GROUP BY DATE_FORMAT(c.completed_at, '%Y-%m')
                        ORDER BY month DESC";
$stmt = $conn->prepare($commission_history_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$commission_history = $stmt->get_result();

// Get recent appointments
$recent_appointments_sql = "SELECT 
                                a.*,
                                u.full_name as patient_name,
                                u.phone_primary as patient_phone,
                                p.patient_number
                            FROM appointments a
                            INNER JOIN patients p ON a.patient_id = p.patient_id
                            INNER JOIN users u ON p.user_id = u.user_id
                            WHERE a.doctor_id = ?
                            ORDER BY a.appointment_date DESC, a.appointment_time DESC
                            LIMIT 10";
$stmt = $conn->prepare($recent_appointments_sql);
$stmt->bind_param('i', $doctor_id);
$stmt->execute();
$recent_appointments = $stmt->get_result();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Doctor Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .profile-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 3rem;
            font-weight: 700;
            color: #667eea;
            border: 5px solid rgba(255,255,255,0.3);
        }
        
        .profile-avatar img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            width: 200px;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        
        .badge-consultant {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-surgeon {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-active {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-inactive {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .commission-card {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
        }
        
        .commission-amount {
            font-size: 2.5rem;
            font-weight: 700;
            margin: 1rem 0;
        }
        
        .commission-details {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid rgba(255,255,255,0.2);
        }
        
        .commission-detail-item {
            text-align: center;
        }
        
        .commission-detail-label {
            font-size: 0.875rem;
            opacity: 0.9;
            margin-bottom: 0.5rem;
        }
        
        .commission-detail-value {
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .appointment-card {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            border-left: 4px solid #667eea;
        }
        
        .history-table {
            width: 100%;
        }
        
        .history-table th {
            background: #f8fafc;
            padding: 0.75rem;
            text-align: left;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .history-table td {
            padding: 0.75rem;
            border-bottom: 1px solid #e2e8f0;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Doctor Profile</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_doctors.php">Doctors</a></li>
                                        <li class="breadcrumb-item active">Profile</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Profile Header -->
                    <div class="profile-header">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div class="profile-avatar">
                                    <?php if ($doctor['profile_picture']): ?>
                                        <img src="<?php echo htmlspecialchars($doctor['profile_picture']); ?>" alt="Doctor Photo">
                                    <?php else: ?>
                                        <?php echo strtoupper(substr($doctor['full_name'], 0, 2)); ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col">
                                <h3 class="mb-2">Dr. <?php echo htmlspecialchars($doctor['full_name']); ?></h3>
                                <div class="d-flex gap-3 flex-wrap">
                                    <div>
                                        <i class="ri-stethoscope-line me-1"></i>
                                        <?php echo htmlspecialchars($doctor['specialization']); ?>
                                        <?php if ($doctor['sub_specialization']): ?>
                                            - <?php echo htmlspecialchars($doctor['sub_specialization']); ?>
                                        <?php endif; ?>
                                    </div>
                                    <div>
                                        <i class="ri-award-line me-1"></i>
                                        <?php echo $doctor['experience_years']; ?> years experience
                                    </div>
                                    <?php if ($doctor['is_consultant']): ?>
                                    <div>
                                        <span class="badge badge-consultant">Consultant</span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($doctor['is_surgeon']): ?>
                                    <div>
                                        <span class="badge badge-surgeon">Surgeon</span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="d-flex gap-3 flex-wrap mt-2">
                                    <div>
                                        <i class="ri-mail-line me-1"></i>
                                        <?php echo htmlspecialchars($doctor['email']); ?>
                                    </div>
                                    <div>
                                        <i class="ri-phone-line me-1"></i>
                                        <?php echo htmlspecialchars($doctor['phone_primary']); ?>
                                    </div>
                                    <div>
                                        <i class="ri-ID-line me-1"></i>
                                        License: <?php echo htmlspecialchars($doctor['medical_license']); ?>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="d-flex gap-2 flex-column">
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                    <a href="edit_doctor.php?id=<?php echo $doctor_id; ?>" class="btn btn-light">
                                        <i class="ri-edit-line me-1"></i> Edit Profile
                                    </a>
                                    <?php endif; ?>
                                    <a href="doctor_schedule.php?doctor_id=<?php echo $doctor_id; ?>" class="btn btn-light">
                                        <i class="ri-calendar-line me-1"></i> Schedule
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($appointment_stats['total_appointments']); ?></div>
                                <div class="stat-label">Total Appointments</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($consultation_stats['total_consultations']); ?></div>
                                <div class="stat-label">Consultations</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($procedure_stats['total_procedures']); ?></div>
                                <div class="stat-label">Procedures Performed</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($appointment_stats['unique_patients']); ?></div>
                                <div class="stat-label">Unique Patients</div>
                            </div>
                        </div>
                    </div>

                    <!-- Commission Summary -->
                    <div class="commission-card">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h5 class="mb-1"><i class="ri-money-dollar-circle-line me-2"></i>Commission Summary</h5>
                                <p class="mb-0" style="opacity: 0.9;"><?php echo date('F Y'); ?> | Rate: <?php echo number_format($doctor['commission_rate'], 2); ?>%</p>
                            </div>
                        </div>
                        <div class="commission-amount">
                            KES <?php echo number_format($total_commission, 2); ?>
                        </div>
                        <div class="commission-details">
                            <div class="commission-detail-item">
                                <div class="commission-detail-label">Total Revenue</div>
                                <div class="commission-detail-value">KES <?php echo number_format($total_revenue, 2); ?></div>
                            </div>
                            <div class="commission-detail-item">
                                <div class="commission-detail-label">Consultation Fee</div>
                                <div class="commission-detail-value">KES <?php echo number_format($doctor['consultation_fee'], 2); ?></div>
                            </div>
                            <div class="commission-detail-item">
                                <div class="commission-detail-label">Follow-up Fee</div>
                                <div class="commission-detail-value">KES <?php echo number_format($doctor['follow_up_fee'], 2); ?></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-4">
                            <!-- Professional Information -->
                            <div class="info-card">
                                <h5><i class="ri-user-star-line me-2"></i>Professional Information</h5>
                                <div class="info-row">
                                    <div class="info-label">Medical License</div>
                                    <div class="info-value"><strong><?php echo htmlspecialchars($doctor['medical_license']); ?></strong></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Specialization</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['specialization']); ?></div>
                                </div>
                                <?php if ($doctor['sub_specialization']): ?>
                                <div class="info-row">
                                    <div class="info-label">Sub-Specialization</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['sub_specialization']); ?></div>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <div class="info-label">Qualification</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['qualification']); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Experience</div>
                                    <div class="info-value"><?php echo $doctor['experience_years']; ?> years</div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Status</div>
                                    <div class="info-value">
                                        <span class="badge <?php echo $doctor['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                            <?php echo $doctor['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Practice Details -->
                            <div class="info-card">
                                <h5><i class="ri-hospital-line me-2"></i>Practice Details</h5>
                                <div class="info-row">
                                    <div class="info-label">Appointment Duration</div>
                                    <div class="info-value"><?php echo $doctor['appointment_duration']; ?> minutes</div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Max Daily Appointments</div>
                                    <div class="info-value"><?php echo $doctor['max_daily_appointments']; ?> patients</div>
                                </div>
                                <?php if ($doctor['languages_spoken']): ?>
                                <div class="info-row">
                                    <div class="info-label">Languages</div>
                                    <div class="info-value">
                                        <?php 
                                        $languages = json_decode($doctor['languages_spoken'], true);
                                        echo is_array($languages) ? implode(', ', $languages) : $doctor['languages_spoken'];
                                        ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <?php if ($doctor['consultation_rooms']): ?>
                                <div class="info-row">
                                    <div class="info-label">Consultation Rooms</div>
                                    <div class="info-value">
                                        <?php 
                                        $rooms = json_decode($doctor['consultation_rooms'], true);
                                        echo is_array($rooms) ? implode(', ', $rooms) : $doctor['consultation_rooms'];
                                        ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Financial Information -->
                            <div class="info-card">
                                <h5><i class="ri-money-dollar-circle-line me-2"></i>Financial Information</h5>
                                <div class="info-row">
                                    <div class="info-label">Consultation Fee</div>
                                    <div class="info-value"><strong>KES <?php echo number_format($doctor['consultation_fee'], 2); ?></strong></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Follow-up Fee</div>
                                    <div class="info-value"><strong>KES <?php echo number_format($doctor['follow_up_fee'], 2); ?></strong></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Commission Rate</div>
                                    <div class="info-value"><strong><?php echo number_format($doctor['commission_rate'], 2); ?>%</strong></div>
                                </div>
                            </div>

                            <!-- Personal Information -->
                            <div class="info-card">
                                <h5><i class="ri-user-line me-2"></i>Personal Information</h5>
                                <div class="info-row">
                                    <div class="info-label">Date of Birth</div>
                                    <div class="info-value"><?php echo date('d M Y', strtotime($doctor['date_of_birth'])); ?></div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Age</div>
                                    <div class="info-value"><?php echo $doctor['age']; ?> years</div>
                                </div>
                                <div class="info-row">
                                    <div class="info-label">Gender</div>
                                    <div class="info-value"><?php echo ucfirst(strtolower($doctor['gender'])); ?></div>
                                </div>
                                <?php if ($doctor['national_id']): ?>
                                <div class="info-row">
                                    <div class="info-label">National ID</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['national_id']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($doctor['phone_secondary']): ?>
                                <div class="info-row">
                                    <div class="info-label">Secondary Phone</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['phone_secondary']); ?></div>
                                </div>
                                <?php endif; ?>
                                <?php if ($doctor['address']): ?>
                                <div class="info-row">
                                    <div class="info-label">Address</div>
                                    <div class="info-value"><?php echo htmlspecialchars($doctor['address']); ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-8">
                            <!-- Recent Appointments -->
                            <div class="info-card">
                                <h5><i class="ri-calendar-line me-2"></i>Recent Appointments</h5>
                                <?php if ($recent_appointments->num_rows > 0): ?>
                                    <?php while($appointment = $recent_appointments->fetch_assoc()): ?>
                                    <div class="appointment-card">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="fw-bold"><?php echo htmlspecialchars($appointment['patient_name']); ?></div>
                                                <div class="text-muted small">
                                                    Patient #: <?php echo htmlspecialchars($appointment['patient_number']); ?> | 
                                                    <?php echo htmlspecialchars($appointment['patient_phone']); ?>
                                                </div>
                                                <div class="text-muted small mt-1">
                                                    <i class="ri-calendar-line me-1"></i>
                                                    <?php echo date('d M Y', strtotime($appointment['appointment_date'])); ?> at 
                                                    <?php echo date('h:i A', strtotime($appointment['appointment_time'])); ?>
                                                </div>
                                                <?php if ($appointment['reason']): ?>
                                                <div class="small mt-1">
                                                    <strong>Reason:</strong> <?php echo htmlspecialchars($appointment['reason']); ?>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="text-end">
                                                <span class="badge bg-<?php 
                                                    echo $appointment['status'] === 'COMPLETED' ? 'success' : 
                                                        ($appointment['status'] === 'SCHEDULED' ? 'info' : 
                                                        ($appointment['status'] === 'CANCELLED' ? 'danger' : 'warning')); 
                                                ?>">
                                                    <?php echo str_replace('_', ' ', $appointment['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                    <div class="text-center mt-3">
                                        <a href="list_appointments.php?doctor_id=<?php echo $doctor_id; ?>" class="btn btn-sm btn-outline-primary">
                                            View All Appointments
                                        </a>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center text-muted py-3">
                                        No appointments recorded yet
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Commission History -->
                            <div class="info-card">
                                <h5><i class="ri-line-chart-line me-2"></i>Commission History (Last 6 Months)</h5>
                                <?php if ($commission_history->num_rows > 0): ?>
                                <div class="table-responsive">
                                    <table class="history-table">
                                        <thead>
                                            <tr>
                                                <th>Month</th>
                                                <th>Consultations</th>
                                                <th>Total Revenue</th>
                                                <th>Commission Earned</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while($history = $commission_history->fetch_assoc()): ?>
                                            <tr>
                                                <td><?php echo date('M Y', strtotime($history['month'] . '-01')); ?></td>
                                                <td><?php echo number_format($history['consultations_count']); ?></td>
                                                <td>KES <?php echo number_format($history['total_revenue'], 2); ?></td>
                                                <td class="fw-bold text-success">KES <?php echo number_format($history['commission'], 2); ?></td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                                <?php else: ?>
                                    <div class="text-center text-muted py-3">
                                        No commission history available
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Account Information -->
                            <div class="info-card">
                                <h5><i class="ri-information-line me-2"></i>Account Information</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">User ID</div>
                                            <div class="info-value"><?php echo $doctor['user_id']; ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Doctor ID</div>
                                            <div class="info-value"><?php echo $doctor['doctor_id']; ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Joined Date</div>
                                            <div class="info-value"><?php echo date('d M Y', strtotime($doctor['created_at'])); ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Account Status</div>
                                            <div class="info-value">
                                                <span class="badge <?php echo $doctor['user_status'] === 'ACTIVE' ? 'badge-active' : 'badge-inactive'; ?>">
                                                    <?php echo $doctor['user_status']; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Doctor Status</div>
                                            <div class="info-value">
                                                <span class="badge <?php echo $doctor['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                                    <?php echo $doctor['is_active'] ? 'Active' : 'Inactive'; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Last Updated</div>
                                            <div class="info-value"><?php echo date('d M Y', strtotime($doctor['updated_at'])); ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Performance Metrics -->
                            <div class="info-card">
                                <h5><i class="ri-bar-chart-line me-2"></i>Performance Metrics</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Total Appointments</div>
                                            <div class="info-value"><strong><?php echo number_format($appointment_stats['total_appointments']); ?></strong></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Completed</div>
                                            <div class="info-value text-success">
                                                <?php echo number_format($appointment_stats['completed_appointments']); ?>
                                                <?php if ($appointment_stats['total_appointments'] > 0): ?>
                                                    (<?php echo number_format(($appointment_stats['completed_appointments'] / $appointment_stats['total_appointments']) * 100, 1); ?>%)
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Cancelled</div>
                                            <div class="info-value text-danger">
                                                <?php echo number_format($appointment_stats['cancelled_appointments']); ?>
                                                <?php if ($appointment_stats['total_appointments'] > 0): ?>
                                                    (<?php echo number_format(($appointment_stats['cancelled_appointments'] / $appointment_stats['total_appointments']) * 100, 1); ?>%)
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Total Consultations</div>
                                            <div class="info-value"><strong><?php echo number_format($consultation_stats['total_consultations']); ?></strong></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Completed Consultations</div>
                                            <div class="info-value text-success"><?php echo number_format($consultation_stats['completed_consultations']); ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Procedures Performed</div>
                                            <div class="info-value"><strong><?php echo number_format($procedure_stats['total_procedures']); ?></strong></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Completed Procedures</div>
                                            <div class="info-value text-success"><?php echo number_format($procedure_stats['completed_procedures']); ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>

    <script>
        // Show success message if redirected with success parameter
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('success') === 'updated') {
            Swal.fire({
                icon: 'success',
                title: 'Profile Updated',
                text: 'Doctor profile has been updated successfully',
                timer: 3000,
                showConfirmButton: false
            });
        }

        // Confirm before deactivating doctor
        function deactivateDoctor(doctorId) {
            Swal.fire({
                title: 'Deactivate Doctor?',
                text: "This doctor will not be able to take new appointments",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, deactivate'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'deactivate_doctor.php?id=' + doctorId;
                }
            });
        }

        // Print doctor profile
        function printProfile() {
            window.print();
        }
    </script>

    <style media="print">
        .page-title-box, .btn, .breadcrumb, #layout-wrapper > div:first-child {
            display: none !important;
        }
        
        .info-card, .stat-card, .commission-card {
            break-inside: avoid;
            page-break-inside: avoid;
        }
        
        body {
            background: white !important;
        }
    </style>
</body>
</html>