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

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

if ($_SESSION['role_code'] !== 'RESIDENT_DOCTOR') {
    header('Location: index.php');
    exit();
}

$page_title = "Supervised Consultations";
$user_id = $_SESSION['user_id'];

// Get resident doctor ID
$doctor_sql = "SELECT doctor_id FROM doctors WHERE user_id = ?";
$stmt = $conn->prepare($doctor_sql);
$stmt->bind_param('i', $user_id);
$stmt->execute();
$result = $stmt->get_result();
$doctor = $result->fetch_assoc();
$resident_doctor_id = $doctor['doctor_id'];

// Get date filter
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-t');

// Fetch supervised consultations
$consultations_sql = "SELECT 
                        rsc.*,
                        c.consultation_number,
                        c.chief_complaint,
                        c.diagnosis_primary,
                        c.status as consultation_status,
                        c.started_at as consultation_date,
                        c.consultation_fee,
                        p.patient_number,
                        u.full_name as patient_name,
                        u.gender,
                        u.date_of_birth,
                        TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
                        sv.full_name as supervisor_name,
                        pv.visit_number
                      FROM resident_supervised_consultations rsc
                      INNER JOIN consultations c ON rsc.consultation_id = c.consultation_id
                      INNER JOIN patients p ON c.patient_id = p.patient_id
                      INNER JOIN users u ON p.user_id = u.user_id
                      INNER JOIN doctors sv_doc ON rsc.supervisor_id = sv_doc.doctor_id
                      INNER JOIN users sv ON sv_doc.user_id = sv.user_id
                      LEFT JOIN patient_visits pv ON c.visit_id = pv.visit_id
                      WHERE rsc.resident_doctor_id = ?
                      AND DATE(c.started_at) BETWEEN ? AND ?
                      ORDER BY c.started_at DESC";

$stmt = $conn->prepare($consultations_sql);
$stmt->bind_param('iss', $resident_doctor_id, $date_from, $date_to);
$stmt->execute();
$consultations = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_consultations,
                SUM(CASE WHEN rsc.supervision_level = 'DIRECT_OBSERVATION' THEN 1 ELSE 0 END) as direct_observations,
                SUM(CASE WHEN rsc.learning_value = 'HIGH' OR rsc.learning_value = 'EXCEPTIONAL' THEN 1 ELSE 0 END) as high_value_cases,
                ROUND(AVG(rsc.competency_rating), 1) as avg_rating,
                COUNT(DISTINCT rsc.supervisor_id) as total_supervisors
              FROM resident_supervised_consultations rsc
              INNER JOIN consultations c ON rsc.consultation_id = c.consultation_id
              WHERE rsc.resident_doctor_id = ?
              AND DATE(c.started_at) BETWEEN ? AND ?";

