<?php 
include ('../includes/connection.php'); 
include('sms.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

 
require 'vendor/autoload.php';

if(isset($_GET['del']))
{
$id= $_GET['del']; 
$sql =mysqli_query($conn,"DELETE FROM `exam_invoice` WHERE invoice_id = $id");
header('location:admin.php?page=invoice"');
}
if(isset($_GET['Id_3']))
{
$id=$_GET['Id_3'];
$status='Disable'; 
$sql =mysqli_query($conn,"update exam_invoice set invoice_status='$status' WHERE invoice_id='$id'");
header('location:admin.php?page=invoice"');
}

//code for active students
if(isset($_GET['Id_2']))
{
$id=$_GET['Id_2'];
$status='Enable'; 
$sql =mysqli_query($conn,"update exam_invoice set invoice_status='$status' WHERE invoice_id='$id'");
header('location:admin.php?page=invoice"');
} 


if (isset($_POST['update'])){
$invoice_id = $_POST['invoice_id']; 
$payment_code=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, 8);
// $payment_code = $_POST['payment_code'];  
$amount = $_POST['amount']; 

$query1= mysqli_query($conn,"SELECT * FROM exam_invoice INNER JOIN student_soes ON student_soes.student_id = exam_invoice.student_id WHERE invoice_id='$invoice_id'")or die(mysqli_error());
$row1 = mysqli_fetch_array($query1);
 $student_name = $row1['student_name']; 
 $s_mobile = $row1['student_contact_no']; 
 $student_email_id = $row1['student_email_id']; 
 
                
$query=mysqli_query($conn,"UPDATE exam_invoice set payment_code='$payment_code',amount='$amount' WHERE invoice_id='$invoice_id'");
  if($query){  
      $s_mobile = substr($s_mobile, 1);
      $s_mobile = "255$s_mobile";
      $message = "Cybercode: Your exam access code is $payment_code. Valid on your exam date only. Don't share it. For help: +255686969536";
      send_message($s_mobile, $message);
       
       echo "<div style='display: none;'>"; 
                    $mail = new PHPMailer(true);

                    try {
                        //Server settings
                        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
                        $mail->isSMTP();                                            //Send using SMTP
                        $mail->Host       = 'mail.cybercode.co.tz';                     //Set the SMTP server to send through
                        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
                        $mail->Username   = 'support@cybercode.co.tz';            //SMTP username
                        $mail->Password   = 'CYBER@support@2024';                   //SMTP password
                        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
                        $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

                        //Recipients
                        $mail->setFrom('support@cybercode.co.tz');
                        $mail->addAddress($student_email_id);

                        //Content
                        $mail->isHTML(true);                                  //Set email format to HTML
                        $mail->Subject = 'Exam Access Code Issued';
                        $mail->Body    = ' 
                        
                        Dear '.$student_name.',<br><br>
                        

                        Your payment has been confirmed. Use the access code below to activate your upcoming examination:<br><br><br>
                        Access Code: '.$payment_code.': Log in to the system and insert it in activate the exam box<br><br>
                        This code is valid for your exam date only and cannot be reused or shared. Ensure you are familiar with our exam policy.<br><br>
                        Best wishes,<br>
                        Cybercode Academy Team<br>
                         
                         ';

			$mail->send();
// 			echo 'Message has been sent';
			} catch (Exception $e) {
			echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
			}
      ?>
      <script type="text/javascript">
          alert("Payment confirmed");
        </script>
        <?php  
      }  
      else{
        ?>  
        <script type="text/javascript">
         alert("Sorry Payment not confirmed Try Again");
        </script>
        <?php
    }
  } 
?>
 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
  <!-- Font Awesome -->
   <link rel="stylesheet" href="../stp_con/fontawesome-free/css/all.min.css">
  <!-- daterange picker -->
  <link rel="stylesheet" href="../stp_con/daterangepicker/daterangepicker.css">
  <!-- iCheck for checkboxes and radio inputs -->
  <link rel="stylesheet" href="../stp_con/icheck-bootstrap/icheck-bootstrap.min.css">
  <!-- Bootstrap Color Picker -->
  <link rel="stylesheet" href="../stp_con/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css">
  <!-- Tempusdominus Bootstrap 4 -->
  <link rel="stylesheet" href="../stp_con/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
  <!-- Select2 -->
  <link rel="stylesheet" href="../stp_con/select2/css/select2.min.css">
  <link rel="stylesheet" href="stp_con/select2-bootstrap4-theme/select2-bootstrap4.min.css">
  <!-- Bootstrap4 Duallistbox -->
  <link rel="stylesheet" href="../stp_con/bootstrap4-duallistbox/bootstrap-duallistbox.min.css">
  <!-- BS Stepper -->
  <link rel="stylesheet" href="../stp_con/bs-stepper/css/bs-stepper.min.css">
  <!-- dropzonejs -->
  <link rel="stylesheet" href="../stp_con/dropzone/min/dropzone.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../assets/css/adminlte.min.css">
   <link rel="stylesheet" type="text/css" href="../stp_con/parsley/parsley.css"/>
