<?php
include('session_validator.php');
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assign Enthic Group to Students</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="js/jquery-3.6.4.min.js"></script>
    <script src="js/jquery.dataTables.min.js"></script>
    <style>
        body {
            background-color: #91ced4;
        }

        body * {
            box-sizing: border-box;
        }

        .header {
            background-color: #327a81;
            color: white;
            font-size: 1.5em;
            padding: 1rem;
            text-align: center;
            text-transform: uppercase;
        }

        .table-users {
            border: 1px solid #327a81;
            border-radius: 10px;
            box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1);
            max-width: calc(100% - 1em);
            overflow: hidden;
            width: 960px;
        }

        table {
            width: 100%;
            margin-left: 1em;
        }

        table td,
        table th {
            color: #2b686e;
            padding: 8px;
        }

        table td {
            text-align: left;
        }

        table td:last-child {
            font-size: 0.95em;
            line-height: 1.4;
            text-align: left;
        }

        table th {
            background-color: #daeff1;
            font-weight: 200;
                   position: sticky;
            z-index: 500;
            top: 0;        }

        table tr:nth-child(2n) {
            background-color: white;
        }

        table tr:nth-child(2n+1) {
            background-color: #edf7f8;
        }

        @media screen and (max-width: 768px) {
            table,
            tr,
            td {
                display: block;
            }

            td:first-child {
                position: absolute;
                top: 50%;
                transform: translateY(-50%);
                width: 100%;;
            }

            td:not(:first-child) {
                clear: both;
                margin-left: 1px;
                padding: 4px 10px 4px 90px;
                position: relative;
                text-align: left;
            }

            td:not(:first-child):before {
                color: #91ced4;
                content: "";
                display: block;
                left: 0;
                position: absolute;
            }

            tr {
                padding: 15px 0;
                position: relative;
            }

            tr:first-child {
                display: none;
            }
        }

        @media screen and (max-width: 960px) {
            .header {
                background-color: transparent;
                color: white;
                font-size: 2em;
                font-weight: 700;
                padding: 0;
                text-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
            }

            td:first-child {
                background-color: #c8e7ea;
                border-bottom: 1px solid #91ced4;
                border-radius: 10px 10px 0 0;
                position: relative;
                top: 0;
                transform: translateY(0);
                width: 100%;
            }

            td:not(:first-child) {
                margin: 0;
                padding: 2px 1em;
                 width: 100%;
            }

            td:not(:first-child):before {
                font-size: 0.8em;
                padding-top: 0.1em;
                position: relative;
            }

            td:last-child {
                padding-bottom: 1rem !important;
            }

            tr {
                background-color: white !important;
                border: 1px solid #6cbec6;
                border-radius: 10px;
                box-shadow: 2px 2px 0 rgba(0, 0, 0, 0.1);
                margin: 0.1rem 0;
                padding: 0;
            }

            .table-users {
                border: none;
                box-shadow: none;
                overflow: visible;
            }
        }
    </style>
</head>
<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <!-- Include topbar and leftbar -->
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <div class="content-container">
                <!-- Include leftbar -->
                <?php include('includes/leftbar.php'); ?>
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Add Enthic Group Combination</h2>
                            </div>
                        </div>
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li> Subjects</li>
                                    <li class="active">Add Enthic Group Combination</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div  class="container-fluid" style="margin-top:5px">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>Add Enthic Group Combination</h5>
                                        </div>
                                    </div>

                                    <div class="panel-body">
                                        <!-- Display class selection dropdown -->
<?php

include("includes/db.php");

// Fetch available classes from the database
$classQuery = "SELECT * FROM classes";
$classResult = $conn->query($classQuery);

if ($classResult->num_rows > 0) {
    echo "<form method='post' action='assign_ent_group.php'>";
    echo " <div class='form-group'>";
    echo "<label for='class' >Select Class:</label>";
    echo "<select style='width:250px' name='class_id' id='class' class='form-control' required>";
    echo "<option value=''>Select Class</option>"; // Default option

    while ($row = $classResult->fetch_assoc()) {
        echo "<option value='{$row['Class_id']}'>{$row['class_name']} - {$row['section']}</option>";
    }

    echo "</select>";
    echo "<br>";
    echo "<input type='submit' class='btn btn-primary' value='Fetch Students'>";
    echo "</div>";
    echo "</form>";
} else {
    echo "No classes available.";
}

// Close the database connection
$conn->close();
?>
</section>




