<?php
 session_start();
require_once('operations.php');

require_once 'phpword/Autoloader.php';
\PhpOffice\PhpWord\Autoloader::register();
use PhpOffice\PhpWord\IOFactory;


$db = new Operations();
$db1 = new Operations();

if (!isset($_SESSION['user'])) {
   header( "Location: index.php" );
}

$month = date("n");
$year = date("Y");

if($month == 19 || $month == 10 || $month == 11 || $month == 12){

$session1 = $year . "/". ($year + 1);
$term1 = "First";
//$term1 = "Third";
}


else if($month == 1 || $month == 2 || $month == 3 || $month == 4){
$session1 = ($year-1)."/".$year;
$term1 = "Second";

//$term1 = "First";
}

else if($month == 5 || $month == 6 || $month == 7 || $month == 9){
$session1 = ($year-1)."/".$year;
$term1 = "Third";
//$term1 = "Second";
//$term1 = "First";
}	

if(isset($_GET['examcode']) && ($_GET['subject_id']) ) {
  $param =  $_GET['examcode'];
  $param2 = $_GET['subject_id'];
  
  $questionEntered = $db1->getCountQuestionsByExamID($param);
  
  $db1->findSubjectById($param2);

  $db->findExamsById($param);
  
  // $db2->
  
  
  }

$noOFQuestions = $db->questions;

if(isset($_POST['submit'])) {

    if($questionEntered >= $noOFQuestions) {

        ?>
<script>
    alert('you have exceeded total no of questions');
    </script>

<?php
    }
else {
    
    

   /* 

 // $examcode = $code1;
  $question = ltrim($_POST['question']);
   $optionA =  ltrim($_POST['optionA']);
   $optionB =  ltrim($_POST['optionB']);
   $optionC =  ltrim($_POST['optionC']);
   $optionD =  ltrim($_POST['optionD']);
   $answer = strtoupper($_POST['answer']);
  // $questions = $_POST['questions'];
  // $total = $_POST['total'];

  // $time1 = $date." ".$time;

 */
 

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        die("Error: No file uploaded or an upload error occurred.");
    }

    $file = $_FILES['file']['tmp_name'];
    /*
    $fileExt = pathinfo($filename, PATHINFO_EXTENSION);
    if (strtolower($fileExt) !== 'docx') {
        ?>
        
        <script>
            alert('only .docx - microsoft word document allowed ');
              window.location.href='uploadFromWord.php';
        </script>
        
        <?php
    }
    */
    
    // new codes
    
     $phpWord = IOFactory::load($file);
    $text = '';

    foreach ($phpWord->getSections() as $section) {
        foreach ($section->getElements() as $element) {
            if (method_exists($element, 'getText')) {
                $text .= $element->getText() . "\n";
            }
        }
    }

    $lines = explode("\n", trim($text));
   
   
    $question = "";
    $options = [];
    $answer = "";
    
    
    //new codes
    
    
    // new codes
    
     foreach ($lines as $line) {
        $line = trim($line);

        if (empty($line)) continue;

        if (strpos($line, 'Answer:') === 0) {
            $answer = trim(str_replace('Answer:', '', $line));

         
     
     $db->addQuestions($param2,$question,$options['A'], $options['B'], $options['C'], $options['D'], $answer,$param);
     
     //new codes
     
     // nw codes
     
     
            $question = "";
            $options = [];
            $answer = "";
        } elseif (preg_match('/^[A-D]\)/', $line)) {
            $parts = explode(')', $line);
            $options[trim($parts[0])] = trim($parts[1]);
        } else {
            $question = $line;
        }
    }
    
    
    
     
    //new codes
    
    ?>
    
    <script>
        alert('upload successful')
    </script>
    
    <?php
 	
  

 }
  
    
   

 



} 


?>
<!--
=========================================================
* Argon Dashboard - v1.2.0
=========================================================
* Product Page: https://www.creative-tim.com/product/argon-dashboard