</head>
<body class="hold-transition sidebar-mini layout-fixed top-nav">
<!-- Site wrapper -->
<div class="wrapper">
 <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <a><strong>Examination Results</strong></a>
          </div>
           <div class="col-sm-6">
             <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li> 
              <li class="breadcrumb-item active">Trainer Results</li>
            </ol>
          </div>
        </div>
      </div>
    <!-- /.container-fluid -->
    </section>
     <br>
    <!-- Main content -->
     <section class="content">
      <div class="container-fluid">
        <div class="row"> 
          <!-- /.col -->
          <div class="col-md-12">
            <div class="card"> 
              <!-- /.card-header --> 
              <div class="card-body"> 
              <div class="tab-content">
              <!-- /.tab-pane -->
              <div class="active tab-pane" id="teacher">
              <div class="container-fluid">
                <div class="row">
                  <div class="col-sm-12">  
                    <div class="card">  
                            <?php

                            //exam_result.php
                            
                            include('Soes.php');
                            
                            $object = new Soes;
                             
                            if(isset($_GET['ec']))
                            {
                            	$exam_id = $object->Get_exam_id($_GET['ec']);
                            
                            	$object->query = "
                            	SELECT exam_class_id FROM exam_soes 
                            	WHERE exam_id = '".$exam_id."'
                            	";
                            
                            	$exam_data = $object->get_result();
                            
                            	$exam_class_id = '';
                            
                            	foreach($exam_data as $exam_row)
                            	{
                            		$exam_class_id = $exam_row["exam_class_id"];
                            	}
                            
                            	$object->query = "
                            	SELECT student_id, student_roll_no FROM student_to_class_soes 
                            	WHERE class_id = '".$exam_class_id."'
                            	";
                            
                            	$class_data = $object->get_result();
                             ?>
                             <div class="card-header">
                                  <h3 class="card-title">Results List Exam - <?php echo $object->Get_exam_name($exam_id) ?> and  Class of <?php echo $object->Get_class_name($exam_class_id) ?></h3>
                                  <div class="float-right mb-2">
                                    <a href="admin.php?page=view_exam_result&Id_2=<?php echo $ex_id ?>&id_c=<?php echo $class_id ?>" onclick="return confirm('Are you sure! Do you want to Send Result?');" class="btn btn-danger btn-xs float-right ml-2" >
                                        <i class="fa fa-upload"></i> SEND RESULTS <?php echo $exam_id ?> 
                                    </a>
                                    </div>
                                     </div> 
                                     <!-- /.card-header -->
                                      <div class="card-body"> 
                            	 <div class="table-responsive">
                                    <table id="example1" class="table table-striped display table-bordered" >
                                    <thead>  
                                   <tr>
                            			<th>Image</th>
                            			<th>Roll No.</th>
                            			<th>Student Name</th>
                            			<th>Total Marks</th>
                            			<th>Marks Obtain</th>
                            		</tr>
                                    </thead>
                                    <tbody>
                              <?php
                            
                            	foreach($class_data as $class_row)
                            	{
                            		$student_name = '';
                            		$student_profile_img = '';
                            		$student_roll_no = $class_row["student_roll_no"];
                            
                            		$object->query = "
                            		SELECT student_soes.student_name, student_soes.student_image FROM student_soes 
                            		WHERE student_id = '".$class_row["student_id"]."'
                            		";
                            		$student_data = $object->get_result();
                            
                            		foreach($student_data as $student_row)
                            		{
                            			$student_name = $student_row["student_name"];
                            			$student_profile_img = $student_row["student_image"];
                            		}
                            
                            		$object->query = "
                            		SELECT * FROM subject_wise_exam_detail 
                            		INNER JOIN subject_soes 
                            		ON subject_soes.subject_id = subject_wise_exam_detail.subject_id
                            		WHERE subject_wise_exam_detail.exam_id = '$exam_id' 
                            		ORDER BY subject_wise_exam_detail.exam_subject_id ASC
                            		";
                            
                            		$result = $object->get_result();
                            
                            		$total_mark = 0;
                            
                            		$stm = 0;
                            
                            		foreach($result as $row)
                            		{
                            
                            			$subject = $row["subject_name"];
                            
                            			$subject_total_mark = $row["subject_total_question"] * $row["marks_per_right_answer"];
                            
                            			$stm = $stm + $subject_total_mark;
                            
                            			$object->query = "
                            			SELECT SUM(exam_subject_question_answer.marks) AS total FROM exam_subject_question_answer 
                            			INNER JOIN exam_subject_question_soes 
                            			ON exam_subject_question_soes.exam_subject_question_id = exam_subject_question_answer.exam_subject_question_id 
                            			WHERE exam_subject_question_soes.exam_subject_id = '".$row["exam_subject_id"]."' 
                            			AND exam_subject_question_answer.student_id = '".$class_row["student_id"]."'
                            			";
                            
                            			$mark_result = $object->get_result(); 
                            
                            			$subject_mark = 0;
                            
                            			foreach($mark_result as $mark_row)
                            			{
                            				$subject_mark = $mark_row["total"];
                            			}
                            
                            			$total_mark = $total_mark + $subject_mark;
                            		}
                             ?>
                            		<tr> 
                            			<td><img src="../<?php echo $student_profile_img ?>" width="50" /></td> 
                            			<td><?php echo $student_roll_no ?></td>
                            			<td><?php echo $student_name ?></td>
                            			<td><?php echo $stm ?></td>
                            			<td><?php echo $total_mark ?></td>
                            		</tr>
                            		<?php  	
                            	} ?>
                             </tbody>
                                <tfoot>
                                <tr>
                                <th>Image</th>
                                <th>Roll No.</th>
                                <th>Student Name</th>
                                <th>Total Marks</th>
                                <th>Marks Obtain</th>
                                </tr>
                                </tfoot>
                                </table> 
                                </div> 
                            <?php } ?>  
                              
                              
                      
                     </div>
                    </div> <!-- end card body-->
                    </div> <!-- end card --> 
                    </div>
                  <!-- /.card -->
                  </div>
                 </div> 
                </div>
                <!-- /.tab-content -->
             </div><!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
          <!-- /.col -->
        </div>
        <!-- /.row -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  <script src="../stp_con/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="../stp_con/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="../stp_con/select2/js/select2.full.min.js"></script>
