<?php
session_start();
error_reporting('0');
if(isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>
        .card-title a {
            font-size: 16px;
            border-bottom: 1px solid #707478;
            color: #707478;
        }
        .card-title a:hover{
            border-bottom: 1px solid #1A2229;
            color: #1A2229;
        }
        .btn-app:first-child{
            margin-left:0 !important;
        }
        .btn-app:hover {
            background-color: #17a2b8 !important;
            border-color: #17a2b8 !important;
            color: #ffffff !important;
        }

        .btn-app:active{
        background: #c3570f !important;
        color: white !important;
        }
    </style>


    <?php include 'includes/styles.php'; ?>
    <title> Students |  <?php echo $school_name; ?> </title>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Students</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                            <li class="breadcrumb-item active">Students</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <div class="row">
                    <!--          <section class="col-lg-12 connectedSortable">-->
                    <!--           <a href="add-class"><button class="btn btn-outline-success">Add a class</button></a>-->
                    <!--          </section>-->
                    <section class="col-lg-12 connectedSortable">
                        <div class="card">
                            <div class="card-header" style="background: #17a2b8; color: white;">
                                <h3 class="card-title" style="font-size: 15px;"> <i class="fa fa-star"></i> Manage Students </h3>
                            </div>
                            <div class="card-header">
                                <h3 class="card-title"><a href="<?php echo $conn->base_url().'add-student'; ?>"> <i class="fa fa-plus"></i> Add a student </a> </h3>
                            </div>
                            <!-- /.card-header -->
                            <div class="card-body">
                                <h3 class="card-title text-center" style="font-size: 15px;"> Please select a class to view the students <i class="fa fa-info-circle" data-toggle="tooltip" title="N.B: Only classes with students added are clickable." style="cursor:pointer;"></i></h3>
                                <br><br>
                                <div>
                                    <?php

                                    $sql = "SELECT *  FROM classes";
                                    $conn->query($sql);
                                    $result = $conn->fetchMultiple();
                                    $n = 0;
                                    foreach ($result as $class){
                                        $class_name = strtolower($conn->slugify($class->name));
                                        $class_id = $class->id;
                                        //badge color array
                                        $badge_color = array('bg-success', 'bg-purple', 'bg-warning', 'bg-info', 'bg-danger', 'bg-teal', 'bg-primary', 'bg-purple', 'bg-orange', 'bg-yellow', 'bg-secondary', 'bg-dark', 'bg-green', 'bg-blue', 'bg-indigo');
                                        //fetch available section in class
                                        $sql = "SELECT COUNT(studentID) FROM student WHERE classesid =:class_id";
                                        $conn->query($sql);
                                        $conn->bind(":class_id", $class_id);
                                        $students_available = $conn->fetchColumn();
                                        //enable or disable link on number of available sections  href="section/<?php echo $class_id;

                                        $link = $base_url ."student/$class_id";
                                        ?>
                                        <a class="btn btn-app" style="min-width: 120px; height: 90px;" <?php if($students_available != 0){echo "href='$link'";}?>>
                                            <span class="badge <?php echo $badge_color[$n]; ?>" data-toggle="tooltip" title="<?php echo $students_available ?> student(s) available in class <?php echo $class_name; ?>"><?php echo $students_available ?></span>
                                            <i class="fas fa-users" style="font-size: 50px;"></i> <?php echo ucwords(str_replace('-', ' ', $class_name)); ?>
                                        </a>
                                        <?php
                                        $n++;

                                    }
                                    ?>

                                </div>
                                <?php
                                //display selected section below
                                if(isset($_GET['class'])){
                                    $classid = $_GET['class'];
                                    $sql = "SELECT *  FROM student WHERE classesid =:class";
                                    $conn->query($sql);
                                    $conn->bind(":class", $classid);
                                    $result = $conn->fetchMultiple();

                                    //fetch class name

                                    $sql = "SELECT name FROM classes WHERE id =:id";
                                    $conn->query($sql);
                                    $conn->bind(":id", $classid);
                                    $className = $conn->fetchColumn();


                                    ?>
                                    <div class="card-header" style="background: #c3570f; color: white; margin: 20px 0 2px;">
                                        <h3 class="card-title" style="font-size: 17px;"> <i class="fa fa-star"></i> Viewing Students details for class <?php echo $className; ?> </h3>
                                    </div>
                                    <table id="teacher" class="table table-bordered table-striped">
                                        <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Photo</th>
                                            <th>Name</th>
                                            <th>Username</th>
                                            <th>Reg no</th>
                                            <th>Section</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        <?php
                                        $i = 1;
                                        if($conn->rowCount()){
                                            foreach ($result as $student_details):
                                                $name = $student_details->name;
                                                $username= $student_details->username;
                                                $photo = $student_details->photo;
                                                $student_id = $student_details->id;
                                                $sex= $student_details->sex;
                                                $reg_no = $student_details->registerNO;
                                                $status = $student_details->status;
                                                $sectionid = $student_details->sectionid;

                                                   //fetch student section 

                                                $sql = "SELECT name FROM sections WHERE class =:id AND id =:sectionid";
                                                $conn->query($sql);
                                                $conn->bind(":id", $classid);
                                                $conn->bind(":sectionid", $sectionid);
                                                $sectionName = $conn->fetchColumn();
                                                ?>
                                                <tr>
                                      <td><?php echo $i++; ?></td>
                                      <td>
                                          <?php
                                            if(empty($photo)){
                                                ?> <img src="<?php echo $base_url; ?>images/default.png" alt="default" width="48" height="48"><?php
                                            }else{
                                                ?> <img src="<?php echo $base_url; ?>upload/<?php echo $photo;?>" alt="photo" width="48" height="48"><?php
                                            }
                                          ?>
                                      </td>
                                      <td><?php echo $name;?></td>
                                      <td><?php echo $username;?></td>
                                      <td><?php echo $reg_no;?></td>
                                      <td><?php echo $sectionName;?></td>
                                      <td>
                                          <?php
                                            if($status == 'on'){
                                                ?> <i class="fa fa-check-circle" style="font-size: 20px; color: #085d3d; cursor:pointer;" data-toggle="tooltip" title="Active"></i> <?php
                                            }else{
                                                ?> <i class="fa fa-check-circle" style="font-size: 20px; color: #6c757d; cursor:pointer;" data-toggle="tooltip" title="Inactive"></i> <?php
                                            }
                                          ?>
                                      </td>
                                      <td>
                                          <a href="<?php echo $base_url; ?>view-student/<?php echo $username;?>" data-toggle="tooltip" title="View">
                                              <i class="fa fa-check-square"></i>
                                          </a>&nbsp;
                                          <a href="<?php echo $base_url; ?>edit-student/<?php echo $username;?>"  data-toggle="tooltip" title="Edit">
                                              <i class="fa fa-edit"></i>
                                          </a>&nbsp;

                                           <a href="javascript:void();" data-toggle='modal' data-target='#delete-student<?php echo $username;?>'>
                                              <i class="fa fa-trash" data-toggle="tooltip" title="Delete"></i>
                                          </a>
                                        
                                      </td>
                                  </tr>

                                            <?php endforeach; ?>
                                            <?php
                                        }else{
                                            ?> <tr>
                                                <td colspan="7" class="text-center">No Data in table</td>
                                            </tr><?php
                                        }

                                        ?>
                                        </tbody>
                                        <tfoot>
                                        <tr>
                                            <th>#</th>
                                            <th>Photo</th>
                                            <th>Name</th>
                                            <th>Username</th>
                                            <th>Reg no</th>
                                            <th>Section</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                        </tr>
                                        </tfoot>
                                    </table>
                                    <?php


                                }



                                ?>

                            </div>
                            <!-- /.card-body -->
                        </div>


                    </section>
                </div>

                <div id="show-msg">

                </div>
                <!-- /.row (main row) -->
            </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "includes/footer.php";?>

    <?php
    foreach ($result as $student_detail) {
            $name = $student_detail->name;
            $student_username= $student_detail->username;
            $photo = $student_detail->photo;
            $student_id = $student_detail->id;
            $sex= $student_detail->sex;
            $reg_no = $student_detail->register_no;
        # run html delete modal
        ?>

        <!-- Delete member Modal start -->
        <div class="modal fade" id="delete-student<?php echo $student_username;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-md" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Delete student <?php echo $name; ?></h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <h4>Are you sure you want to do this?
                            <br><small class="text-warning">This action will also affect all the scores for this particular student.</small></h4>
                        <form action="" method="post">
                            <div class="form-group">
                                <input type="hidden" name="username" value="<?php echo $student_username; ?>">
                                <div class="form-group">
                                </div>
                            </div>

                            <div class="modal-footer" style="margin-bottom: -10px;">
                                <button class="btn" data-dismiss="modal"><i class="flaticon-cancel-12"></i> Cancel</button>
                                <input type="submit" class="btn btn-outline-danger" value="Delete student anyways" id="submit" name="delete_student">
                            </div>
                        </form>

                    </div>
                </div>
            </div>
        </div>
        <!-- Delete member Modal end -->

        <?php

    }

    if(isset($_POST['delete_student'])){
        $username = $_POST['username'];

        //fetch student name using username
        $sql = "SELECT name FROM student WHERE username =:username";
        $conn->query($sql);
        $conn->bind(":username", $username);
        $student_name = $conn->fetchColumn();
        /*
            * go ahead and update :
            * 1. student table
            * 2. result table,
            * 3. psychomotor table,
            * 4. cognitive table and
            * 5. attendance table with new name
            * 6. student class position
            * 7. pins
            */

        try {
            //delete student from database

            $sql = "DELETE  FROM student WHERE username = :username";
            $conn->query($sql);
            $conn->bind(":username", $username);
            $conn->execute();

            //2. delete student name in results table if it exists
            $sql = "SELECT name_of_student FROM results WHERE name_of_student =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                $sql = "DELETE FROM results WHERE name_of_student =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //3. delete student name in psychomotor if it exists
            $sql = "SELECT student_name FROM students_psychomotor WHERE student_name =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                $sql = "DELETE FROM students_psychomotor WHERE student_name =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //4. delete student name in cognitive if it exists

            $sql = "SELECT student_name FROM students_cognitive_area WHERE student_name =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                $sql = "DELETE FROM students_cognitive_area WHERE student_name =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //5. delete student name in attendance if it exists

            $sql = "SELECT student_name FROM attendance WHERE student_name =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                $sql = "DELETE FROM attendance WHERE student_name =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //6. delete name in student class position if it exists

            $sql = "SELECT name FROM student_class_positions WHERE name =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                $sql = "DELETE FROM student_class_positions WHERE name =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //7. delete name in pins if it exists

            $sql = "SELECT used_by FROM pins WHERE used_by =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                //update old student name with new student name
                $sql = "DELETE FROM pins WHERE used_by =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            //8. delete name in subject positions if it exists

            $sql = "SELECT name FROM subject_positions WHERE name =:student_name";
            $conn->query($sql);
            $conn->bind(":student_name", $student_name);
            if($conn->rowCount() > 0){
                //update old student name with new student name
                $sql = "DELETE FROM subject_positions WHERE name =:student_name";
                $conn->query($sql);
                $conn->bind(":student_name", $student_name);
                $conn->execute();
            }

            echo "<p class='alert alert-success alert-dismissible fade show' role='alert'>
                    <i class='fas fa-check-circle'></i> Student deleted successfully.
                  <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
                             <span aria-hidden=\"true\">×</span>
                  </button>
                   <meta http-equiv='refresh' content='3; ../student'>
                  
           </p>";

        }catch (PDOException $err){
            $error = $err->getMessage();
            echo "<p class='alert alert-danger alert-dismissible fade show' role='alert'>
                    <i class='fas fa-check-circle'></i> An error occurred: $error
                  <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\">
                             <span aria-hidden=\"true\">×</span>
                  </button>
                   <meta http-equiv='refresh' content='3; ../student'>
                  
           </p>";
        }

    }

    ?>

    <script>
        $(document).ready(function(){
            $('[data-toggle="tooltip"]').tooltip();
        });
    </script>

    <script>
        $(function () {
            $("#teacher").DataTable({
                "responsive": true, "lengthChange": false, "autoWidth": false,
                "buttons": ["copy", "csv", "pdf", "print"]
            }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
            $('#example2').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true
            });
        });
    </script>

    <?php
    }else{
    ?>
    <!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, maximum-scale=1, shrink-to-fit=no">
        <title>Login to continue |  <?php echo $school_name; ?> </title>

        <?php include 'includes/styles.php'; ?>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
