<?php
namespace App\Controllers;
SESSION_START();
use \Core\View;
use \Core\Inputs;
use \Core\Userlog;
use \Core\Menu;
use \Core\Form;
use App\Models\Homem;
use App\Email\Emails;
class Internalexams extends \Core\Controller
{
    // Supporting Scripts for every page common started
    private static function css()
    {
        $css = 
        '<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
            <title>Hindu College of Engineering & Technology || Guntur</title>
            <link rel="icon" href = "https://assets.hinduengg.com/hindu/assets/img/logo.png" type = "image/x-icon"> 
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
            <title>Hindu College of Engineering & Technology || Guntur</title>
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/css/bootstrap.min.css">
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/css/style.css">
            <link rel="stylesheet" href="https://assets.hinduengg.com/hindu/assets/sweetalert2/sweetalert2.min.css" >
            <style>
                @media print
                {
                    body * {
                        visibility: hidden;
                    }
                    .print-this, .print-this * {
                        visibility: visible;
                    }
                }
            </style>
            <script>
                function exportTableToExcel(tableID, filename = "")
                {
                    var downloadLink;
                    var dataType = "application/vnd.ms-excel";
                    var tableSelect = document.getElementById(tableID);
                    var tableHTML = tableSelect.outerHTML.replace(/ /g, "%20");
                    
                    // Specify file name
                    filename = filename?filename+".xls":"excel_data.xls";
                    
                    // Create download link element
                    downloadLink = document.createElement("a");
                    
                    document.body.appendChild(downloadLink);
                    
                    if(navigator.msSaveOrOpenBlob){
                        var blob = new Blob(["\ufeff", tableHTML], {
                            type: dataType
                        });
                        navigator.msSaveOrOpenBlob( blob, filename);
                    }else{
                        // Create a link to the file
                        downloadLink.href = "data:" + dataType + ", " + tableHTML;
                    
                        // Setting the file name
                        downloadLink.download = filename;
                        
                        //triggering the function
                        downloadLink.click();
                    }
                }
            </script>
        </head>';
        return $css;  
    }
    private static function script()
    {
        $script =
                '
                <div class="footer navbar-fixed-bottom text-center">        
                    <span class="text-muted text-center">Copyright &#169 2020. Hindu College of Engineering & Technology, Guntur</span>
                </div>
                <script src="https://assets.hinduengg.com/hindu/assets/word/jquery.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/js/bootstrap.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/sweetalert2/dist/sweetalert2.min.js" ></script>
                <!-- Script to stop mouse right click start-->
            <script>
                //Disable right click script
                var message = "";
                ///////////////////////////////////
                function clickIE() {
                    if (document.all) {
                        (message);
                        return false;
                    }
                }

                function clickNS(e) {
                    if (document.layers || (document.getElementById && !document.all)) {
                        if (e.which == 2 || e.which == 3) {
                            (message);
                            return false;
                        }
                    }
                }
                if (document.layers) {
                    document.captureEvents(Event.MOUSEDOWN);
                    document.onmousedown = clickNS;
                } else {
                    document.onmouseup = clickNS;
                    document.oncontextmenu = clickIE;
                }

                document.oncontextmenu = new Function("return false")
            </script>
            <!-- Script to stop mouse right click end-->

            <!-- Script to prevent selection start-->
            <script>
                $(document).ready(function () {
                    $("body").bind("cut copy", function (e) {
                        e.preventDefault();
                    });
                });
            </script>
            <!-- Script to prevent selection end-->
                ';
        return $script;  
    }
    private static function sscript()
    {
        $script =
                '
                <div class="footer navbar-fixed-bottom text-center">        
                    <span class="text-muted text-center">Copyright &#169 2020. Hindu College of Engineering & Technology, Guntur</span>
                </div>
                <script src="https://assets.hinduengg.com/hindu/assets/word/jquery.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/js/bootstrap.min.js" ></script>
                <script src="https://assets.hinduengg.com/hindu/assets/sweetalert2/dist/sweetalert2.min.js" ></script>
                ';
        return $script;  
    }
    public static function checkbrower()
    {
        $mystring = $_SERVER['HTTP_USER_AGENT'];
        $word = 'Chrome';
        if(strpos($mystring, $word) !== false)
        {
            echo "1";
        }
        else
        {
            echo "0";
        }
    }
    public static function checkurl()
    {
        $url= $_SERVER['HTTP_HOST'];   
        return $url;
    }
    // Non used function
    public static function blockingscripts()
    {
        $a .= '
            <!--Script to confirm refresh start-->
            <script type="text/javascript">
                window.onbeforeunload = function () {
                    return "The Data in this page may lost. Do you want to refresh this page now.?";
                }
            </script>
            <!--Script to confirm refresh end-->
            <!--Script to Disable keyboard start-->
            <!--
                <script  type="text/javascript">
                    document.onkeydown = function (e) {	return false;}
                    $(function() {
                        $(this).bind("contextmenu", function(e) {
                            e.preventDefault();
                        });
                    });	
                </script>
            -->
            <!--Script to Disable keyboard end-->

            <!--Script to stop mouse move up and down start-->
            <script  type="text/javascript">
                $(document).ready(function () {
                        addEvent(document, "mouseout", function(e) {
                            e = e ? e : window.event;
                            var from = e.relatedTarget || e.toElement;
                            if (!from || from.nodeName == "HTML") {
                                console.log("Out of zone");
                                // swal("Sorry! Not Permitted to enter this area..", "You are not permitted to enter in to this area...", "error");
                            }
                        });
                });
                    function addEvent(obj, evt, fn) {
                        if (obj.addEventListener) {
                            obj.addEventListener(evt, fn, false);
                        }
                        else if (obj.attachEvent) {
                            obj.attachEvent("on" + evt, fn);
                        }
                    }
            </script>
            <!--Script to stop mouse move up and down end-->

            <!-- Script to prevent back button start-->
            <script>
                (function (global) {
                    if (typeof (global) === "undefined") {
                        throw new Error("window is undefined");
                    }
                    var _hash = "!";
                    var noBackPlease = function () {
                        global.location.href += "#";
                
                        // making sure we have the fruit available for juice....
                        // 50 milliseconds for just once do not cost much (^__^)
                        global.setTimeout(function () {
                            global.location.href += "!";
                        }, 50);
                    };
                    // Earlier we had setInerval here....
                    global.onhashchange = function () {
                        if (global.location.hash !== _hash) {
                            global.location.hash = _hash;
                        }
                    };
                    global.onload = function () {
                        noBackPlease();
                        // disables backspace on page except on input fields and textarea..
                        document.body.onkeydown = function (e) {
                            var elm = e.target.nodeName.toLowerCase();
                            if (e.which === 8 && (elm !== "input" && elm !== "textarea")) {
                                e.preventDefault();
                            }
                            // stopping event bubbling up the DOM tree..
                            e.stopPropagation();
                        };
                    };
                })(window);
                
            </script>
            <!-- Script to prevent back button end-->

            <!-- Script to stop mouse right click start-->
            <script>
                //Disable right click script
                var message = "";
                ///////////////////////////////////
                function clickIE() {
                    if (document.all) {
                        (message);
                        return false;
                    }
                }

                function clickNS(e) {
                    if (document.layers || (document.getElementById && !document.all)) {
                        if (e.which == 2 || e.which == 3) {
                            (message);
                            return false;
                        }
                    }
                }
                if (document.layers) {
                    document.captureEvents(Event.MOUSEDOWN);
                    document.onmousedown = clickNS;
                } else {
                    document.onmouseup = clickNS;
                    document.oncontextmenu = clickIE;
                }

                document.oncontextmenu = new Function("return false")
            </script>
            <!-- Script to stop mouse right click end-->

            <!-- Script to prevent selection start-->
            <script>
                $(document).ready(function () {
                    $("body").bind("cut copy", function (e) {
                        e.preventDefault();
                    });
                });
            </script>
            <!-- Script to prevent selection end-->
            ';
    }
    public static function jscripttime()
    {
        echo '
        <p id="demo"></p>
        <script>
        function presentdatetime()
        {
            var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Kolkata"});
            var d = new Date(d);
            var y = d.getFullYear()+"-";
            var m = parseInt(d.getMonth())+1;
            var da = "-"+d.getDate();
            var h = " "+d.getHours();
            var min = ":"+d.getMinutes();
            var s = ":"+d.getSeconds();
            var total = y+m+da+h+min+s;
            return total;
        }
            document.getElementById("demo").innerHTML = presentdatetime();
        </script>
        ';
    }
    // Supporting Scripts for every page common Ended
    
    
    // Internal Exam Dates Fixation
    public static function fixdatesofinternalexam()
    {
        if($_SESSION['user_role'] == 9 || $_SESSION['user_role'] == 4 || $_SESSION['user_role'] == 8 || $_SESSION['user_role'] == 6 || $_SESSION['user_role'] == 7)
        {
            $table = '';
            $course = Inputs::optionsdb(Homem::getdata("SELECT * FROM `degree_name_master`"), 'id', 'code');
            $dept = Inputs::optionsdb(Homem::getdata("SELECT * FROM `degree_dept_master`"), 'id', 'name');
            $fdept = Inputs::optionsdb($data = Homem::getdata("SELECT * FROM (SELECT DISTINCT `fk_dept_id` FROM `user_master` WHERE `user_role`!='3' AND `fk_dept_id`!='' AND `org_id`='$_SESSION[org_id]') a JOIN degree_dept_master ddm ON a.fk_dept_id=ddm.id"), 'id', 'name');
            $data = Homem::getdata("SELECT sd.*, sf.student_year as syear, sf.add_date, um.name as fname FROM subject_faculty sf JOIN subject_data sd ON sf.fk_sub_id=sd.sub_id JOIN user_master um ON sf.fk_user_id=um.id WHERE sf.status='1' ORDER BY sf.sf_id ASC");
            if($data > 0)
            {
                $table = Form::dbtableed($data, ['Regulation', 'Subject Code', 'Subject Name', 'Type', 'Faculty Name', 'Join Year'], ['regulation', 'subcode', 'subname', 'type', 'fname', 'syear'], '', '', '');
            }
            echo static::css();
            echo '<body>';
            echo $_SESSION['menu'];
            echo '
                <div class="clearfix"></div>
                <form action="/Internalexams/savefixdatesofinternalexam" method="POST">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-2"></div>
                            <div class="col-lg-8">                                       
                                <div class="row">
                                    <div class="col-lg-12">
                                        <section class="box" style="margin-top: 10px;">
                                            <header class="panel_header">
                                                <h4 class="title pull-left">Create Examination Time Table</h4>
                                            </header>
                                            <div class="content-body"> 
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <h6>Select Subject</h6>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="course" id="course" class="form-control" onchange="getstdjoinyear()">
                                                            <option value="">Course</option>
                                                            ';
                                                            echo $course;
                                                            echo '
                                                            </select>
                                                        </div>
                                                    </div>    
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="dept" id="dept" class="form-control" onchange="getregulation()">
                                                            <option value="">Select Department</option>
                                                            </select>
                                                        </div>
                                                    </div> 
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="regulation" id="regulation" class="form-control" >
                                                            <option value="">Select Regulation</option>
                                                            </select>
                                                        </div>
                                                    </div>                           
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="year" id="year" class="form-control">
                                                            <option value="">Select Year</option>
                                                            <option value="1">First Year</option>
                                                            <option value="2">Second Year</option>
                                                            <option value="3">Third Year</option>
                                                            <option value="4">Fourth Year</option>
                                                            </select>
                                                        </div>
                                                    </div>   
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="sem" id="sem" class="form-control" onchange="getstudentyear()">
                                                                <option value="">Select Semester</option>
                                                                <option value="1">First Sem</option>
                                                                <option value="2">Second Sem</option>
                                                            </select>
                                                        </div>
                                                    </div> 
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="syear" id="syear" class="form-control" onchange="getstudentdetails()">
                                                                <option value="">Select Students Joining Year</option>
                                                            </select>
                                                        </div>
                                                    </div> 										
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="mid" id="mid" class="form-control">
                                                                <option value="">Select Mid</option>
                                                                <option value="1">First (Mid - 1)</option>
                                                                <option value="2">Second (Mid - 2)</option>
                                                                <option value="3">Third (Mid - 3)</option>
                                                            </select>
                                                        </div>
                                                    </div> 
                                                    <div class="col-lg-4">
                                                        <div class="form-group">                                            
                                                            <select name="midtype" id="midtype" class="form-control">
                                                                <option value="">Select Mid Type</option>
                                                                <option value="1">Descriptive</option>
                                                                <option value="2">Quiz</option>
                                                                <option value="3">Online</option>
                                                            </select>
                                                        </div>
                                                    </div> 
                                                    <div class="col-lg-4">
                                                        <div class="form-group">    
                                                            <input type="text" name="time" id="time" class="form-control" placeholder="Time of Exam" onfocus="this.type=`time`" onblur="this.type=`text`">
                                                            <input type="hidden" name="edit_id" id="edit_id" class="form-control" placeholder="Edit ID">
                                                        </div>
                                                    </div> 										
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <div id="subjectdetails" class="subjectdetails">
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-md-12">  
                                                        <div class="form-group">
                                                            <button id="btn_reg" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <div id="students" class="students">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>                        
                                        </section>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-2"></div>
                        </div>
                        <div class="row">
                            <div class="col-lg-1"></div>
                            <div class="col-lg-10">
                            '.$table.'
                            </div>
                            <div class="col-lg-1"></div>
                        </div>
                    </div>
                </form>
                ';
            echo '</body>';
            echo static::script();
            echo '
            <script>
                function getstdjoinyear()
                {
                    var course = document.getElementById("course").value;
                    var dept = document.getElementById("dept").value;
                    $.ajax({
                        type: "POST",
                        data : {course: course},
                        url: "/Exams/getstdjoinyear",
                        success: function(d){
                            $("#dept").html(d);
                            
                        }
                    });
                }
                function getregulation()
                {
                    
                    var course = document.getElementById("course").value;
                    var dept = document.getElementById("dept").value;
                    $.ajax({
                        type: "POST",
                        data : {course: course, dept: dept},
                        url: "/Exams/getregulation",
                        success: function(d){
                            $("#regulation").html(d);
                            
                        }
                    });
                }
                function getsubjects()
                {
                    var course = document.getElementById("course").value;
                    var dept = document.getElementById("dept").value;
                    var regulation = document.getElementById("regulation").value;
                    var year = document.getElementById("year").value;
                    var sem = document.getElementById("sem").value;
                    var syear = document.getElementById("syear").value;
                    $.ajax({
                        type: "POST",
                        data : {course: course, dept: dept, regulation: regulation, year: year, sem: sem, syear: syear},
                        url: "/Internalexams/getsubjectsgrid",
                        success: function(d){
                            $("#subjectdetails").html(d);
                        }
                    });
                }
                function getstudentyear()
                {
                    var course = document.getElementById("course").value;
                    var dept = document.getElementById("dept").value;
                    var regulation = document.getElementById("regulation").value;
                    $.ajax({
                        type: "POST",
                        data : {course: course, dept: dept, regulation: regulation},
                        url: "/Exams/getstudentyear",
                        success: function(d){
                            $("#syear").html(d);
                        }
                    });
                }
                function getstudentdetails()
                {
                    var course = document.getElementById("course").value;
                    var dept = document.getElementById("dept").value;
                    var regulation = document.getElementById("regulation").value;
                    var syear = document.getElementById("syear").value;
                    $.ajax({
                        type: "POST",
                        data : {course: course, dept: dept, regulation: regulation, syear: syear},
                        url: "/Exams/getstudentdetails",
                        success: function(d){
                            $("#students").html(d);
                            getsubjects();
                            // alert(course+dept+regulation+syear);
                        }
                    });
                }
            </script>
            ';
            if(isset($_GET['status']))
            {
                if($_GET['status'] == 1)
                {
                    echo '<script>swal("", "Inserted Successfully", "success");</script>';
                }
                else if($_GET['status'] == 2)
                {
                    echo '<script>swal("", "Updated Successfully", "success");</script>';
                }
                else
                {
                    echo '<script>swal("", "Something went Wrong.. Please try again later..", "error");</script>';
                }
            }
        }
    }
    public static function savefixdatesofinternalexam()
    {
        if($_SESSION['user_role'] == 9 || $_SESSION['user_role'] == 8 || $_SESSION['user_role'] == 6 || $_SESSION['user_role'] == 7)
        {
            if($_POST['edit_id'] == '')
            {
                date_default_timezone_set('Asia/Kolkata'); 
                $edate = date('Y-m-d');
                $etime = date('Y-m-d H:i:s A');
                $work = array();
                $work = $_POST['work'];
                
                $sid = array();
                $sid = $_POST['sid'];
                $marks = array();
                $marks = $_POST['marks'];
                $fid = array();
                $fid = $_POST['fid'];
                $date = array();
                $date = $_POST['edate'];
                $acount = 0;
                for($i=0; $i<sizeof($work); $i++)
                {
                    if($work[$i] == 1 && $edate[$i] != '' && $fid[$i] != '' && $marks[$i] != '')
                    {
                        $acount++;
                    }
                }
                // $acount = static::arraysum($work);
                Homem::insert("INSERT INTO `mid_tt_master` (`id`, `course`, `dept`, `regulation`, `year`, `sem`, `syear`, `mid`, `midtype`, `time`, `scount`, `acount`, `resultstatus`, `fk_user_id`, `edate`, `etime`, `status`, `locks`) VALUES 
                (NULL, '$_POST[course]', '$_POST[dept]', '$_POST[regulation]', '$_POST[year]', '$_POST[sem]', '$_POST[syear]', '$_POST[mid]', '$_POST[midtype]', '$_POST[time]', '$_POST[scount]', '$acount', '0', '$_SESSION[user_id]', '$edate', '$etime', '1', '0')");
                $ndata = Homem::getdata("SELECT * FROM `mid_tt_master` WHERE `course`='$_POST[course]' AND `dept`='$_POST[dept]' AND `regulation`='$_POST[regulation]' AND `year`='$_POST[year]' AND `sem`='$_POST[sem]' AND `syear`='$_POST[syear]' AND `mid`='$_POST[mid]' AND `midtype`='$_POST[midtype]' AND `scount`='$_POST[scount]' AND `fk_user_id`='$_SESSION[user_id]' AND `edate`='$edate' ORDER BY `id` DESC");
                $id= $ndata[0]['id'];
                for($i=0; $i<sizeof($work); $i++)
                {
                    if($work[$i] == 1 && $edate[$i] != '' && $fid[$i] != '' && $marks[$i] != '')
                    {
                        Homem::insert("INSERT INTO `mid_tt_submaster` (`id`, `masterid`, `sub_id`, `faculty_id`, `examdate`, `maxmarks`, `resultdate`, `appeared`, `absents`, `resultstatus`, `approval`) VALUES 
                        (NULL, '$id', '$sid[$i]', '$fid[$i]', '$date[$i]', '$marks[$i]', '', '', '', '0', '')");
                    }
                    
                }
                echo '<script>window.location = "/Internalexams/fixdatesofinternalexam?status=1";</script>';
            }
            else
            {
                echo '<script>window.location = "/Internalexams/fixdatesofinternalexam?status=0";</script>';
            }
        }
    }
    public static function arraysum($data)
    {
        $sum = 0;
        for($i=0; $i<sizeof($data); $i++)
        {
            $sum = $sum + $data[$i];
        }
        return $sum;
    }
    // Supprting funcitons for fixdatesofinternalexam() Start
    public static function getsubjectsgrid()
    {
        $data = Homem::getdata("SELECT sd.sub_id, sd.subcode, sd.subname, sd.type, um.id, um.name FROM subject_faculty sf JOIN subject_data sd ON sf.fk_sub_id=sd.sub_id JOIN user_master um ON sf.fk_user_id=um.id WHERE sf.status='1' AND sd.course='$_POST[course]' AND sd.dept='$_POST[dept]' AND sd.regulation='$_POST[regulation]' AND sd.year='$_POST[year]' AND sd.sem='$_POST[sem]' AND sf.student_year='$_POST[syear]'");
        echo '<h6>List of subjects in the class: (Number of subjects: '.sizeof($data).')</h6>';
            echo '<input type="hidden" name="scount" id="scount" placeholder="Count" value="'.sizeof($data).'">';
            $data1 = '
            <div class="table-responsive">
                <table class="table table-responsive-sm">
                    <thead>
                        <tr>
                            <th><input type="checkbox" name="allworking" id="allworking" onchange="setallpresent()">Available</th>
                            <th>Subject Code</th>
                            <th>Subject Name</th>
                            <th>Faculty Name</th>
                            <th>Exam Date</th>
                            <th>Max Marks</th>
                        </tr>
                    </thead>
                    <tbody>';
            for($i=0; $i<sizeof($data); $i++)
            {
                $data1 .= '<tr><td><input type="hidden" name="work['.$i.']" id="work['.$i.']" value="0"> <input type="checkbox" name="work['.$i.']" id="work['.$i.']" value="1"></td>';
                $data1 .= '<td><input type="hidden" name="sid['.$i.']" id="sid['.$i.']" value="'.$data[$i]['sub_id'].'">'.$data[$i]['subcode'].'</td>';
                $data1 .= '<td><input type="hidden" name="sname['.$i.']" id="sname['.$i.']" value="'.$data[$i]['name'].'">'.$data[$i]['subname'].' (<b>'.$data[$i]['type'].'</b>)</td>';
                $data1 .= '<td><input type="hidden" name="fid['.$i.']" id="fid['.$i.']" value="'.$data[$i]['id'].'">'.$data[$i]['name'].'</td>';
                $data1 .= '<td><input type="text" name="edate['.$i.']" id="edate['.$i.']" placeholder="Exam Date" class="form-control" onfocus="this.type=`date`" onblur="this.type=`text`"></td>';
                $data1 .= '<td><input type="text" name="marks['.$i.']" id="marks['.$i.']" placeholder="Max Marks" class="form-control" onfocus="this.type=`number`" onblur="this.type=`text`"></td>';
                // $data1 .= '<td><input type="hidden" name="mobile['.$i.']" id="mobile['.$i.']" value="'.$data[$i]['fmobile'].'">'.$data[$i]['fmobile'].'</td>';
                $data1 .= '</tr>';
            }
            $data1 .= '</tbody></table>';
            echo $data1;
            echo '
            <script type="text/javascript">  
                $(document).ready(function() {
                });
                function setallpresent()
                {
                    var present = document.getElementById("allworking");
                    if(present.checked == true)
                    {
                        selects();
                    }
                    else
                    {
                        deselects();
                    }
                }
                function selects()
                {  
                    var scount = document.getElementById("scount");
                    for(var i=0; i<scount.value; i++)
                    { 
                        var a = "work["+i+"]";
                        // $("#elementId").attr("required", ""); 
                        // element.required = false; 
                        var ele=document.getElementsByName(a);
                        for(var j=0; j<ele.length; j++)
                        {  
                            if(ele[j].type=="checkbox")  
                            {
                                ele[j].checked=true;
                            }
                        }
                    }
                }   
                function deselects()
                {  
                    var scount = document.getElementById("scount");
                    for(var i=0; i<scount.value; i++)
                    { 
                        var a = "work["+i+"]";
                        var ele=document.getElementsByName(a);
                        for(var j=0; j<ele.length; j++)
                        {  
                            if(ele[j].type=="checkbox")  
                            {
                                ele[j].checked=false;
                            }
                        }
                    }
                }          
            </script>  
            ';
    }
    // Supprting funcitons for fixdatesofinternalexam() End
    
    
    // Internal subject marks entry
    public static function singlesubjectinternalmarksentry()
    { 
        if($_SESSION['user_role'] == 8 || $_SESSION['user_role'] == 6 || $_SESSION['user_role'] == 7 || $_SESSION['user_role'] == 2 || $_SESSION['user_role'] == 4)
        {
            $query = Homem::getdata("SELECT mts.id, sd.subcode, sd.subname, mtm.mid FROM mid_tt_submaster mts JOIN subject_data sd ON mts.sub_id=sd.sub_id JOIN mid_tt_master mtm ON mtm.id=mts.masterid WHERE mts.resultstatus='0' AND mts.faculty_id='$_SESSION[user_id]'");
            $data = '';
            $table ='';
            for($i=0; $i<sizeof($query); $i++)
            {
                $data .= '<option value="'.$query[$i]['id'].'">'.$query[$i]['subname'].'('.$query[$i]['subcode'].')- Mid-'.$query[$i]['mid'].'</option>';
            }
            echo static::css();
            echo '<body>';
                echo $_SESSION['menu'];
                {
                    echo '
                    <div class="clearfix"></div>
                    <form action="/Internalexams/savesinglesubjectinternalmarksentry" method="POST">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-3"></div>
                            <div class="col-lg-6">                                       
                                <div class="row">
                                    <div class="col-lg-12">
                                        <section class="box" style="margin-top: 30px;">
                                            <header class="panel_header">
                                                <h4 class="title pull-left">Internal Exam Marks Entry</h4>
                                                <div class="actions panel_actions pull-right">
                                                    <a class="fa fa-refresh" onclick="refreshClick()"></a>
                                                    <a class="box_toggle fa fa-chevron-down"></a>
                                                </div>
                                            </header>
                                            <div class="content-body">    
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <div class="form-group">                                      
                                                            <select id="mtsid" name="mtsid" class="form-control" onchange="getstudentdetailsforinternalmarksentry()" required>
                                                                <option value="">Select Subject</option>
                                                                '.$data.'
                                                            </select>
                                                        </div>
                                                    </div>   
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <div class="form-group">                
                                                            <input type="hidden" name="course" id="course" class="form-control" placeholder="Course" required>      
                                                            <input type="hidden" name="dept" id="dept" class="form-control" placeholder="Dept" required>    
                                                            <input type="hidden" name="year" id="year" class="form-control" placeholder="Year" required>    
                                                            <input type="hidden" name="sem" id="sem" class="form-control" placeholder="Sem" required>    
                                                            <input type="hidden" name="syear" id="syear" class="form-control" placeholder="Studnet Year" required>    
                                                            <input type="hidden" name="edit_id" id="edit_id" class="form-control" placeholder="Edit ID">
                                                        </div>
                                                    </div>  										
                                                </div>
                                                <div class="row">
                                                    <div class="col-lg-12">
                                                        <div id="students" class="students">
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-12">  
                                                        <div class="form-group">
                                                            <button id="btn_reg" class="btn btn-primary pull-right" type="submit" style="background-color: #002366 !important;">Submit</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>                        
                                        </section>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-3"></div>
                        </div>
                        <div class="row">
                            <div class="col-lg-12">
                                <div id="students" class="students">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-1"></div>
                            <div class="col-lg-10">
                            '.$table.'
                            </div>
                            <div class="col-lg-1"></div>
                        </div>
                    </div>
                    </form>';
                }
            echo '</body>';
            echo static::sscript();
            echo '<script>
            function getstudentdetailsforinternalmarksentry()
            {
                    var mtsid = document.getElementById("mtsid").value;
                    $.ajax({
                        type: "POST",
                        data : {mtsid: mtsid},
                        url: "/Internalexams/getstudentdetailsforinternalmarksentry",
                        success: function(d){
                            $("#students").html(d);
                            
                        }
                    });
            }
            </script>';
            
        }
    }
    public static function savesinglesubjectinternalmarksentry()
    {
        if($_SESSION['user_role'] == 8 || $_SESSION['user_role'] == 6 || $_SESSION['user_role'] == 7)
        {
            if($_POST['edit_id'] == '')
            {
                date_default_timezone_set('Asia/Kolkata'); 
                $edate = date('Y-m-d');
                $etime = date('Y-m-d H:i:s A');
                $work = array();
                $work = $_POST['work'];
                $sid = array();
                $sid = $_POST['sid'];
                $marks = array();
                $marks = $_POST['marks'];
                $acount = $_POST['dcount'];
                $pcount = 0;
                
                for($i=0; $i<sizeof($work); $i++)
                {
                    if($work[$i] == 1)
                    {
                        $pcount++;
                        $data[$sid[$i]]['marks']= $marks[$i];
                    }
                    else
                    {
                        $data[$sid[$i]]['marks']= 'A';
                    }
                }
                $absent = $acount-$pcount;
                if(sizeof(Homem::getdata("SELECT * FROM `mid_marks` WHERE `mtsid`='$_POST[mtsid]'"))==0)
                {
                    Homem::update("UPDATE `mid_tt_submaster` SET `resultdate`='$edate', `appeared`='$acount', `absents`='$absent', `resultstatus`='1', `approval`='0' WHERE `id`='$_POST[mtsid]' AND `faculty_id`='$_SESSION[user_id]'");
                    for($i=0; $i<sizeof($sid); $i++)
                    {
                        $stdid = $sid[$i];
                        $marks = $data[$sid[$i]]['marks'];
                        $status = $work[$i];
                        Homem::insert("INSERT INTO `mid_marks` (`id`, `mtsid`, `sid`, `marks`, `status`, `modified`) VALUES (NULL, '$_POST[mtsid]', '$stdid', '$marks', '$status', '0')");
                        
                    }
                }
                echo '<script>window.location = "/Internalexams/singlesubjectinternalmarksentry?status=1";</script>';
            }
        }
    }
    public static function getstudentdetailsforinternalmarksentry()
    {
        if(isset($_POST['mtsid']))
        {
            $data = Homem::getdata("SELECT DISTINCT um.id, um.no, um.name FROM mid_tt_submaster mts JOIN mid_tt_master mtm ON mts.masterid=mtm.id JOIN user_master um ON um.fromyear=mtm.syear WHERE mts.id='$_POST[mtsid]' AND mtm.course=um.fk_course_id AND mtm.dept=um.fk_dept_id AND mtm.regulation=um.regulation");
            // $data = Homem::getdata("SELECT DISTINCT um.id, um.no, um.name FROM mid_tt_submaster mts JOIN subject_faculty sf ON sf.fk_sub_id=mts.sub_id JOIN user_master um ON um.fromyear=sf.student_year JOIN mid_tt_master mtm ON mtm.course=um.fk_course_id WHERE mts.id='$_POST[mtsid]' AND mts.faculty_id=sf.fk_user_id AND mtm.dept=um.fk_dept_id AND mtm.course=um.fk_course_id AND um.user_role='3'");
            echo '<h6>List of students in the class: (Number of students: '.sizeof($data).')</h6>';
            echo '<input type="hidden" name="dcount" id="dcount" placeholder="Count" value="'.sizeof($data).'">';
            $data1 = '
            <div class="table-responsive">
                <table class="table table-responsive-sm">
                    <thead>
                        <tr>
                            <th><input type="checkbox" name="allworking" id="allworking" onchange="setallpresent()">Present</th>
                            <th>Hallticket</th>
                            <th>Name</th>
                            <th>Marks</th>
                        </tr>
                    </thead>
                    <tbody>';
            for($i=0; $i<sizeof($data); $i++)
            {
                $data1 .= '<tr><td><input type="hidden" name="work['.$i.']" id="work['.$i.']" value="0"> <input type="checkbox" name="work['.$i.']" id="work['.$i.']" value="1"></td>';
                $data1 .= '<td><input type="hidden" name="sid['.$i.']" id="sid['.$i.']" value="'.$data[$i]['id'].'">'.$data[$i]['no'].'</td>';
                $data1 .= '<td><input type="hidden" name="name['.$i.']" id="name['.$i.']" value="'.$data[$i]['name'].'">'.$data[$i]['name'].'</td>';
                $data1 .= '<td><input type="text" name="marks['.$i.']" id="marks['.$i.']" placeholder="'.$data[$i]['no'].'" class="form-control" required></td>';
                // $data1 .= '<td><input type="hidden" name="mobile['.$i.']" id="mobile['.$i.']" value="'.$data[$i]['fmobile'].'">'.$data[$i]['fmobile'].'</td>';
                $data1 .= '</tr>';
            }
            $data1 .= '</tbody></table>';
            echo $data1;
            echo '
            <script type="text/javascript">  
                $(document).ready(function() {
                });
                function setallpresent()
                {
                    var present = document.getElementById("allworking");
                    if(present.checked == true)
                    {
                        selects();
                    }
                    else
                    {
                        deselects();
                    }
                }
                function selects()
                {  
                    var scount = document.getElementById("dcount");
                    for(var i=0; i<scount.value; i++)
                    { 
                        var a = "work["+i+"]";
                        var ele=document.getElementsByName(a);
                        for(var j=0; j<ele.length; j++)
                        {  
                            if(ele[j].type=="checkbox")  
                            {
                                ele[j].checked=true;
                            }
                        }
                    }
                }   
                function deselects()
                {  
                    var scount = document.getElementById("dcount");
                    for(var i=0; i<scount.value; i++)
                    { 
                        var a = "work["+i+"]";
                        var ele=document.getElementsByName(a);
                        for(var j=0; j<ele.length; j++)
                        {  
                            if(ele[j].type=="checkbox")  
                            {
                                ele[j].checked=false;
                            }
                        }
                    }
                }          
            </script>  
            ';
        }
    }
    
    
    
}