<!-- DataTables  & Plugins -->
<script src="../stp_con/datatables/jquery.dataTables.min.js"></script>
<script src="../stp_con/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="../stp_con/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="../stp_con/datatables-responsive/js/responsive.bootstrap4.min.js"></script>
<script src="../stp_con/datatables-buttons/js/dataTables.buttons.min.js"></script>
<script src="../stp_con/datatables-buttons/js/buttons.bootstrap4.min.js"></script>
<script src="../stp_con/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<script src="../stp_con/jszip/jszip.min.js"></script>
<script src="../stp_con/pdfmake/pdfmake.min.js"></script>
<script src="../stp_con/pdfmake/vfs_fonts.js"></script>  
<script src="../stp_con/datatables-buttons/js/buttons.html5.min.js"></script>
<script src="../stp_con/datatables-buttons/js/buttons.print.min.js"></script>
<script src="../stp_con/datatables-buttons/js/buttons.colVis.min.js"></script>
<script src="../stp_con/summernote/summernote-bs4.min.js"></script>  
<script src="../assets/js/adminlte.min.js"></script>   
 
 <script>
  $(function () {
    $("#example1").DataTable({
      "responsive": true, "lengthChange": false, "autoWidth": false,
      "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
    }).buttons().container().appendTo('#example1_wrapper .col-md-6:eq(0)'); 
  });
