<?php
session_start();
include 'dbconn.php';

$limitVote = 28;
$errorMessage = '';
$studentName = '';
$studentIC = '';
$showVoting = false;

if (isset($_GET['error'])) {
  $errorMessage = $_GET['error'];
}

if (isset($_POST['studentIC'])) {
  $studentIC = trim($_POST['studentIC']);

  if ($studentIC === '') {
    $errorMessage = 'Sila masukkan nombor kad pengenalan.';
  } else {
    $safeStudentIC = mysqli_real_escape_string($conn, $studentIC);
    $studentSql = "SELECT studentName, studentIC, voteStatus FROM tblstudent WHERE studentIC = '$safeStudentIC' LIMIT 1";
    $studentResult = mysqli_query($conn, $studentSql);

    if ($studentResult && mysqli_num_rows($studentResult) > 0) {
      $studentRow = mysqli_fetch_assoc($studentResult);

      if ((int)$studentRow['voteStatus'] === 1) {
        $errorMessage = 'Anda hanya boleh mengundi sekali sahaja.';
      } else {
        $_SESSION["name"] = $studentRow["studentName"];
        $_SESSION["ic"] = $studentRow["studentIC"];
        $studentName = $studentRow["studentName"];
        $studentIC = $studentRow["studentIC"];
        $showVoting = true;
      }
    } else {
      $errorMessage = 'No kad pengenalan tidak dijumpai.';
    }
  }
}

if (isset($_SESSION["name"]) && isset($_SESSION["ic"]) && !$showVoting) {
  $studentName = $_SESSION["name"];
  $studentIC = $_SESSION["ic"];
  $showVoting = true;
}

$sql = "SELECT candID, image, candN, candName, candCourse, motto AS moto FROM tblcandidate ORDER BY candN ASC";
$result = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <title>Profil Pelajar - KVS Digital E-Voting</title>
  <link href="assets/img/kvs.png" rel="icon">
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <style>
    body {
      background: linear-gradient(135deg, #f4f8ff 0%, #edf7f0 100%);
      font-family: "Poppins", sans-serif;
      min-height: 100vh;
    }

    .profile-header {
      background: linear-gradient(120deg, #0f6bff, #00a7a2);
      color: #fff;
      border-radius: 18px;
      box-shadow: 0 10px 30px rgba(15, 107, 255, 0.2);
    }

    .search-box,
    .ic-input {
      border: none;
      border-radius: 50px;
      padding: 12px 18px;
      box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    }

    .course-filter {
      border-radius: 50px;
      border: none;
      padding: 12px 16px;
      box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
    }

    .profile-card {
      border: none;
      border-radius: 18px;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
      transition: transform 0.25s ease, box-shadow 0.25s ease;
      cursor: pointer;
      height: 100%;
    }

    .profile-card:hover {
      transform: translateY(-6px) scale(1.01);
      box-shadow: 0 16px 28px rgba(15, 107, 255, 0.22);
    }

    .profile-image-wrap {
      height: 220px;
      background: #dbe8ff;
      overflow: hidden;
      position: relative;
    }

    .profile-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
      transition: transform 0.35s ease;
    }

    .profile-card:hover .profile-image {
      transform: scale(1.08);
    }

    .cand-badge {
      font-size: 0.8rem;
      letter-spacing: 0.5px;
      background: rgba(15, 107, 255, 0.1);
      color: #0f6bff;
      border-radius: 999px;
      padding: 5px 12px;
      font-weight: 600;
    }

    .moto-text {
      color: #495057;
      font-style: italic;
      min-height: 48px;
    }

    .empty-state {
      display: none;
      background: #fff;
      border-radius: 14px;
      padding: 28px;
      text-align: center;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.07);
    }

    .vote-check {
      transform: scale(1.3);
      margin-right: 8px;
    }
  </style>
