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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'RESIDENT_DOCTOR') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

try {
    $resident_doctor_id = (int)$_POST['resident_doctor_id'];
    $log_date = mysqli_real_escape_string($conn, $_POST['log_date']);
    $activity_type = mysqli_real_escape_string($conn, $_POST['activity_type']);
    $activity_title = mysqli_real_escape_string($conn, $_POST['activity_title']);
    $patient_id = !empty($_POST['patient_id']) ? (int)$_POST['patient_id'] : NULL;
    $supervisor_id = !empty($_POST['supervisor_id']) ? (int)$_POST['supervisor_id'] : NULL;
    $duration_hours = !empty($_POST['duration_hours']) ? (float)$_POST['duration_hours'] : NULL;
    $competency_level = mysqli_real_escape_string($conn, $_POST['competency_level']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $learning_points = mysqli_real_escape_string($conn, $_POST['learning_points']);
    $challenges_faced = mysqli_real_escape_string($conn, $_POST['challenges_faced']);
    $self_assessment_score = !empty($_POST['self_assessment_score']) ? (int)$_POST['self_assessment_score'] : NULL;
    $supervisor_present = (int)$_POST['supervisor_present'];
    $status = mysqli_real_escape_string($conn, $_POST['status']); // DRAFT or SUBMITTED

    // Insert training log
    $sql = "INSERT INTO resident_training_log (
                resident_doctor_id, log_date, activity_type, activity_title,
                patient_id, supervisor_id, duration_hours, competency_level,
                description, learning_points, challenges_faced,
                self_assessment_score, supervisor_present, status
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param(
        'isssiidssssiis',
        $resident_doctor_id, $log_date, $activity_type, $activity_title,
        $patient_id, $supervisor_id, $duration_hours, $competency_level,
        $description, $learning_points, $challenges_faced,
        $self_assessment_score, $supervisor_present, $status
    );

    if ($stmt->execute()) {
        $log_id = $stmt->insert_id;
        
        // Log activity
        $activity_desc = "Added training log entry: " . $activity_title;
        $activity_sql = "INSERT INTO activity_logs (user_id, activity_type, activity_description) VALUES (?, 'TRAINING_LOG', ?)";
        $activity_stmt = $conn->prepare($activity_sql);
        $activity_stmt->bind_param('is', $_SESSION['user_id'], $activity_desc);
        $activity_stmt->execute();

        echo json_encode([
            'success' => true,
            'message' => $status === 'SUBMITTED' ? 'Training log submitted successfully!' : 'Training log saved as draft!',
            'log_id' => $log_id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save training log: ' . $stmt->error]);
    }

    $stmt->close();
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}

mysqli_close($conn);
?>