<?php include 'inc_classes.php'; 
include "admin_authentication.php";
?>
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Employee Feedback</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- Bootstrap 3.3.7 -->
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="bower_components/Ionicons/css/ionicons.min.css">
    <!-- daterange picker -->
    <link rel="stylesheet" href="bower_components/bootstrap-daterangepicker/daterangepicker.css">
    <!-- bootstrap datepicker -->
    <link rel="stylesheet" href="bower_components/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css">
    <!-- iCheck for checkboxes and radio inputs -->
    <link rel="stylesheet" href="plugins/iCheck/all.css">
    <!-- Bootstrap Color Picker -->
    <link rel="stylesheet" href="bower_components/bootstrap-colorpicker/dist/css/bootstrap-colorpicker.min.css">
    <!-- Bootstrap time Picker -->
    <link rel="stylesheet" href="plugins/timepicker/bootstrap-timepicker.min.css">
    <!-- Select2 -->
    <link rel="stylesheet" href="bower_components/select2/dist/css/select2.min.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
    <!-- paginate style -->
    <link rel="stylesheet" href="dist/css/paginate.min.css">
    <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
    <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
    <!-- Google Font -->
    <link rel="stylesheet"
        href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>

<script>
let feedbackValues = {};
let feedbackCount = 0;
function submit_value(selectedImg, value, questionId) {
    const stickersContainer = selectedImg.closest('.stickers');
    if (!stickersContainer) {
        console.error("Stickers container not found.");
        return;
    }
    const allImages = stickersContainer.querySelectorAll('img');
    allImages.forEach(img => img.classList.remove('selected'));
    selectedImg.classList.add('selected');
    feedbackValues[questionId] = parseInt(value);
    feedbackCount = Object.keys(feedbackValues).length;
    const feedbackArray = Object.entries(feedbackValues).map(([key, value]) => ({
        questionId: key,
        value: value
    }));
    updateProgressBar();
}
function updateProgressBar() {
    const totalQuestionsElement = document.getElementById("tot_que");
    if (!totalQuestionsElement) {
        console.error("Total questions element not found.");
        return;
    }

    const totalQuestions = parseInt(totalQuestionsElement.value);
    if (isNaN(totalQuestions) || totalQuestions <= 0) {
        console.error("Invalid total questions value.");
        return;
    }

    const progressPercentage = (feedbackCount / totalQuestions) * 100;
    const progressBarSpan = document.querySelector('.progress-bar span');
    if (!progressBarSpan) {
        console.error("Progress bar span not found.");
        return;
    }
    progressBarSpan.style.width = progressPercentage + '%';
    const greenIntensity = Math.floor((1 - progressPercentage / 100) * 91) + 134; // Scale from 225 to 134
    progressBarSpan.style.backgroundColor = `rgb(0, ${greenIntensity}, 0)`; 
}

function submit_feedback() {
    const feedbackIds = document.getElementById("feedbackIds").value;
    const totalQuestionsElement = document.getElementById("tot_que");
    const commentElement = document.getElementById("comment");
    if (!totalQuestionsElement || !commentElement) {
        console.error("Required elements for feedback submission not found.");
        return;
    }
    const totalQuestions = parseInt(totalQuestionsElement.value);
    if (isNaN(totalQuestions) || totalQuestions <= 0) {
        alert("Invalid total questions value.");
        return;
    }
    if (totalQuestions !== feedbackCount) {
        alert("All questions should be answered.");
        return;
    }
    const comment = commentElement.value.trim();
    // if (comment === "") {
    //     alert("Please provide a comment.");
    //     return;
    // }
    const feedbackArray = Object.entries(feedbackValues).map(([key, value]) => ({
        questionId: key,
        value: value
    }));
    const datas = `action=submit_feedback&array_value=${encodeURIComponent(JSON.stringify(feedbackArray))}&comment=${encodeURIComponent(comment)}&totQue=${encodeURIComponent(totalQuestions)}&feedbackIds=${encodeURIComponent(feedbackIds)}`;
    $.ajax({
        url: "emp_feedback_ajax.php",
        type: "POST",
        data: datas,
        cache: false,
        success: function (response) {
            alert("Feedback submitted successfully");
            window.location.reload();
        },
        error: function (xhr, status, error) {
            console.error("Error occurred during AJAX request:", error);
            alert("An error occurred while submitting feedback. Please try again.");
        }
    });
}
</script>

