{% load static %}
{% include 'registration_form/header.html' %}

<style>
    /* Existing styles remain unchanged, only new or modified styles are highlighted */
    #complete-button, #gate-pass{
        display: none;
        margin-top: 10px;
        padding: 10px 20px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        color: white;
    }
    #safety_video {
        display: none;
    }

    #complete-button { background-color: #3c8dbc; }
    #complete-button:hover { background-color: #45a049; }

    #print-button, #back-button { background-color: #3c8dbc; }
    #print-button:hover { background-color: #0056b3; }

    .gate-pass-header, .pass-status {
        text-align: center;
        font-weight: bold;
    }

    .pass-status { font-size: 1.5em; color: green; margin-top: 10px; }

    .gate-pass-row {
        display: flex;
        justify-content: space-between;
        margin-bottom: 5px;
    }

    @media print {
        body, body * {
            visibility: hidden;
            margin: 0;
            padding: 0;
        }
        #gate-pass, #gate-pass * {
            visibility: visible;
        }
        #gate-pass {
            position: absolute;
            top: 0;
            left: 0;
            width: 210mm;
            min-height: 297mm;
            margin: 5mm;
            padding: 5mm;
            box-sizing: border-box;
            page-break-inside: avoid;
            page-break-after: avoid;
            background-color: #ffffff;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        #complete-button, .button-container, .sidebar {
            display: none !important;
            visibility: hidden !important;
        }
        .crad-v {
            max-width: 190mm;
            padding: 6mm;
            border: 1px solid #000 !important;
            box-shadow: none !important;
            box-sizing: border-box;
            font-size: 10px;
            line-height: 1.2;
        }
        .field-name {
            margin-bottom: 2px;
            font-size: 9px;
        }
        .field-name span {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .imglogo-v img, .com-img {
            max-width: 60px !important;
            height: auto !important;
            margin: 0 5px;
        }
        .heading h2 {
            font-size: 14px;
            margin: 4px 0;
        }
        .op-bottom {
            margin-top: 8px;
            padding: 2px 0;
        }
        .op-bottom::before {
            height: 1px;
            background-color: #327ab9;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }
        strong.font-bolder-new {
            font-size: 10px !important;
        }
        .user-details {
            font-size: 9px;
        }
        address {
            font-size: 8px;
        }
        .imglogo-v-wrap {
            justify-content: space-between;
        }
        .row {
            margin: 0;
        }
        .col-lg-4, .col-sm-4 {
            padding: 0 2px;
        }
    }

    .visitor-card {
        min-height: 50vh;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .visitor-card .container {
        margin: 0 auto;
    }
    .heading {
        text-align: center;
        padding: 10px 0;
        color: #000000;
    }

    .heading h2 {
        font-size: 20px;
        font-weight: 500;
        text-transform: uppercase;
        text-decoration: underline;
        text-underline-offset: 5px;
        text-decoration-color: #327ab9;
        color: #000000;
    }
    strong {
        font-weight: 700 !important;
        font-size: 14px !important;
    }
    .copyright {
        font-weight: 700 !important;
        font-size: 16px !important;
    }

    .field-name {
        display: flex;
        justify-content: space-between;
        color: #000000;
        margin-bottom: 5px;
    }

    .field-name span {
        flex: 1;
    }

    .imglogo-v {
        text-align: center;
    }

    .imglogo-v img {
        max-width: 200px;
    }

    .com-img {
        border-radius: 10px;
        border: 6px double #1c3a6b;
        width: 100px;
        height: 100px;
        margin: 0 15px;
    }

    .op-bottom {
        position: relative;
        padding: 5px 0;
        margin-top: 20px;
        text-align: center;
        color: #000000;
    }

    .op-bottom::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 100%;
        height: 2px;
        background: #327ab9;
        color: #000000;
    }

    .crad-v {
        max-width: 450px;
        margin: 0 auto;
        padding: 20px;
        border: 1px solid #eee;
        -webkit-box-shadow: 0px 0px 2px 5px #0000002a;
        box-shadow: 0px 0px 2px 2px #0000002a;
        background-color: #ffffff;
        box-sizing: border-box;
    }

    strong.font-bolder-new {
        font-size: 14px;
        font-weight: bolder !important;
        text-transform: capitalize;
    }

    .user-details {
        font-size: 12px;
        text-transform: uppercase;
        padding-left: 5px;
    }
    .visitor-card .imglogo-v-wrap {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    address {
        font-size: 12px;
    }
    .button-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 10vh;
    }

    body {
        background-color: #ecf0f5;
        min-height: 100vh;
        display: flex;
        flex-direction: column;
    }
    .content {
        padding: 50px 20px;
    }
    .wrapperes {
        display: flex;
        flex-direction: column;
        flex-grow: 1;
        background-color: #ecf0f5;
    }


    a {
        color: #ffffff !important;
        text-decoration: none;
    }

    .box.box-primary {
        max-width: 950px;
        width: 100%;
        margin: 0 auto;
    }

    .content-wrapperes form {
        padding-top: 10px;
    }
    .content-wrapperes form label {
        text-transform: capitalize;
    }

    #checkin-message {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 20px;
        border-radius: 10px;
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        display: none;
        z-index: 1000;
    }

    #error-message {
        color: red;
        font-size: 16px;
        padding: 10px;
        margin: 10px 0;
        border: 1px solid red;
        border-radius: 5px;
        background-color: #fff0f0;
        display: none;
        text-align: center;
    }

    /* Quiz Section Styling */
    #question-section {
        background-color: #ffffff;
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 25px;
        max-width: 700px;
        margin: 30px auto;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    .quiz-header {
        text-align: center;
        margin-bottom: 20px;
    }
    .quiz-title {
        font-size: 24px;
        color: #3c8dbc;
        font-weight: 600;
        text-transform: uppercase;
        margin-bottom: 10px;
    }
    .quiz-progress {
        font-size: 16px;
        color: #555;
    }
    .question-container .question-item {
        margin-bottom: 25px;
        padding: 15px;
        border: 1px solid #e0e0e0;
        border-radius: 3px;
        background-color: #f9f9f9;
    }
    .question-item label.question-text {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 12px;
    }
    .question-item .option {
        display: flex;
        align-items: center;
        padding: 10px;
        margin: 8px 0;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    .question-item .option:hover {
        background-color: #e6f0fa;
        border-color: #3c8dbc;
    }
    .question-item input[type="radio"] {
        margin-right: 10px;
        accent-color: #3c8dbc;
        width: 18px;
        height: 18px;
    }
    .question-item input[type="radio"]:focus {
        outline: 2px solid #3c8dbc;
        outline-offset: 2px;
    }
    .quiz-feedback {
        font-size: 16px;
        padding: 10px;
        border-radius: 5px;
    }
    .quiz-feedback.success {
        background-color: #dff0d8;
        color: #3c763d;
    }
    .quiz-feedback.error {
        background-color: #f2dede;
        color: #a94442;
    }
    .quiz-actions .btn-primary {
        background-color: #3c8dbc;
        border: none;
        padding: 10px 30px;
        font-size: 16px;
        border-radius: 5px;
        transition: background-color 0.3s ease;
    }
    .quiz-actions .btn-primary:hover {
        background-color: #327ab9;
    }

    /* New Sidebar Styling */
    .sidebar {
        width: 300px;
        background-color: #ffffff;
        padding: 20px;
        border-right: 1px solid #ddd;
        box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
    }
    .sidebar h3 {
        font-size: 18px;
        color: #3c8dbc;
        margin-bottom: 20px;
        text-transform: uppercase;
    }
    .sidebar .field-name {
        margin-bottom: 10px;
        font-size: 14px;
    }
    .sidebar .field-name strong {
        font-weight: 600;
        color: #333;
    }
    .sidebar .user-details {
        font-size: 12px;
        color: #555;
        text-transform: uppercase;
    }
    .main-content {
        display: flex;
        flex-grow: 1;
    }
    .content-wrapperes {
        flex: 1;
        padding: 20px;
    }

    /* Responsive Design */
    @media (max-width: 768px) {
        .main-content {
            flex-direction: column;
        }
        .sidebar {
            width: 100%;
            min-height: auto;
            border-right: none;
            border-bottom: 1px solid #ddd;
        }
        #question-section {
            padding: 15px;
            margin: 15px;
        }
        .quiz-title {
            font-size: 20px;
        }
        .question-item label.question-text {
            font-size: 14px;
        }
        .question-item .option {
            font-size: 14px;
            padding: 8px;
        }

    }
    .crad-v{
        color:#000;
    }