$stmt = $conn->prepare($stats_sql);
$stmt->bind_param('iss', $resident_doctor_id, $date_from, $date_to);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #1e5a1e 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .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;
            margin-bottom: 1.5rem;
            height: 100%;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 1rem;
        }
        
        .stat-icon.primary { background: linear-gradient(135deg, #2d7a2d 0%, #1e5a1e 100%); color: white; }
        .stat-icon.success { background: linear-gradient(135deg, #059669 0%, #047857 100%); color: white; }
        .stat-icon.info { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white; }
        .stat-icon.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; }
        .stat-icon.purple { background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; }
        
        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .chart-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;
        }
        
        .badge-supervision {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .badge-direct { background: #dcfce7; color: #166534; }
        .badge-same-room { background: #dbeafe; color: #1e40af; }
        .badge-immediate { background: #fef3c7; color: #92400e; }
        .badge-post { background: #f3e8ff; color: #6b21a8; }
        
        .learning-value-low { color: #64748b; }
        .learning-value-medium { color: #3b82f6; }
        .learning-value-high { color: #f59e0b; }
        .learning-value-exceptional { color: #dc2626; }
        
        .rating-stars {
            color: #f59e0b;
            font-size: 0.875rem;
        }
        
        .consultation-details {
            border-left: 3px solid #2d7a2d;
            padding-left: 1rem;
            margin: 1rem 0;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="content-page">
            <div class="content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-1"><?php echo $page_title; ?></h3>
                                <p class="mb-0 opacity-75">Track consultations performed under supervision</p>
                            </div>
                        </div>
                    </div>

                    <!-- Date Filter -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="chart-card">
                                <form method="GET" class="row g-3">
                                    <div class="col-md-4">
                                        <label class="form-label">From Date</label>
                                        <input type="date" name="date_from" class="form-control" value="<?php echo $date_from; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">To Date</label>
                                        <input type="date" name="date_to" class="form-control" value="<?php echo $date_to; ?>">
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <button type="submit" class="btn btn-primary me-2">
                                                <i class="ri-filter-line me-1"></i> Apply Filter
                                            </button>
                                            <a href="supervised_consultations.php" class="btn btn-outline-secondary">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </a>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon primary">
                                    <i class="ri-stethoscope-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['total_consultations']; ?></div>
                                <div class="stat-label">Total Consultations</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="ri-eye-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['direct_observations']; ?></div>
                                <div class="stat-label">Direct Observations</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon warning">
                                    <i class="ri-star-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['avg_rating'] ?? 'N/A'; ?></div>
                                <div class="stat-label">Average Rating</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon purple">
                                    <i class="ri-lightbulb-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['high_value_cases']; ?></div>
                                <div class="stat-label">High Value Cases</div>
                            </div>
                        </div>
                    </div>

                    <!-- Consultations List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Consultation Records</h5>
                                
                                <div class="table-responsive">
                                    <table id="consultationsTable" class="table table-hover">
                                        <thead class="bg-light">
                                            <tr>
                                                <th>Date</th>
                                                <th>Patient</th>
                                                <th>Visit Number</th>
                                                <th>Chief Complaint</th>
                                                <th>Supervision Level</th>
                                                <th>Supervisor</th>
                                                <th>Rating</th>
                                                <th>Learning Value</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($consultations->num_rows > 0): ?>
                                                <?php while($cons = $consultations->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo date('M d, Y', strtotime($cons['consultation_date'])); ?></strong>
                                                        <br><small class="text-muted"><?php echo date('h:i A', strtotime($cons['consultation_date'])); ?></small>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($cons['patient_name']); ?></strong>
                                                            <br><small class="text-muted"><?php echo $cons['age']; ?>Y / <?php echo $cons['gender']; ?></small>
                                                        </div>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($cons['visit_number']); ?></td>
                                                    <td>
                                                        <?php 
                                                        $complaint = $cons['chief_complaint'];
                                                        echo htmlspecialchars(strlen($complaint) > 50 ? substr($complaint, 0, 50) . '...' : $complaint); 
                                                        ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge-supervision badge-<?php echo strtolower(str_replace('_', '-', $cons['supervision_level'])); ?>">
                                                            <?php echo str_replace('_', ' ', $cons['supervision_level']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($cons['supervisor_name']); ?></td>
                                                    <td>
                                                        <?php if ($cons['competency_rating']): ?>
                                                            <span class="rating-stars">
                                                                <?php for($i = 1; $i <= 10; $i++): ?>
                                                                    <?php if ($i <= $cons['competency_rating']): ?>
                                                                        <i class="ri-star-fill"></i>
                                                                    <?php else: ?>
                                                                        <i class="ri-star-line"></i>
                                                                    <?php endif; ?>
                                                                <?php endfor; ?>
                                                            </span>
                                                            <div><small><?php echo $cons['competency_rating']; ?>/10</small></div>
                                                        <?php else: ?>
                                                            <span class="text-muted">Not rated</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="learning-value-<?php echo strtolower($cons['learning_value']); ?>">
                                                            <strong><?php echo $cons['learning_value']; ?></strong>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-sm btn-outline-primary view-details-btn" 
                                                                data-id="<?php echo $cons['supervised_consultation_id']; ?>">
                                                            <i class="ri-eye-line"></i> View
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr>
                                                    <td colspan="9" class="text-center py-4">
                                                        <div class="text-muted">
                                                            <i class="ri-information-line" style="font-size: 2rem;"></i>
                                                            <p class="mt-2">No supervised consultations found for the selected period</p>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Details Modal -->
    <div class="modal fade" id="detailsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Consultation Details & Supervision Notes</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="modalContent">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </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="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#consultationsTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25,
                language: {
                    search: "Search consultations:",
                    lengthMenu: "Show _MENU_ consultations per page"
                }
            });

            // View details
            $('.view-details-btn').on('click', function() {
                const id = $(this).data('id');
                
                $('#modalContent').html(`
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                `);
                
                new bootstrap.Modal(document.getElementById('detailsModal')).show();
                
                // Load consultation details via AJAX
                $.ajax({
                    url: 'ajax/get_supervised_consultation_details.php',
                    type: 'GET',
                    data: { id: id },
                    success: function(response) {
                        $('#modalContent').html(response);
                    },
                    error: function() {
                        $('#modalContent').html(`
                            <div class="alert alert-danger">
                                <i class="ri-error-warning-line me-2"></i>
                                Failed to load consultation details. Please try again.
                            </div>
                        `);
                    }
                });
            });
        });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>