<style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 20px;
        }

        .header h1 {
            margin: 0;
            font-size: 24px;
        }
        .progress-bar {
            width: 100%;
            background: #e0e0e0;
            border-radius: 20px;
            margin: 10px 0;
            height: 10px;
            position: relative;
        }

        .progress-bar span {
            display: block;
            height: 100%;
            width: 0.5%; 
            background: #4caf50;
            border-radius: 20px;
            transition: width 0.3s ease, background-color 0.3s ease; 
        }
        .question {
            margin: 20px 0;
        }

        .question h3 {
            margin-bottom: 10px;
            color: #333;
        }

        .options {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .options .option {
            background: #f1f1f1;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: 0.3s;
        }

        .options .option:hover {
            background: #e0e0ff;
            transform: scale(1.05);
        }

        .stickers {
            display: flex;
            gap: 35px;
            margin: 15px 0;
        }

        .stickers img {
            width: 60px;
            height: 60px;
            cursor: pointer;
            transition: transform 0.3s;
        }

        .stickers img {
            border: 2px solid transparent;
            border-radius: 8px;
            transition: 0.3s;
        }
        .stickers img.selected {
            /* border: 2px solid #808080;  */
            box-shadow: 0 0 10px rgba(128, 128, 128, 0.7); 
            transform: scale(1.2) rotate(8deg); 
            transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.3s ease; 
            border-radius: 15px;
        }
        .stickers img:hover {
            transform: scale(1.1);
        }
        .text-feedback textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            resize: none;
        }

        .footer {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .footer button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        .footer .prev {
            background: #ccc;
        }

        .footer .next {
            background: #4caf50;
            color: #fff;
        }

        .footer .next:hover {
            background: #45a049;
        }
        .feedbackDiv{
            margin-top: 15px;
        }
        .feedbackImgs {
            width: 100px;
            height: 100px;
            border-radius: 15px;
            transition: transform 0.3s ease, border-color 0.3s ease;
        }

        .feedbackImgs:hover {
            transform: scale(1.2);
            /* border: 2px solid #4CAF50; */
        }
    </style>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        <?php include "include/header-main.php"; ?>
        <!-- Left side column. contains the logo and sidebar -->
        <?php include "include/menu_left.php"; ?>
        <!-- Content Wrapper. Contains page content -->
        <!-- Left side column. contains the logo and sidebar -->
        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
                <h1>
                Employee Feedback
                </h1>
                <ol class="breadcrumb">
                    <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
                    <li class="active">Dashboard</li>
                </ol>
            </section>
            <!-- Main content -->
            <section class="content">
                <!-- SELECT2 EXAMPLE -->
                <div class="box box-default">
                    <div class="box-body">
                        <form name="task_form" method="post">
                            <div class="container">
                                <?php
                                $today = date('Y-m-d');
                                $twoDaysAgo = date('Y-m-d', strtotime('-3 days'));
                                $select_feedbackId = "SELECT DISTINCT efq.feedback_id FROM employee_feedback_question efq LEFT JOIN emp_feedback_percentage efp ON efq.feedback_id = efp.feedback_id AND efp.admin_id = '" . $_SESSION['admin_id'] . "' WHERE efq.feedback_date >= '$twoDaysAgo' AND efq.feedback_date <= '$today' AND efp.id IS NULL ORDER BY efq.feedback_id ASC";
                                $ptr_feedbackId = mysql_query($select_feedbackId);
                                $Fd_record = mysql_num_rows($ptr_feedbackId);
                                if ($Fd_record > 0)
                                {
                                    $data_feedbackId = mysql_fetch_array($ptr_feedbackId);
                                    ?>
                                    <div class="header">
                                        <h1>Employee Feedback #<?php echo $data_feedbackId['feedback_id'] ?></h1>
                                        <div class="progress-bar">
                                            <span></span>
                                        </div>
                                        <p>Please answer the following questions honestly to help us improve your experience.</p>
                                    </div>
                                    <?php
                                    $select_faculty = "SELECT question_id FROM employee_feedback_question WHERE feedback_id='" . $data_feedbackId['feedback_id'] . "' ORDER BY id DESC
                                    ";
                                    $ptr_faculty = mysql_query($select_faculty);
                                    $tot_que = mysql_num_rows($ptr_faculty);
                                
                                    if ($tot_que > 0) 
                                    {
                                        $i = 0;
                                        while ($data_faculty = mysql_fetch_array($ptr_faculty)) 
                                        {
                                            $select_que = "SELECT question FROM feedback_question WHERE que_id='" . $data_faculty['question_id'] . "'";
                                            $ptr_que = mysql_query($select_que);
                                            $data_que = mysql_fetch_array($ptr_que);
                                            ?>
                                            <input type="hidden" name="tot_que" id="tot_que" value="<?php echo $tot_que; ?>" />
                                            <input type="hidden" name="feedbackIds" id="feedbackIds" value="<?php echo $data_feedbackId['feedback_id']; ?>" />
                                            <div class="question" id="question-<?php echo $i; ?>" <?php echo $i > 0 ? 'style="display:none;"' : ''; ?>>
                                                <h3><?php echo ($i + 1) . '. ' . ucfirst($data_que['question']); ?></h3>
                                                <div class="stickers">
                                                    <img src="images/excellent.jpg" alt="Excellent" value="100" 
                                                        onclick="submit_value(this, '100', <?php echo $data_faculty['question_id']; ?>)">
                                                    <img src="images/good.jpg" alt="Good" value="75" 
                                                        onclick="submit_value(this, '75', <?php echo $data_faculty['question_id']; ?>)">
                                                    <img src="images/average.jpg" alt="Average" value="50" 
                                                        onclick="submit_value(this, '50', <?php echo $data_faculty['question_id']; ?>)">
                                                    <img src="images/poor.jpg" alt="Poor" value="25" 
                                                        onclick="submit_value(this, '25', <?php echo $data_faculty['question_id']; ?>)">
                                                    <img src="images/bad.jpg" alt="Bad" value="0" 
                                                        onclick="submit_value(this, '0', <?php echo $data_faculty['question_id']; ?>)">
                                                </div>                                        
                                            </div>
                                            <?php
                                            $i++;
                                        }
                                        ?>
                                        <div class="text-feedback">
                                            <h3>Any additional comments?</h3>
                                            <textarea rows="2" id="comment<?php echo $data_faculty['question_id']; ?>" 
                                                name="comment<?php echo $data_faculty['question_id']; ?>" 
                                                placeholder="Write your feedback here..."></textarea>
                                        </div>
                                        <div class="footer">
                                            <button class="prev" type="button" onclick="prevQuestion()">Previous</button>
                                            <button class="next" type="button" onclick="nextQuestion()">Next</button>
                                        </div>
                                        <?php
                                    } 
                                    else 
                                    {
                                        echo "<div style='text-align: center; margin: 20px auto; font-family: Arial, sans-serif;'>";
                                        echo "<h2 style='color: red;'>No feedback questions available</h2>";
                                        echo "</div>";
                                    }
                                } 
                                else 
                                {
                                    echo "<div style='text-align: center; margin: 20px auto; font-family: Arial, sans-serif;'>";
                                    echo "<h2 style='color: #4CAF50;'>Thank You for Your Valuable Feedback!</h2>";
                                    echo "<div class='feedbackDiv'>
                                            <img src='images/happy.jpg' class='feedbackImgs' alt='Thanks'>
                                          </div>";
                                    echo "</div>";
                                }
                                ?>
                                
                            </div>
                        </form>
                    </div>
                </div>
            </section>
            <!-- /.content -->
        </div>
        <!-- /.content-wrapper -->
        <?php include "include/footer-main.php"; ?>
    </div>
    <!-- jQuery 3 -->
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <!-- Bootstrap 3.3.7 -->
    <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
    <!-- Select2 -->
    <script src="bower_components/select2/dist/js/select2.full.min.js"></script>
    <!-- InputMask -->
    <script src="plugins/input-mask/jquery.inputmask.js"></script>
    <script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
    <script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
    <!-- date-range-picker -->
    <script src="bower_components/moment/min/moment.min.js"></script>
    <script src="bower_components/bootstrap-daterangepicker/daterangepicker.js"></script>
    <!-- bootstrap datepicker -->
    <script src="bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js"></script>
    <!-- bootstrap color picker -->
    <script src="bower_components/bootstrap-colorpicker/dist/js/bootstrap-colorpicker.min.js"></script>
    <!-- bootstrap time picker -->
    <script src="plugins/timepicker/bootstrap-timepicker.min.js"></script>
    <!-- SlimScroll -->
    <script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
    <!-- iCheck 1.0.1 -->
    <script src="plugins/iCheck/icheck.min.js"></script>
    <!-- FastClick -->
    <script src="bower_components/fastclick/lib/fastclick.js"></script>
    <!-- AdminLTE App -->
    <script src="dist/js/adminlte.min.js"></script>
    <!-- AdminLTE for demo purposes -->
    <script src="dist/js/demo.js"></script>
    <!-- Page script -->
    <script>
    let currentQuestion = 0;
    var totalQuestions = document.getElementById("tot_que").value;
    const questions = document.querySelectorAll('.question');
    const nextButton = document.querySelector('.next');
    const prevButton = document.querySelector('.prev');
    const footer = document.querySelector('.footer');

    function showQuestion(index) {
        questions.forEach((question, i) => {
            question.style.display = i === index ? 'block' : 'none';
        });
        if (index === questions.length - 1) {
            nextButton.style.display = 'none';
            if (!document.querySelector('.submit')) {
                const submitButton = document.createElement('button');
                submitButton.classList.add('submit');
                submitButton.style.color = 'white';
                submitButton.style.backgroundColor = 'green';
                submitButton.type = 'button';
                submitButton.textContent = 'Submit';
                submitButton.onclick = function () {
                    setTimeout(function() {
                        submit_feedback();
                    }, 200);
                };
                footer.appendChild(submitButton);
            }
        } else {
            nextButton.style.display = 'inline-block';
            const submitButton = document.querySelector('.submit');
            if (submitButton) submitButton.remove(); 
        }
        prevButton.style.display = index === 0 ? 'none' : 'inline-block';
    }

    function nextQuestion() {
        if (currentQuestion < questions.length - 1) {
            currentQuestion++;
            showQuestion(currentQuestion);
        }
    }

    function prevQuestion() {
        if (currentQuestion > 0) {
            currentQuestion--;
            showQuestion(currentQuestion);
        }
    }
    showQuestion(currentQuestion);
</script>

    <script>
        $(function () {
            //Initialize Select2 Elements
            $('.select2').select2()

            //Date picker
            $('#datepicker').datepicker({
                autoclose: true,
                format: 'dd/mm/yyyy',
                startDate: '-0d',
                Default: true,
                todayHighlight: true
            })
            $('#datepicker1').datepicker({
                autoclose: true,
                format: 'dd/mm/yyyy',
                Default: true,
                todayHighlight: true
            })
            //iCheck for checkbox and radio inputs
            $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
                checkboxClass: 'icheckbox_minimal-blue',
                radioClass: 'iradio_minimal-blue'
            })
            //Red color scheme for iCheck
            $('input[type="checkbox"].minimal-red, input[type="radio"].minimal-red').iCheck({
                checkboxClass: 'icheckbox_minimal-red',
                radioClass: 'iradio_minimal-red'
            })
            //Flat red color scheme for iCheck
            $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
                checkboxClass: 'icheckbox_flat-green',
                radioClass: 'iradio_flat-green'
            })

            //Colorpicker
            $('.my-colorpicker1').colorpicker()
            //color picker with addon
            $('.my-colorpicker2').colorpicker()

            //Timepicker
            $('.timepicker').timepicker({
                showInputs: false
            })
        })
    </script>
</body>

</html>