</head>
<body>
  <div class="container py-4 py-md-5">
    <div class="profile-header p-4 p-md-5 mb-4">
      <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between">
        <div>
          <h1 class="h3 mb-2">Paparan Profil Pelajar</h1>
          <p class="mb-0">Masukkan IC, semak profil calon dan pilih tepat <?php echo $limitVote; ?> undian.</p>
        </div>
        <a href="index.php" class="btn btn-light mt-3 mt-md-0">
          <i class='bx bx-left-arrow-alt'></i> Kembali ke Utama
        </a>
      </div>
    </div>

    <?php if (!$showVoting) { ?>
      <div class="row justify-content-center">
        <div class="col-md-7 col-lg-6">
          <div class="card border-0 shadow-sm" style="border-radius: 16px;">
            <div class="card-body p-4">
              <h5 class="mb-3">Pengesahan Pengundi</h5>
              <p class="text-muted mb-3">Sila masukkan nombor IC untuk memulakan proses undian.</p>
              <?php if ($errorMessage !== '') { ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($errorMessage); ?></div>
              <?php } ?>
              <form action="profilpelajar.php" method="post">
                <div class="form-group">
                  <input type="text" name="studentIC" class="form-control ic-input" placeholder="Contoh: 010203040506" required>
                </div>
                <button type="submit" class="btn btn-primary btn-block mt-3">Teruskan ke Undian</button>
              </form>
            </div>
          </div>
        </div>
      </div>
    <?php } else { ?>
    <div class="alert alert-info">
      Pengundi: <strong><?php echo htmlspecialchars($studentName); ?></strong> (<?php echo htmlspecialchars($studentIC); ?>).
      Pilih tepat <strong><?php echo $limitVote; ?> calon</strong> sebelum hantar undian.
    </div>

    <form name="voteForm" action="undiantest.php" method="post" onsubmit="return validateVoting()">
    <div class="row g-3 mb-4">
      <div class="col-md-8 mb-2 mb-md-0">
        <input type="text" class="form-control search-box" id="searchInput" placeholder="Cari berdasarkan candN, candName atau moto...">
      </div>
      <div class="col-md-4">
        <select class="form-control course-filter" id="courseFilter">
          <option value="">Semua Kelas</option>
          <?php
          $courseSql = "SELECT DISTINCT candCourse FROM tblcandidate ORDER BY candCourse ASC";
          $courseResult = mysqli_query($conn, $courseSql);
          if ($courseResult) {
            while ($course = mysqli_fetch_assoc($courseResult)) {
              echo '<option value="' . htmlspecialchars($course['candCourse']) . '">' . htmlspecialchars($course['candCourse']) . '</option>';
            }
          }
          ?>
        </select>
      </div>
    </div>

    <div class="row" id="candidateList">
      <?php if ($result && mysqli_num_rows($result) > 0) { ?>
        <?php while ($row = mysqli_fetch_assoc($result)) { ?>
          <div class="col-sm-6 col-lg-4 col-xl-3 mb-4 candidate-item"
               data-name="<?php echo strtolower(htmlspecialchars($row['candName'])); ?>"
               data-nick="<?php echo strtolower(htmlspecialchars($row['candN'])); ?>"
               data-course="<?php echo strtolower(htmlspecialchars($row['candCourse'])); ?>"
               data-moto="<?php echo strtolower(htmlspecialchars($row['moto'])); ?>">
            <div class="card profile-card"
                 data-toggle="modal"
                 data-target="#profileModal"
                 data-image="<?php echo htmlspecialchars($row['image']); ?>"
                 data-candn="<?php echo htmlspecialchars($row['candN']); ?>"
                 data-candname="<?php echo htmlspecialchars($row['candName']); ?>"
                 data-candcourse="<?php echo htmlspecialchars($row['candCourse']); ?>"
                 data-moto="<?php echo htmlspecialchars($row['moto']); ?>">
              <div class="profile-image-wrap">
                <img src="<?php echo htmlspecialchars($row['image']); ?>" class="profile-image" alt="Gambar calon">
              </div>
              <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-2">
                  <span class="cand-badge"><?php echo htmlspecialchars($row['candN']); ?></span>
                  <small class="text-muted"><?php echo htmlspecialchars($row['candCourse']); ?></small>
                </div>
                <h5 class="card-title mb-1"><?php echo htmlspecialchars($row['candName']); ?></h5>
                <p class="moto-text mb-0">"<?php echo htmlspecialchars($row['moto']); ?>"</p>
                <div class="mt-3">
                  <input type="checkbox"
                         class="vote-check"
                         id="cand<?php echo (int)$row['candID']; ?>"
                         name="check[]"
                         value="<?php echo (int)$row['candID']; ?>"
                         onclick="limitCheckboxes(this, <?php echo $limitVote; ?>)">
                  <label for="cand<?php echo (int)$row['candID']; ?>" class="mb-0">Pilih calon ini</label>
                </div>
              </div>
            </div>
          </div>
        <?php } ?>
      <?php } ?>
    </div>

    <div id="emptyState" class="empty-state mt-3">
      <h5 class="mb-2">Tiada profil dijumpai</h5>
      <p class="mb-0">Cuba kata kunci atau pilihan kelas yang lain.</p>
    </div>
      <div class="text-center mt-4">
        <button type="submit" name="submit1" class="btn btn-success btn-lg">Hantar Undian</button>
      </div>
    </form>
    <?php } ?>
  </div>

  <!-- <div class="modal fade" id="profileModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content border-0" style="border-radius: 18px;">
        <div class="modal-body p-0">
          <img id="modalImage" src="" alt="Gambar calon" style="width:100%;height:300px;object-fit:cover;border-radius:18px 18px 0 0;">
          <div class="p-4">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <h4 id="modalCandN" class="mb-0"></h4>
              <span id="modalCourse" class="badge badge-info"></span>
            </div>
            <h5 id="modalName" class="mb-3 text-dark"></h5>
            <p class="mb-0 text-secondary"><strong>Moto:</strong> <span id="modalMoto"></span></p>
          </div>
        </div>
      </div>
    </div>
  </div> -->

  <script src="assets/vendor/jquery/jquery.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script>
    (function () {
      var searchInput = document.getElementById("searchInput");
      var courseFilter = document.getElementById("courseFilter");
      var items = document.querySelectorAll(".candidate-item");
      var emptyState = document.getElementById("emptyState");
      var voteLimit = <?php echo $limitVote; ?>;

      function filterCandidates() {
        var keyword = searchInput.value.toLowerCase().trim();
        var selectedCourse = courseFilter.value.toLowerCase().trim();
        var visibleCount = 0;

        items.forEach(function (item) {
          var name = item.getAttribute("data-name");
          var nick = item.getAttribute("data-nick");
          var course = item.getAttribute("data-course");
          var moto = item.getAttribute("data-moto");

          var textMatch = name.indexOf(keyword) !== -1 || nick.indexOf(keyword) !== -1 || moto.indexOf(keyword) !== -1;
          var courseMatch = selectedCourse === "" || course === selectedCourse;

          if (textMatch && courseMatch) {
            item.style.display = "";
            visibleCount++;
          } else {
            item.style.display = "none";
          }
        });

        emptyState.style.display = visibleCount === 0 ? "block" : "none";
      }

      if (searchInput) {
        searchInput.addEventListener("input", filterCandidates);
      }
      if (courseFilter) {
        courseFilter.addEventListener("change", filterCandidates);
      }

      // $("#profileModal").on("show.bs.modal", function (event) {
      //   var button = $(event.relatedTarget);
      //   $("#modalImage").attr("src", button.data("image"));
      //   $("#modalCandN").text(button.data("candn"));
      //   $("#modalName").text(button.data("candname"));
      //   $("#modalCourse").text(button.data("candcourse"));
      //   $("#modalMoto").text(button.data("moto"));
      // });

      window.limitCheckboxes = function (checkbox, limit) {
        var checked = document.querySelectorAll('input[name="check[]"]:checked').length;
        if (checked > limit) {
          var lebihan = checked - limit;
          alert("Undian melebihi had. Sila buang " + lebihan + " pilihan untuk kekal pada " + limit + " calon.");
          checkbox.checked = false;
        }
      };

      window.validateVoting = function () {
        var checked = document.querySelectorAll('input[name="check[]"]:checked').length;
        if (checked !== voteLimit) {
          if (checked < voteLimit) {
            var baki = voteLimit - checked;
            alert("Undian belum mencukupi. Sila tambah " + baki + " lagi calon untuk cukup " + voteLimit + " undian.");
          } else {
            var lebihan = checked - voteLimit;
            alert("Undian melebihi had. Sila buang " + lebihan + " pilihan untuk kekal pada " + voteLimit + " undian.");
          }
          return false;
        }
        return true;
      };
    })();
  </script>
</body>
</html>