</style>

<body class="skin-blue">
    <div class="wrapperes">
        <header class="main-header">
            <nav class="navbar navbar-static-top text-center" role="navigation" style="background-color: #fff !important; margin-left: 0px !important; display: flex; justify-content: center; align-items: center; border-bottom: 1px solid #ccc;">
                {% if GET_PASS_IMAGE %}
                    <img src="{% static GET_PASS_IMAGE %}" class="com-logo" style="margin: 5px; width: 200px;">
                {% else %}
                    <img src="{% static 'default_logo.png' %}" class="com-logo" style="margin: 5px; width: 200px;">
                {% endif %}
            </nav>
        </header>
        <div id="error-message" style="color: red;"></div>
        <div class="main-content">
            <!-- Sidebar for Appointment Details -->
            <div class="sidebar">
                <h3>Appointment Details</h3>
                <div class="field-name">
                    <span><strong>Gate Pass No</strong></span>:
                    <span class="user-details" id="sidebar-gate-pass-number">{{ formatted_gate_pass_number|default:"Not Available" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Visitor Type</strong></span>:
                    <span class="user-details">{{ all_data_user.visitors_type|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Name</strong></span>:
                    <span class="user-details">{{ user.first_name }} {{ user.last_name }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Address</strong></span>:
                    <span class="user-details">{{ user.address|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Mobile No</strong></span>:
                    <span class="user-details">{{ user.mobile|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Check In Date & Time</strong></span>:
                    <span class="user-details">{{ all_data_user.check_in_time|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Check Out Date & Time</strong></span>:
                    <span class="user-details">{{ all_data_user.check_out_time|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>To Meet</strong></span>:
                    <span class="user-details">{{ employee_data.first_name }} {{ employee_data.last_name }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Company Name</strong></span>:
                    <span class="user-details">{{ company_data.company_name|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Department Name</strong></span>:
                    <span class="user-details">{{ department_data.department_name|default:"N/A" }}</span>
                </div>
                <div class="field-name">
                    <span><strong>Location Name</strong></span>:
                    <span class="user-details">{{ location_data.location_name|default:"N/A" }}</span>
                </div>
            </div>

            <div id="safety_video">
                <div class="content-wrapperes" style="background-color: #ecf0f5">
                    <section class="content">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="box box-primary">
                                    <div class="box-header">
                                        <h3 class="box-title">Safety Training</h3>
                                        <div id="messageContainer">
                                            {% if messages %}
                                                {% for message in messages %}
                                                    <div class="alert {% if 'success' in message.tags %}alert-success{% elif 'danger' in message.tags %}alert-danger{% endif %}" role="alert" id="success-alert">
                                                        {{ message }}
                                                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                                            <span aria-hidden="true">×</span>
                                                        </button>
                                                    </div>
                                                {% endfor %}
                                            {% endif %}
                                        </div>

                                        {% if not user.is_safety_training %}
                                            <div id="video-container" style="text-align: center;">
                                                {% if last_video %}
                                                    <video id="safety-video" width="640" height="360" autoplay muted>
                                                        <source src="/safety_training/{{ last_video }}" type="video/mp4">
                                                        Your browser does not support the video tag.
                                                    </video>
                                                    <div style="display: grid; place-items: center; margin-top: 15px;">
                                                        <button id="play-video-btn" class="btn btn-primary">
                                                            ▶ Play Video
                                                        </button>
                                                    </div>
                                                    <div style="display: grid; place-items: center; height: 10vh;">
                                                        <button id="complete-button">Complete Safety Training</button>
                                                    </div>
                                                    <div id="question-section" style="display: none; text-align: left; margin: 20px auto; max-width: 640px;">
                                                        <form id="quiz-form">
                                                            <div id="question-container"></div>
                                                            <button type="submit" class="btn btn-primary mt-3">Submit Answers</button>
                                                        </form>
                                                    </div>
                                                {% else %}
                                                    <p>No safety training videos available.</p>
                                                {% endif %}
                                            </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>

            <div id="checkin-message" style="display: none;">
                <p>Check-in already done. Back to new appointment.</p>
            </div>

            <div id="gate-pass">
                {{gate_pass_template}}
<!--                <div class="visitor-card">-->
<!--                    <div class="container">-->
<!--                        <div class="crad-v">-->
<!--                            <div class="imglogo-v-wrap">-->
<!--                                <div class="imglogo-v">-->
<!--                                    {% if GET_PASS_IMAGE %}-->
<!--                                        <img src="{% static GET_PASS_IMAGE %}" class="com-logo">-->
<!--                                    {% else %}-->
<!--                                        <img src="{% static 'default_logo.png' %}" class="com-logo">-->
<!--                                    {% endif %}-->
<!--                                    <h6>{{ company_data.company_name }}</h6>-->
<!--                                    <address>{{ company_data.address_1 }}</address>-->
<!--                                </div>-->
<!--                                <div class="imglogo-v">-->
<!--                                    {% if user.image %}-->
<!--                                        <img src="/user/{{ user.image }}" class="com-img">-->
<!--                                    {% else %}-->
<!--                                        <img src="{% static 'default_user.png' %}" class="com-img">-->
<!--                                    {% endif %}-->
<!--                                </div>-->
<!--                            </div>-->
<!--                            <div class="mb-2">-->
<!--                                <div class="heading">-->
<!--                                    <h2>Visitor Slip</h2>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                            <div class="row">-->
<!--                                <div class="col-lg-12 col-sm-12">-->
<!--                                    <div class="text-vcard visitor-details">-->
<!--                                        <div class="mb-2">-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Gate Pass No</strong></span>:-->
<!--                                                    <span class="user-details" id="gate_pass_number">{{ formatted_gate_pass_number }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Visitor Type</strong></span>:-->
<!--                                                <span class="user-details">{{ all_data_user.visitors_type }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Name</strong></span>:-->
<!--                                                <span class="user-details">{{ user.first_name }} {{ user.last_name }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Address</strong></span>:-->
<!--                                                <span class="user-details">{{ user.address }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Mobile No</strong></span>:-->
<!--                                                <span class="user-details">{{ user.mobile }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Check In Date & Time</strong></span>:-->
<!--                                                <span class="user-details">{{ all_data_user.check_in_time }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Check Out Date & Time</strong></span>:-->
<!--                                                <span class="user-details">{{ all_data_user.check_out_time }}</span>-->
<!--                                            </div>-->
<!--                                        </div>-->
<!--                                    </div>-->
<!--                                    <div class="text-vcard">-->
<!--                                        <div class="mb-2">-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">To Meet</strong></span>:-->
<!--                                                <span class="user-details">{{ employee_data.first_name }} {{ employee_data.last_name }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Company Name</strong></span>:-->
<!--                                                <span class="user-details">{{ company_data.company_name }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Department Name</strong></span>:-->
<!--                                                <span class="user-details">{{ department_data.department_name }}</span>-->
<!--                                            </div>-->
<!--                                            <div class="field-name"><span><strong class="font-bolder-new">Location Name</strong></span>:-->
<!--                                                <span class="user-details">{{ location_data.location_name }}</span>-->
<!--                                            </div>-->
<!--                                        </div>-->
<!--                                    </div>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                            <div class="row">-->
<!--                                <div class="col-lg-4 col-sm-4">-->
<!--                                    <div class="op-bottom"><span><strong class="font-bolder-new">Sign Of Visitor</strong></span></div>-->
<!--                                </div>-->
<!--                                <div class="col-lg-4 col-sm-4">-->
<!--                                    <div class="op-bottom"><span><strong class="font-bolder-new">Sign Of Meeting Person</strong></span></div>-->
<!--                                </div>-->
<!--                                <div class="col-lg-4 col-sm-4">-->
<!--                                    <div class="op-bottom"><span><strong class="font-bolder-new">Sign Of Security Officer</strong></span></div>-->
<!--                                </div>-->
<!--                            </div>-->
<!--                        </div>-->
                <div class="button-container">
                    <button id="print-button" class="btn btn-primary d-grid" style="margin-right:10px">Print Gate Pass</button>
                    <button id="back-button" class="btn btn-primary d-grid">Back</button>
                </div>
<!--                    </div>-->
<!--                </div>-->

            </div>
        </div>
    </div>

    <!-- Separate script block for questions to isolate potential JSON issues -->
    <script src="{% static 'default/footer/sweetalert2@10.js' %}"></script>
    <script>
        var questionsData = {% if questions %}{{ questions | safe }}{% else %}[]{% endif %};
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            try {
                // DOM elements
                var videoContainer = document.getElementById('video-container');
                var video = document.getElementById('safety-video');
                var completeButton = document.getElementById('complete-button');
                var gatePass = document.getElementById('gate-pass');
                var safetyVideo = document.getElementById('safety_video');
                var printButton = document.getElementById('print-button');
                var backButton = document.getElementById('back-button');
                var errorMessageDiv = document.getElementById('error-message');
                var gatePassNumberElement = document.getElementById('gate_pass_number');
                var sidebarGatePassNumber = document.getElementById('sidebar-gate-pass-number');
                var questionSection = document.getElementById('question-section');
                var questionContainer = document.getElementById('question-container');
                var userId = "{{ user_id }}";
                var isSafetyTraining = {% if user.is_safety_training %}true{% else %}false{% endif %};
                var employeeApproval = "{{ all_data_user.employee_approval }}";
                var appointmentId = "{{ all_data_user.id }}";
                var checkInTime = "{{ all_data_user.check_in_time }}";
                var redirectUrl = "{% url 'visitors_self_safety_training' %}";
                var playVideoBtn = document.getElementById('play-video-btn');
                // Debug logs to verify variable values
                console.log("isSafetyTraining:", isSafetyTraining);
                console.log("employeeApproval:", employeeApproval);
                console.log("appointmentId:", appointmentId);
                console.log("checkInTime:", checkInTime);
                console.log("userId:", userId);
                console.log("errorMessageDiv exists:", !!errorMessageDiv);

                // Initialize visibility based on safety training status
                if (isSafetyTraining) {
                    if (employeeApproval === 'accepted') {
                        gatePass.style.display = 'block';
                        safetyVideo.style.display = 'none';
                        if (!checkInTime) {
                            if (printButton) {
                                printButton.style.display = 'block';
                            } else {
                                console.error("printButton not found when trying to display.");
                            }
                        } else {
                            if (backButton) {
                                backButton.style.display = 'block';
                            }
                            showMessage("Check-in already done. Redirecting...", "success");
                            setTimeout(() => { window.location.href = redirectUrl; }, 2000);
                        }
                    } else {
                        if (errorMessageDiv) {
                            errorMessageDiv.style.display = 'block';
                            errorMessageDiv.innerHTML = '<strong>Approval pending!</strong> Please contact your manager.';
                            backButton.style.display = 'block';
                            console.log("Showing errorMessageDiv for pending approval");
                        } else {
                            console.error("errorMessageDiv not found in DOM");
                        }
                        if (backButton) {
                            backButton.style.display = 'block';
                        }
                        safetyVideo.style.display = 'none';
                    }
                } else {
                    safetyVideo.style.display = 'block';
                    if (video) {

                            // prevent autoplay
                            video.autoplay = false;
                            video.muted = false;

                            // play video ONLY when user clicks on video
                            if (video) {
                        video.autoplay = false;
                        video.muted = false;
                        video.pause(); // ensure it never auto-plays
                    }

                    if (playVideoBtn && video) {
                        playVideoBtn.addEventListener('click', function () {
                            video.play();
                            playVideoBtn.style.display = 'none'; // hide button after play
                        });
                    }

                    // after video ends → load questions
                    if (video) {
                        video.addEventListener('ended', function () {
                            loadQuestions();
                        });
                    }

                            // after video ends
                            video.addEventListener('ended', function () {
                                loadQuestions();
                            });
                        }
                }

                // Back button event listener
                if (backButton) {
                    backButton.addEventListener('click', function () {
                        window.location.href = redirectUrl;
                    });
                }

                // Complete safety training
                if (completeButton) {
                    completeButton.addEventListener('click', function () {
                        if (!userId) {
                            alert("User ID is missing or invalid.");
                            return;
                        }
                        $.ajax({
                            url: "{% url 'update_safety_training_status' %}",
                            type: "POST",
                            headers: { "X-CSRFToken": "{{ csrf_token }}" },
                            data: JSON.stringify({ user_id: userId }),
                            contentType: "application/json",
                            success: function (response) {
                                if (employeeApproval === 'accepted') {
                                    if (videoContainer) videoContainer.style.display = 'none';
                                    gatePass.style.display = 'block';
                                    safetyVideo.style.display = 'none';
                                    if (!checkInTime) {
                                        if (printButton) printButton.style.display = 'block';
                                    } else {
                                        if (backButton) backButton.style.display = 'block';
                                    }
                                    if (response.gate_pass_number) {
                                        if (gatePassNumberElement) {
                                            gatePassNumberElement.textContent = response.gate_pass_number;
                                        }
                                        if (sidebarGatePassNumber) {
                                            sidebarGatePassNumber.textContent = response.gate_pass_number;
                                        }
                                    }
                                } else {
                                    if (errorMessageDiv) {
                                        errorMessageDiv.style.display = 'block';
                                        errorMessageDiv.innerHTML = '<strong>Approval pending!</strong> Please contact your manager.';
                                        console.log("Showing errorMessageDiv after AJAX for pending approval");
                                    } else {
                                        console.error("errorMessageDiv not found in DOM after AJAX");
                                    }
                                    if (backButton) {
                                        backButton.style.display = 'block';
                                    }
                                    if (videoContainer) videoContainer.style.display = 'none';
                                    safetyVideo.style.display = 'none';
                                }
                            },
                            error: function (xhr) {
                                alert(xhr.responseJSON?.message || "An error occurred during safety training update.");
                            }
                        });
                    });
                }

                // Print gate pass
                if (printButton) {
                    printButton.addEventListener('click', function () {
                        if (!appointmentId) {
                            Swal.fire("Error", "Appointment ID is missing or invalid.", "error");
                            return;
                        }

                        // ✅ Directly print only #gate-pass content
                        var gatePass = document.getElementById('gate-pass');
                        if (gatePass) {
                            // ✅ Apply new design styles directly

                            gatePass.style.padding = "20px";
                            gatePass.style.borderRadius = "12px";
                            gatePass.style.fontFamily = "Arial, sans-serif";
                            gatePass.style.backgroundColor = "#f9f9f9";


                            // ✅ Print only the updated gatePass
                            var originalContent = document.body.innerHTML;
                            document.body.innerHTML = gatePass.outerHTML;
                            window.print();
                            document.body.innerHTML = originalContent; // restore after printing
                        } else {
                            Swal.fire("Error", "Gate pass content not found.", "error");
                        }

                        // Redirect after printing
                        setTimeout(() => {
                            window.location.href = redirectUrl;
                        }, 1000);


                    });
                }


                // Load quiz questions
                function loadQuestions() {
                    try {
                        var questions = questionsData;
                        questionContainer.innerHTML = "";
                        if (!questions || !Array.isArray(questions) || questions.length === 0) {
                            questionContainer.innerHTML = "<p>No questions available.</p>";
                            return;
                        }
                        questions.forEach(q => {
                            if (q && q.id && q.question_text) {
                                var div = document.createElement("div");
                                div.classList.add("question-item");
                                div.innerHTML = `
                                    <label class="question-text">${q.question_text}</label>
                                    <div class="option"><input type="radio" name="${q.id}" value="A" required> ${q.option_a || 'N/A'}</div>
                                    <div class="option"><input type="radio" name="${q.id}" value="B"> ${q.option_b || 'N/A'}</div>
                                    <div class="option"><input type="radio" name="${q.id}" value="C"> ${q.option_c || 'N/A'}</div>
                                    <div class="option"><input type="radio" name="${q.id}" value="D"> ${q.option_d || 'N/A'}</div>
                                `;
                                questionContainer.appendChild(div);
                            }
                        });
                        questionSection.style.display = "block";
                    } catch (e) {
                        console.error("Error loading questions:", e);
                        questionContainer.innerHTML = "<p>Error loading questions. Please try again.</p>";
                    }
                }

                // Submit quiz answers
                var quizForm = document.getElementById("quiz-form");
                if (quizForm) {
                    quizForm.addEventListener("submit", function (e) {
                        e.preventDefault();
                        var formData = new FormData(e.target);
                        var answers = {};
                        for (var [key, value] of formData.entries()) {
                            answers[key] = value;
                        }
                        fetch("{% url 'submit_safety_questions' %}", {
                            method: "POST",
                            headers: {
                                "X-CSRFToken": "{{ csrf_token }}",
                                "Content-Type": "application/json"
                            },
                            body: JSON.stringify({ user_id: userId, answers: answers })
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.status === "success") {
                                if (data.score >= 50) {
                                    Swal.fire("✅ You scored " + data.score + "%. You may now complete the safety training.");
                                    questionSection.style.display = "none";
                                    if (completeButton) completeButton.style.display = "block";
                                } else {
                                    Swal.fire("❌ You scored " + data.score + "%. Minimum 50% required. The video will restart.");
                                    questionSection.style.display = "none";
                                    if (completeButton) completeButton.style.display = "none";
                                    if (video) {
                                        video.currentTime = 0;
                                        video.play();
                                    }
                                }
                            } else {
                                Swal.fire("❌ " + data.message + "\nPlease try again.");
                                location.reload();
                            }
                        })
                        .catch(error => {
                            console.error("Error submitting quiz:", error);
                            Swal.fire("Something went wrong. Please try again.");
                        });
                    });
                }

                // Show message
                function showMessage(message, type) {
                    var messageContainer = document.getElementById("messageContainer");
                    if (messageContainer) {
                        var alertDiv = document.createElement("div");
                        alertDiv.className = `alert alert-${type}`;
                        alertDiv.setAttribute("role", "alert");
                        alertDiv.innerHTML = message;
                        alertDiv.innerHTML += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
                        messageContainer.appendChild(alertDiv);
                        setTimeout(() => { alertDiv.remove(); }, 2000);
                    }
                }
            } catch (e) {
                console.error("Initialization error:", e);
                Swal.fire("An error occurred while loading the page. Please refresh.");
            }
        });
    </script>
    {% include 'registration_form/footer.html' %}
</body>