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

$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";
} elseif($month == 1 || $month == 2 || $month == 3 || $month == 4){
    $session1 = ($year-1)."/".$year;
    $term1 = "Second";
} else {
    $session1 = ($year-1)."/".$year;
    $term1 = "Third";
}

if(isset($_GET['examcode']) && isset($_GET['subject_id'])) {
    $param =  $_GET['examcode'];
    $param2 = $_GET['subject_id'];

    $questionEntered = $db1->getCountQuestionsByExamID($param);
    $db1->findSubjectById($param2);
    $db->findExamsById($param);
}

$noOFQuestions = $db->questions;



?>

<!--
=========================================================
* 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">
                    <?php

                    if(isset($_POST['submit'])) {
      if ($questionEntered >= $noOFQuestions) {
          echo "<script>alert('You have exceeded total number of questions');</script>";
      } else {
          if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
              die("Error: No file uploaded or an upload error occurred.");
          }

          $fileTmp = $_FILES['file']['tmp_name'];
          $fileName = $_FILES['file']['name'];
          $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

          if (!in_array($fileExt, ['htm', 'html'])) {
              echo "<script>alert('Only .html or .htm files allowed.');</script>";
              return;
          }

          libxml_use_internal_errors(true);
          $doc = new DOMDocument();
          $doc->loadHTMLFile($fileTmp);

          $paragraphs = $doc->getElementsByTagName('p');

          $question = "";
          $options = [];
          $answer = "";
          $qCount = 0;
          $skipped = [];
          $questionNumber = 1;

          foreach ($paragraphs as $p) {
              // inner HTML of <p>
              $innerHtml = '';
              foreach ($p->childNodes as $child) {
                  $innerHtml .= $doc->saveHTML($child);
              }

              // Normalize
              $innerHtml = preg_replace('/<o:p>.*?<\/o:p>/is', '', $innerHtml);
              $innerHtml = str_replace("\xC2\xA0", ' ', $innerHtml);
              $innerHtml = preg_replace('/[\x00-\x1F\x7F]/u', '', $innerHtml);

              // If <br> inside <p>, split into logical lines
              if (preg_match('/<br\b/i', $innerHtml)) {
                  $parts = preg_split('/<br[^>]*>/i', $innerHtml);
                  foreach ($parts as $part) {
                      $plain = trim(strip_tags($part));
                      if ($plain === '') continue;

                      // Answer line
                      if (preg_match('/^\s*answer\s*[:\-]?\s*([A-D])\b/i', $plain, $m)) {
                          $answer = strtoupper($m[1]);
                      }
                      // Options
                      elseif (preg_match('/^\s*([A-D])\)\s*(.+)$/i', $plain, $m)) {
                          $key = strtoupper($m[1]);
                          $options[$key] = trim($m[2]);
                      }
                      // Question text
                      else {
                          // Finalize previous Q if one is pending
                          if (!empty($answer) || !empty($options)) {
                              if (!empty($question) && count($options) === 4 && in_array($answer, ['A','B','C','D'])) {
                                  $db->addQuestions($param2, trim($question), $options['A'], $options['B'], $options['C'], $options['D'], $answer, $param);
                                  $qCount++;
                              } else {
                                  $reason = [];
                                  if (empty($question)) $reason[] = "Empty question";
                                  if (count($options) < 4) $reason[] = "Missing options (found " . count($options) . ")";
                                  if (!in_array($answer, ['A','B','C','D'])) $reason[] = "Invalid answer: $answer";
                                  $skipped[] = "Question $questionNumber skipped: " . implode(', ', $reason);
                              }
                              $questionNumber++;
                              $question = "";
                              $options = [];
                              $answer = "";
                          }
                          $question .= strip_tags($plain) . " ";
                      }
                  }

                  // finalize if answer present
                  if (!empty($question) && count($options) === 4 && in_array($answer, ['A','B','C','D'])) {
                      $db->addQuestions($param2, trim($question), $options['A'], $options['B'], $options['C'], $options['D'], $answer, $param);
                      $qCount++;
                      $questionNumber++;
                      $question = "";
                      $options = [];
                      $answer = "";
                  }
                  continue; // go to next <p>
              }

              // No <br>, use old logic
              $plainText = trim($p->textContent);
              if ($plainText === '') continue;

              // Answer
              if (preg_match('/^\s*answer\s*[:\-]?\s*([A-D])\b/i', $plainText, $m)) {
                  $answer = strtoupper($m[1]);
                  if (!empty($question) && count($options) === 4 && in_array($answer, ['A','B','C','D'])) {
                      $db->addQuestions($param2, trim($question), $options['A'], $options['B'], $options['C'], $options['D'], $answer, $param);
                      $qCount++;
                  } else {
                      $reason = [];
                      if (empty($question)) $reason[] = "Empty question";
                      if (count($options) < 4) $reason[] = "Missing options (found " . count($options) . ")";
                      if (!in_array($answer, ['A','B','C','D'])) $reason[] = "Invalid answer: $answer";
                      $skipped[] = "Question $questionNumber skipped: " . implode(', ', $reason);
                  }
                  $question = "";
                  $options = [];
                  $answer = "";
                  $questionNumber++;
                  continue;
              }

              // Options
              if (preg_match('/^\s*([A-D])\)\s*(.+)$/i', $plainText, $matches)) {
                  $key = strtoupper(trim($matches[1]));
                  $options[$key] = trim($matches[2]);
                  continue;
              }

              // Question text
              $question .= strip_tags($plainText) . " ";
          }

          // Final check
          if (!empty($question) && count($options) === 4 && in_array($answer, ['A','B','C','D'])) {
              $db->addQuestions($param2, trim($question), $options['A'], $options['B'], $options['C'], $options['D'], $answer, $param);
              $qCount++;
          } elseif (!empty($question) && (!empty($options) || !empty($answer))) {
              $reason = [];
              if (empty($question)) $reason[] = "Empty question";
              if (count($options) < 4) $reason[] = "Missing options (found " . count($options) . ")";
              if (!in_array($answer, ['A','B','C','D'])) $reason[] = "Invalid answer: $answer";
              $skipped[] = "Question $questionNumber skipped: " . implode(', ', $reason);
          }

          // Show summary
          if (!empty($skipped)) {
              echo "<h4>Upload Summary</h4>";
              echo "<p>Uploaded successfully: <strong>$qCount</strong></p>";
              echo "<p>Skipped: <strong>" . count($skipped) . "</strong></p>";
              echo "<ul style='color:red'>";
              foreach ($skipped as $msg) {
                  echo "<li>$msg</li>";
              }
              echo "</ul>";
          } else {
              echo "<script>alert('Upload successful! Total: $qCount questions');</script>";
          }
      }
  }
  ?>

                    
                  <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>Convert your questions to web page using MS WORD(click on file -> save as -> give it a name, on save as type select web page then click save </h4> 
               <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>