</script> 

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

    //Initialize Select2 Elements
    $('.select2bs4').select2({
      theme: 'bootstrap4'
    })

    //Datemask dd/mm/yyyy
    $('#datemask').inputmask('dd/mm/yyyy', { 'placeholder': 'dd/mm/yyyy' })
    //Datemask2 mm/dd/yyyy
    $('#datemask2').inputmask('mm/dd/yyyy', { 'placeholder': 'mm/dd/yyyy' })
    //Money Euro
    $('[data-mask]').inputmask()

    //Date picker
    $('#reservationdate').datetimepicker({
        format: 'L'
    }); 
    //Date range picker
    $('#reservation').daterangepicker()
    //Date range picker with time picker
    $('#reservationtime').daterangepicker({
      timePicker: true,
      timePickerIncrement: 30,
      locale: {
        format: 'MM/DD/YYYY hh:mm A'
      }
    })
    //Date range as a button
    $('#daterange-btn').daterangepicker(
      {
        ranges   : {
          'Today'       : [moment(), moment()],
          'Yesterday'   : [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
          'Last 7 Days' : [moment().subtract(6, 'days'), moment()],
          'Last 30 Days': [moment().subtract(29, 'days'), moment()],
          'This Month'  : [moment().startOf('month'), moment().endOf('month')],
          'Last Month'  : [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
        },
        startDate: moment().subtract(29, 'days'),
        endDate  : moment()
      },
      function (start, end) {
        $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'))
      }
    )

    //Timepicker
    $('#timepicker').datetimepicker({
      format: 'LT'
    })

    //Bootstrap Duallistbox
    $('.duallistbox').bootstrapDualListbox()

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

    $('.my-colorpicker2').on('colorpickerChange', function(event) {
      $('.my-colorpicker2 .fa-square').css('color', event.color.toString());
    })
  })
  // BS-Stepper Init
  document.addEventListener('DOMContentLoaded', function () {
    window.stepper = new Stepper(document.querySelector('.bs-stepper'))
  })

  // DropzoneJS Demo Code Start
  Dropzone.autoDiscover = false

  // Get the template HTML and remove it from the doumenthe template HTML and remove it from the doument
  var previewNode = document.querySelector("#template")
  previewNode.id = ""
  var previewTemplate = previewNode.parentNode.innerHTML
  previewNode.parentNode.removeChild(previewNode)

  var myDropzone = new Dropzone(document.body, { // Make the whole body a dropzone
    url: "/target-url", // Set the url
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    parallelUploads: 20,
    previewTemplate: previewTemplate,
    autoQueue: false, // Make sure the files aren't queued until manually added
    previewsContainer: "#previews", // Define the container to display the previews
    clickable: ".fileinput-button" // Define the element that should be used as click trigger to select files.
  })

  myDropzone.on("addedfile", function(file) {
    // Hookup the start button
    file.previewElement.querySelector(".start").onclick = function() { myDropzone.enqueueFile(file) }
  })

  // Update the total progress bar
  myDropzone.on("totaluploadprogress", function(progress) {
    document.querySelector("#total-progress .progress-bar").style.width = progress + "%"
  })

  myDropzone.on("sending", function(file) {
    // Show the total progress bar when upload starts
    document.querySelector("#total-progress").style.opacity = "1"
    // And disable the start button
    file.previewElement.querySelector(".start").setAttribute("disabled", "disabled")
  })


    $('.toastrDefaultSuccess').click(function() {
      toastr.success('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
    });
    $('.toastrDefaultInfo').click(function() {
      toastr.info('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
    });
    $('.toastrDefaultError').click(function() {
      toastr.error('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
    });
    $('.toastrDefaultWarning').click(function() {
      toastr.warning('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.')
    });

  // Hide the total progress bar when nothing's uploading anymore
  myDropzone.on("queuecomplete", function(progress) {
    document.querySelector("#total-progress").style.opacity = "0"
  })

  // Setup the buttons for all transfers
  // The "add files" button doesn't need to be setup because the config
  // `clickable` has already been specified.
  document.querySelector("#actions .start").onclick = function() {
    myDropzone.enqueueFiles(myDropzone.getFilesWithStatus(Dropzone.ADDED))
  }
  document.querySelector("#actions .cancel").onclick = function() {
    myDropzone.removeAllFiles(true)
  }
  // DropzoneJS Demo Code End
  </script>
<script>
$(document).ready(function(){
    $('#login_form').parsley();
     $('#login_form2').parsley();
     $('#login_form3').parsley();
     $('#login_form4').parsley();
     $('#login_form5').parsley();
     $('#login_form6').parsley(); 
});

</script>

