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

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

$page_title = "Training Log";
$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();
$doctor = $stmt->get_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-d');

// Fetch training logs
$logs_sql = "SELECT 
                rtl.*,
                p.patient_number,
                u.full_name as patient_name,
                sv.full_name as supervisor_name,
                rv.full_name as reviewed_by_name
              FROM resident_training_log rtl
              LEFT JOIN patients p ON rtl.patient_id = p.patient_id
              LEFT JOIN users u ON p.user_id = u.user_id
              LEFT JOIN doctors sv_doc ON rtl.supervisor_id = sv_doc.doctor_id
              LEFT JOIN users sv ON sv_doc.user_id = sv.user_id
              LEFT JOIN users rv ON rtl.reviewed_by = rv.user_id
              WHERE rtl.resident_doctor_id = ?
              AND rtl.log_date BETWEEN ? AND ?
              ORDER BY rtl.log_date DESC, rtl.created_at DESC";

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

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_entries,
                SUM(CASE WHEN status = 'APPROVED' THEN 1 ELSE 0 END) as approved_entries,
                SUM(CASE WHEN activity_type = 'CONSULTATION' THEN 1 ELSE 0 END) as consultations,
                SUM(CASE WHEN activity_type = 'PROCEDURE' THEN 1 ELSE 0 END) as procedures,
                COALESCE(SUM(duration_hours), 0) as total_hours,
                ROUND(AVG(self_assessment_score), 1) as avg_self_rating,
                ROUND(AVG(supervisor_rating), 1) as avg_supervisor_rating
              FROM resident_training_log
              WHERE resident_doctor_id = ?
              AND log_date 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();

// Get my assigned patients for dropdown
$patients_sql = "SELECT DISTINCT p.patient_id, p.patient_number, u.full_name as patient_name
                 FROM resident_patient_assignments rpa
                 INNER JOIN patients p ON rpa.patient_id = p.patient_id
                 INNER JOIN users u ON p.user_id = u.user_id
                 WHERE rpa.resident_doctor_id = ? AND rpa.status = 'ACTIVE'
                 ORDER BY u.full_name";

$stmt = $conn->prepare($patients_sql);
$stmt->bind_param('i', $resident_doctor_id);
$stmt->execute();
$assigned_patients = $stmt->get_result();

// Get supervisors
$supervisors_sql = "SELECT DISTINCT d.doctor_id, u.full_name as supervisor_name
                    FROM resident_patient_assignments rpa
                    INNER JOIN doctors d ON rpa.supervisor_doctor_id = d.doctor_id
                    INNER JOIN users u ON d.user_id = u.user_id
                    WHERE rpa.resident_doctor_id = ?
                    ORDER BY u.full_name";

$stmt = $conn->prepare($supervisors_sql);
$stmt->bind_param('i', $resident_doctor_id);
$stmt->execute();
$supervisors = $stmt->get_result();
?>

