<?php
session_start();

$ic = $_SESSION["ic"];

if(isset($_SESSION["name"])){
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">

  <title>KVS DIGITAL - E-VOTING SYSTEM</title>
  <meta content="" name="description">
  <meta content="" name="keywords">

  <!-- Favicons -->
  <link href="assets/img/kvs.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i|Raleway:300,300i,400,400i,500,500i,600,600i,700,700i|Poppins:300,300i,400,400i,500,500i,600,600i,700,700i" rel="stylesheet">

  <!-- Vendor CSS Files -->
 	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/icofont/icofont.min.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
  <link href="assets/vendor/venobox/venobox.css" rel="stylesheet">
  <link href="assets/vendor/aos/aos.css" rel="stylesheet">

  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <script type = "text/javascript" >
  history.pushState(null, null, 'index.html');
 window.addEventListener('popstate', function(event) {
  history.pushState(null, null, 'index.html');
    });

</script>
</head>
<body>

<!-- ======= Header ======= -->
  <header id="header" class="fixed-top  header-transparent ">
    <div class="container d-flex align-items-center">
      
      <div class="logo mr-auto">      
        
        <!-- Uncomment below if you prefer to use an image logo -->
        <a class="navbar-brand" href="#"></a>
          <h1 class="text-light"><a href="index.html">KVS DIGITAL E- VOTING</a></h1>
        </a>
      </div>

      <nav class="nav-menu d-none d-lg-block">
        
        <ul>
          <li class="active"><a href="index.php">Home</a></li>
          <li><a href="#features">Tatacara</a></li>
          <li><a href="#features">JOM UNDI</a></li>
          <li><a href="profile.php">Profil Calon</a></li>
          <li><a href="#" data-target="#loginModal" data-toggle="modal">ADMIN</a></li>
         <li class="get-started"><a href="logout.php">LOGOUT</a></li>
         
        </ul>
      </nav><!-- .nav-menu -->
 
    </div>
  </header><!-- End Header -->
<br><br><br><hr>
 <div class="container">
<?php
include 'dbconn.php';

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

//<!-- <form name="undisijil" action="undian3a.php" method="post"> -->

// Loop to store and display values of individual checked checkbox.
$selected = isset($_POST["check"]) ? $_POST["check"] : array();
$selected = array_map('intval', $selected);
$selected = array_values(array_unique($selected));
$N = count($selected);

if ($N !== 28) {
  if ($N < 28) {
    $baki = 28 - $N;
    echo "<div class='alert alert-danger mt-4'>Undian belum mencukupi. Sila tambah $baki lagi calon untuk cukup 28 undian.</div>";
  } else {
    $lebihan = $N - 28;
    echo "<div class='alert alert-danger mt-4'>Undian melebihi had. Sila buang $lebihan pilihan untuk kekal pada 28 undian.</div>";
  }
  echo "<a class='btn btn-primary mt-3' href='profilpelajar.php'>Kembali ke Profil Pelajar</a>";
  exit;
}
echo "<h4>Calon MPP Pilihan anda</h4><br><br>";

mysqli_begin_transaction($conn);

try {
  for($i=0; $i < $N; $i++) {
    $id = $selected[$i];
    $votecast = "SELECT candName FROM tblcandidate WHERE candID='$id' LIMIT 1";
    $cast = mysqli_query($conn, $votecast);

    if (!$cast || mysqli_num_rows($cast) === 0) {
      throw new Exception("Calon tidak dijumpai.");
    }

    $row = mysqli_fetch_assoc($cast);
    echo htmlspecialchars($row["candName"]) . "<br>";

    $sq1 = "UPDATE tblcandidate SET voteCount = COALESCE(voteCount, 0) + 1 WHERE candID='$id'";
    if (!mysqli_query($conn, $sq1) || mysqli_affected_rows($conn) !== 1) {
      throw new Exception("Kemaskini voteCount gagal.");
    }
  }

  $sq = "UPDATE tblstudent SET voteStatus='1' WHERE studentIC='" . mysqli_real_escape_string($conn, $ic) . "'";
  if (!mysqli_query($conn, $sq)) {
    throw new Exception("Kemaskini voteStatus gagal.");
  }

  mysqli_commit($conn);
} catch (Exception $e) {
  mysqli_rollback($conn);
  echo "<div class='alert alert-danger mt-4'>Undian gagal diproses. Sila cuba semula.</div>";
  echo "<a class='btn btn-primary mt-3' href='profilpelajar.php'>Kembali ke Profil Pelajar</a>";
  exit;
}
}
echo "<br><br><h5>Terima kasih kerana menggunakan kvsdigital Voting System</h5><br><br>";
session_destroy();
}else{
     header("Location: ../index.php?error= You are not logged in");
     //echo "yoouu";
} 
?>

</div>

<br><br><br><hr>
  <!-- ======= Footer ======= -->
  <footer id="footer">
    <div class="container py-4">
      <div class="copyright">
        &copy; Copyright 2021 <strong><span> kvsdigital.my </span></strong>. All Rights Reserved
      </div>
      <div class="credits">
        Designed by Bootstrap 
      </div>
    </div>
  </footer><!-- End Footer -->

</body>
</html>