<body>

      
        <?php
    
        include("includes/db.php");

        if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['class_id']) && !empty($_POST['class_id'])) {
            $classId = $_POST['class_id'];

            // Fetch available ethnic groups
            $ethnicGroupQuery = "SELECT * FROM ent_group";
            $ethnicGroupResult = $conn->query($ethnicGroupQuery);

            if ($ethnicGroupResult->num_rows > 0) {
                ?>


                <form method="post" action="assign_ent_group.php" onsubmit="return validateForm();">
                    <input type="hidden" name="class_id" value="<?php echo $classId; ?>"> <!-- Pass class_id to the next page -->

                    <!-- Display students for the selected class -->
                    <?php
                    $studentQuery = "SELECT * FROM students WHERE Class_id = $classId";
                    $studentResult = $conn->query($studentQuery);
                    ?>
    <section>
                    <!-- Display table headers for ethnic groups -->
                    <table>
                        <b>Assign Ethnic Groups to Students</b>
                        <tr>
                            <th style="width: 100px;">Student ID</th>
                            <th style="width: 100px;">Student Regd</th>
                            <th style="width: 250px;">Student Name</th>
                            <!-- Display radio buttons for ethnic groups -->
                            <?php
                            while ($ethnicGroup = $ethnicGroupResult->fetch_assoc()) {
                                $groupName1 = $ethnicGroup['group_name'];
                                $entid = $ethnicGroup['id'];
                                echo "<th style='width:110px'>$groupName1</th>";
                            }
                            ?>
                        </tr>

                        <!-- Display students and radio buttons for ethnic groups -->
                        <?php
                        while ($student = $studentResult->fetch_assoc()) {
                            $studentId = $student['student_id'];
                            $studentregd = $student['regd_id'];
                            $studentName = $student['name'];

                            echo "<tr>";
                            echo "<td>$studentId</td>";
                            echo "<td>$studentregd</td>";
                            echo "<td style='align:left'>$studentName</td>";

                            // Display radio buttons for ethnic groups
                            $ethnicGroupResult->data_seek(0); // Reset the pointer to fetch groups again
                            while ($ethnicGroup = $ethnicGroupResult->fetch_assoc()) {
                                $groupName1 = $ethnicGroup['group_name'];
                                $groupName = $ethnicGroup['id'];
                                echo "<td>";
echo "<label>";
echo "<input type='radio' name='student_groups[$studentId]' value='$groupName'>";
echo "<span style='font-size: 80%'>$groupName1</span>";
echo "</label>";
echo "</td>";

                            }

                            echo "</tr>";
                        }
                        ?>
                    </table>
                    </section>
                    <br>
                    <button style='margin-left:250px' type='submit' class='btn btn-primary'>Assign Ethnic Groups</button>
                </form>
            
                <?php
            } else {
                echo "No ethnic groups found in the database.";
            }
        } else {
            echo "Please select a class.";
        }
        ?>
    </div>
</body>
<div>
   <?php

include("includes/db.php");

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['class_id']) && !empty($_POST['class_id'])) {
    $classId = $_POST['class_id'];

    if (isset($_POST['student_groups']) && is_array($_POST['student_groups'])) {
        foreach ($_POST['student_groups'] as $studentId => $selectedGroup) {
            // Sanitize inputs to prevent SQL injection
            $studentId = mysqli_real_escape_string($conn, $studentId);
            $selectedGroup = mysqli_real_escape_string($conn, $selectedGroup);

            // Check if the studentId already exists in the std_ent_group table
            $checkQuery = "SELECT COUNT(*) as count FROM std_ent_group WHERE std_id = '$studentId'";
            $result = $conn->query($checkQuery);
            $row = $result->fetch_assoc();

            // If the studentId exists, update the existing record; otherwise, insert a new one
            if ($row['count'] > 0) {
                $updateQuery = "UPDATE std_ent_group 
                                SET ethnic_group = '$selectedGroup'
                                WHERE std_id = '$studentId'";

                if ($conn->query($updateQuery) === TRUE) {
                    echo "Ethnic group updated for student ID: $studentId<br>";
                } else {
                    echo "Error updating group for student ID: $studentId - " . $conn->error . "<br>";
                }
            } else {
                $insertQuery = "INSERT INTO std_ent_group (std_id, classid, ethnic_group) 
                                VALUES ('$studentId', '$classId', '$selectedGroup')";

                if ($conn->query($insertQuery) === TRUE) {
                    echo "Ethnic group assigned to new student ID: $studentId<br>";
                } else {
                    echo "Error assigning group to new student ID: $studentId - " . $conn->error . "<br>";
                }
            }

            // Update the std_group column in the students table
            $updateStudentQuery = "UPDATE students 
                                   SET std_group = '$selectedGroup'
                                   WHERE student_id = '$studentId'";

            if ($conn->query($updateStudentQuery) === TRUE) {
                echo "Student group updated for student ID: $studentId<br>";
            } else {
                echo "Error updating student group for student ID: $studentId - " . $conn->error . "<br>";
            }
        }
    } else {
        echo "No student groups selected.";
    }
} else {
    echo " ";
}

// Close the database connection
$conn->close();

?>

</div>
</div>
                                </div>
                            </div>
                            <!-- /.col-md-12 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
           </div>
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/DataTables/datatables.min.js"></script>
        <script src="js/main.js"></script>
        <script>
            $(function($) {
                $('#example').DataTable();
            });
        </script>
</body>

</html>