<?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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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-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-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .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-activity {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .badge-consultation { background: #dcfce7; color: #166534; }
        .badge-procedure { background: #dbeafe; color: #1e40af; }
        .badge-surgery { background: #fee2e2; color: #991b1b; }
        .badge-rounds { background: #fef3c7; color: #92400e; }
        .badge-seminar { background: #f3e8ff; color: #6b21a8; }
        .badge-workshop { background: #e0f2fe; color: #075985; }
        
        .status-draft { color: #64748b; }
        .status-submitted { color: #3b82f6; }
        .status-reviewed { color: #f59e0b; }
        .status-approved { color: #059669; }
        
        .competency-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .competency-observed { background: #f1f5f9; color: #64748b; }
        .competency-assisted { background: #dbeafe; color: #1e40af; }
        .competency-supervised { background: #fef3c7; color: #92400e; }
        .competency-independent { background: #dcfce7; color: #166534; }
    </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">Document your daily training activities and learning progress</p>
                            </div>
                            <button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addLogModal">
                                <i class="ri-add-line me-1"></i> Add Training Entry
                            </button>
                        </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
                                            </button>
                                            <a href="training_log.php" class="btn btn-outline-secondary">
                                                <i class="ri-refresh-line me-1"></i> Reset
                                            </a>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

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

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="ri-check-double-line"></i>
                                </div>
                                <div class="stat-value"><?php echo $stats['approved_entries']; ?></div>
                                <div class="stat-label">Approved Entries</div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon info">
                                    <i class="ri-time-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($stats['total_hours'], 1); ?>h</div>
                                <div class="stat-label">Training Hours</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_supervisor_rating'] ?? 'N/A'; ?></div>
                                <div class="stat-label">Avg Supervisor Rating</div>
                            </div>
                        </div>
                    </div>

                    <!-- Training Log Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Training Log Entries</h5>
                                
                                <div class="table-responsive">
                                    <table id="logsTable" class="table table-hover">
                                        <thead class="bg-light">
                                            <tr>
                                                <th>Date</th>
                                                <th>Activity</th>
                                                <th>Patient</th>
                                                <th>Duration</th>
                                                <th>Competency</th>
                                                <th>Self Rating</th>
                                                <th>Supervisor Rating</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($training_logs->num_rows > 0): ?>
                                                <?php while($log = $training_logs->fetch_assoc()): ?>
                                                <tr>
                                                    <td>
                                                        <strong><?php echo date('M d, Y', strtotime($log['log_date'])); ?></strong>
                                                    </td>
                                                    <td>
                                                        <span class="badge-activity badge-<?php echo strtolower($log['activity_type']); ?>">
                                                            <?php echo $log['activity_type']; ?>
                                                        </span>
                                                        <div><small><?php echo htmlspecialchars($log['activity_title']); ?></small></div>
                                                    </td>
                                                    <td>
                                                        <?php 
                                                        if ($log['patient_name']) {
                                                            echo htmlspecialchars($log['patient_name']);
                                                            echo '<br><small class="text-muted">' . $log['patient_number'] . '</small>';
                                                        } else {
                                                            echo '<span class="text-muted">N/A</span>';
                                                        }
                                                        ?>
                                                    </td>
                                                    <td><?php echo $log['duration_hours'] ? $log['duration_hours'] . ' hrs' : '-'; ?></td>
                                                    <td>
                                                        <span class="competency-badge competency-<?php echo strtolower($log['competency_level']); ?>">
                                                            <?php echo $log['competency_level']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php echo $log['self_assessment_score'] ? $log['self_assessment_score'] . '/10' : '-'; ?>
                                                    </td>
                                                    <td>
                                                        <?php echo $log['supervisor_rating'] ? $log['supervisor_rating'] . '/10' : '-'; ?>
                                                    </td>
                                                    <td>
                                                        <span class="status-<?php echo strtolower($log['status']); ?>">
                                                            <strong><?php echo $log['status']; ?></strong>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button class="btn btn-outline-primary view-log-btn" data-id="<?php echo $log['log_id']; ?>">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <?php if ($log['status'] === 'DRAFT'): ?>
                                                            <button class="btn btn-outline-success submit-log-btn" data-id="<?php echo $log['log_id']; ?>">
                                                                <i class="ri-send-plane-line"></i>
                                                            </button>
                                                            <?php endif; ?>
                                                        </div>
                                                    </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 training log entries found</p>
                                                            <button class="btn btn-primary mt-2" data-bs-toggle="modal" data-bs-target="#addLogModal">
                                                                <i class="ri-add-line me-1"></i> Add Your First Entry
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Add Log Modal -->
    <div class="modal fade" id="addLogModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <form id="addLogForm">
                    <div class="modal-header">
                        <h5 class="modal-title">Add Training Log Entry</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Log Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="log_date" required value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Activity Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="activity_type" required>
                                    <option value="">Select Type</option>
                                    <option value="CONSULTATION">Consultation</option>
                                    <option value="PROCEDURE">Procedure</option>
                                    <option value="SURGERY">Surgery</option>
                                    <option value="ROUNDS">Rounds</option>
                                    <option value="SEMINAR">Seminar</option>
                                    <option value="WORKSHOP">Workshop</option>
                                    <option value="RESEARCH">Research</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">Activity Title <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="activity_title" required placeholder="Brief title of the activity">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Patient (if applicable)</label>
                                <select class="form-select select2" name="patient_id">
                                    <option value="">Select Patient</option>
                                    <?php while($pat = $assigned_patients->fetch_assoc()): ?>
                                    <option value="<?php echo $pat['patient_id']; ?>">
                                        <?php echo htmlspecialchars($pat['patient_name']) . ' (' . $pat['patient_number'] . ')'; ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Supervisor</label>
                                <select class="form-select select2" name="supervisor_id">
                                    <option value="">Select Supervisor</option>
                                    <?php while($sup = $supervisors->fetch_assoc()): ?>
                                    <option value="<?php echo $sup['doctor_id']; ?>">
                                        <?php echo htmlspecialchars($sup['supervisor_name']); ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Duration (hours)</label>
                                <input type="number" step="0.5" class="form-control" name="duration_hours" placeholder="e.g., 2.5">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Competency Level <span class="text-danger">*</span></label>
                                <select class="form-select" name="competency_level" required>
                                    <option value="OBSERVED">Observed Only</option>
                                    <option value="ASSISTED">Assisted</option>
                                    <option value="SUPERVISED">Performed Under Supervision</option>
                                    <option value="INDEPENDENT">Performed Independently</option>
                                </select>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">Description</label>
                                <textarea class="form-control" name="description" rows="3" placeholder="Describe what you did..."></textarea>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">Learning Points</label>
                                <textarea class="form-control" name="learning_points" rows="3" placeholder="Key things you learned..."></textarea>
                            </div>
                            <div class="col-md-12">
                                <label class="form-label">Challenges Faced</label>
                                <textarea class="form-control" name="challenges_faced" rows="2" placeholder="Difficulties encountered..."></textarea>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Self Assessment (1-10)</label>
                                <input type="number" min="1" max="10" class="form-control" name="self_assessment_score" placeholder="Rate yourself">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Supervisor Present?</label>
                                <select class="form-select" name="supervisor_present">
                                    <option value="1">Yes</option>
                                    <option value="0">No</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-save-line me-1"></i> Save as Draft
                        </button>
                        <button type="button" class="btn btn-primary" id="submitBtn">
                            <i class="ri-send-plane-line me-1"></i> Save & Submit
                        </button>
                    </div>
                </form>
            </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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            $('.select2').select2({
                theme: 'bootstrap-5',
                dropdownParent: $('#addLogModal')
            });

            $('#logsTable').DataTable({
                order: [[0, 'desc']],
                pageLength: 25
            });

            // Add log form submission
            $('#addLogForm').on('submit', function(e) {
                e.preventDefault();
                const formData = new FormData(this);
                formData.append('status', 'DRAFT');
                formData.append('resident_doctor_id', <?php echo $resident_doctor_id; ?>);
                
                $.ajax({
                    url: 'ajax/add_training_log.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        const data = JSON.parse(response);
                        if (data.success) {
                            Swal.fire('Success!', data.message, 'success').then(() => location.reload());
                        } else {
                            Swal.fire('Error!', data.message, 'error');
                        }
                    }
                });
            });

            $('#submitBtn').on('click', function() {
                const formData = new FormData($('#addLogForm')[0]);
                formData.append('status', 'SUBMITTED');
                formData.append('resident_doctor_id', <?php echo $resident_doctor_id; ?>);
                
                $.ajax({
                    url: 'ajax/add_training_log.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        const data = JSON.parse(response);
                        if (data.success) {
                            Swal.fire('Success!', data.message, 'success').then(() => location.reload());
                        } else {
                            Swal.fire('Error!', data.message, 'error');
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>