* Copyright  Creative Tim (http://www.creative-tim.com)
* Coded by www.creative-tim.com



=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-->
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Start your development with a Dashboard for Bootstrap 4.">
  <meta name="author" content="Creative Tim">
  <title>Exam App</title>
  <!-- Favicon 
  <link rel="icon" href="assets/img/brand/favicon.png" type="image/png">
  -->
  <!-- Fonts -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
  <!-- Icons -->
  <link rel="stylesheet" href="assets/vendor/nucleo/css/nucleo.css" type="text/css">
  <link rel="stylesheet" href="assets/vendor/@fortawesome/fontawesome-free/css/all.min.css" type="text/css">
  <!-- Page plugins -->
  <!-- Argon CSS -->
  <link rel="stylesheet" href="assets/css/argon.css?v=1.2.0" type="text/css">
  <link href="summernote-bs4.css" rel="stylesheet">
  <!-- date picker -->

  
  

  


  <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
         
         <style>
       
        .upload-card {
            max-width: 500px;
            margin: 50px auto;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
        }
    </style>

</head>

<body>
  <!-- Sidenav -->
  <nav class="sidenav navbar navbar-vertical  fixed-left  navbar-expand-xs navbar-light bg-white" id="sidenav-main">
    <div class="scrollbar-inner">
      <!-- Brand -->
      <div class="sidenav-header  align-items-center">
        <a class="navbar-brand" href="javascript:void(0)">
          <h4>Exam App</h4>
        </a>
      </div>
      <div class="navbar-inner">
        <!-- Collapse -->
        <div class="collapse navbar-collapse" id="sidenav-collapse-main">
          <!-- Nav items -->
          <?php include('staffmenu.html')  ?>
          <!-- Divider -->
          <hr class="my-3">
          <!-- Heading -->
          
        </div>
      </div>
    </div>
  </nav>
  <!-- Main content -->
  <div class="main-content" id="panel">
    <!-- Topnav -->
    <nav class="navbar navbar-top navbar-expand navbar-dark bg-primary border-bottom">
      <div class="container-fluid">
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <!-- Search form -->
          <form class="navbar-search navbar-search-light form-inline mr-sm-3" id="navbar-search-main">
            <div class="form-group mb-0">
              <div class="input-group input-group-alternative input-group-merge">
                <div class="input-group-prepend">
                  <span class="input-group-text"><i class="fas fa-search"></i></span>
                </div>
                <input class="form-control" placeholder="Search" type="text">
              </div>
            </div>
            <button type="button" class="close" data-action="search-close" data-target="#navbar-search-main" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </form>
          <!-- Navbar links -->
          
          
        </div>
      </div>
    </nav>
    <!-- Header -->
    <!-- Header -->
    <div class="header bg-primary pb-6">
      <div class="container-fluid">
        <div class="header-body">
          <div class="row align-items-center py-4">
            
          
          </div>
          <!-- Card stats -->
         
          <!-- put content  -->




         



          <div class="container-fluid mt--6">
      
       
      <div class="row">
        <div class="col-xl-10">
          <div class="card">
            <div class="card-header border-0">
              <div class="row align-items-center">
                <div class="col">
                  <h3 class="mb-0">Add Questions For  <?php  echo $db1->title ." Class: ".$db->class; ?></h3>
                  <h3 class="mb-0"> 
                  <a href="" class="btn btn-primary ">UPLOAD FROM FILE</a>
                   </h3>
                </div>
                <div class="col text-right">
                  
                </div>
              </div>
            </div>
            <div class="table-responsive">
              <!-- Projects table -->
              <div class="card-body">
              
              <!--  
              
              Add file upload here
              
              -->
             
               <h4>Your questions should be in this format(file should contain 15 questions at once)</h4> 
           <img src="cbtformat.PNG" alt="Upload Icon" class="placeholder-img">     
             
         <form method="post" enctype="multipart/form-data">
                <!-- File Input -->
                <div class="mb-3">
                    <label for="file" class="form-label">Select File</label>
                    <input type="file" class="form-control" name="file" id="file" required>
                </div>
                
                <!-- Submit Button -->
                <div class="d-grid">
                    <button type="submit" name="submit" class="btn btn-primary">
                        <i class="bi bi-upload"></i> Upload
                    </button>
                </div>
            </form>

                  



                  
              <!-- end -->
            </div>
          </div>
        </div>
        
            </div>
          </div>
        </div>
      </div>


          <!-- put content --->
          
        </div>
      </div>
    </div>
    <!-- Page content -->
    <div class="container-fluid mt--6">
    
       
      
        </div>
      </div>
      <!-- Footer -->
      <footer class="footer pt-0">
        <div class="row align-items-center justify-content-lg-between">
          <div class="col-lg-6">
            
          </div>
          <div class="col-lg-6">
            
          </div>
        </div>
      </footer>
    </div>
  </div>
  <!-- Argon Scripts -->
  <!-- Core -->

   <script src="assets/vendor/jquery/dist/jquery.min.js"></script> 
  <script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/js-cookie/js.cookie.js"></script>
  <script src="assets/vendor/jquery.scrollbar/jquery.scrollbar.min.js"></script>
  <script src="assets/vendor/jquery-scroll-lock/dist/jquery-scrollLock.min.js"></script>
  <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

  <script src ="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>  

<script src ="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>  

<!--  summernote -->

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="summernote-bs4.js"></script>
<!-- -->
  <!-- Optional JS -->
  <script src="assets/vendor/chart.js/dist/Chart.min.js"></script>
  <script src="assets/vendor/chart.js/dist/Chart.extension.js"></script>
  <!-- Argon JS -->
  <script src="js/argon.js?v=1.2.0"></script>

  <script>
    // WRITE THE VALIDATION SCRIPT.
    function isNumber(evt) {
        var iKeyCode = (evt.which) ? evt.which : evt.keyCode
        if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57))
            return false;

        return true;
    }    
</script>

<script>
         $(function() {
			  
            $( "#datepicker-13" ).datepicker(
			{dateFormat: 'yy-mm-dd',minDate:0}).datepicker("setDate", new Date());
           
			
			
         });
      </script>


<script>
$('#summernote').summernote(
{
        placeholder: 'enter your questions here, you can paste from Microsoft word',
        tabsize: 2,
        height: 300,
		width:  600,
		toolbar: [
          ['style', ['style']],
          ['font', ['bold', 'underline', 'clear']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['table', ['table']],
          ['insert', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'help']]
        ]
      });
	  
	  
	  $('#summernote1').summernote(
{
        placeholder: 'enter option',
        tabsize: 2,
        height: 100,
		width:  600
      });
	  
	   $('#summernote2').summernote(
{
        placeholder: 'enter your option',
        tabsize: 2,
        height: 100,
		width:  600
      });
	  
	   $('#summernote3').summernote(
{
        placeholder: 'enter your option',
        tabsize: 2,
        height: 100,
		width:  600
      });
	  
	   $('#summernote4').summernote(
{
        placeholder: 'enter your option',
        tabsize: 2,
        height: 100,
		width:  600
      });
	  
	   $('#summernote5').summernote(
{
        placeholder: 'enter your answer',
        tabsize: 2,
        height: 100,
		width:  600
      });
</script>

</body>

</html>