<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];
include('includes/flash.php');
if (isset($_POST['submit'])) {
  $sid = $_SESSION['student_id'];
  $studentimage = $_FILES["studentimage"]["name"];
  move_uploaded_file($_FILES["studentimage"]["tmp_name"], "studentimages/" . $_FILES["studentimage"]["name"]);
  $sql = "update students set studentImage=:studentimage where id='$sid'";
  $query = $dbh->prepare($sql);
  $query->bindParam(':studentimage', $studentimage, PDO::PARAM_STR);
  $query->execute();
  if ($query->execute()) {
    flash_alert('Profile photo updated successfully.');
    header("Location: stdprofileoldboard.php?tab_id=$tabSessionID");
    exit;
  } else {
    flash_alert('Something went wrong, please try again later.');
  }
}
?>
<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <?php @include("includes/headerstd.php"); ?>
    <?php @include("includes/sidebaroldstdboard.php"); ?>
    <div class="content-wrapper">
      <section class="content-header premium-header">
        <div class="container-fluid">
          <div class="header-glass-card">
            <div class="row align-items-center">
              <div class="col-md-8">
                <div class="title-section">
                  <div class="icon-box bg-primary-gradient shadow-sm">
                    <i class="fas fa-user-graduate"></i>
                  </div>
                  <div>
                    <h1 class="premium-title text-primary">
                      Student Information Management
                      <span class="premium-subtitle text-secondary">Profile Update</span>
                    </h1>
                    <div class="mt-1">
                      <?php if ($currentSessionName): ?>
                        <span class="badge badge-primary mr-1">
                          <i class="fas fa-calendar-alt"></i>
                          <?= htmlspecialchars($currentSessionName) ?>
                        </span>
                      <?php endif; ?>
                      <?php if ($currentTermName): ?>
                        <span class="badge badge-success">
                          <i class="fas fa-bookmark"></i>
                          <?= htmlspecialchars($currentTermName) ?>
                        </span>
                      <?php else: ?>
                        <span class="badge badge-warning">
                          <i class="fas fa-exclamation-triangle"></i> No active term
                        </span>
                      <?php endif; ?>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <nav aria-label="breadcrumb">
                  <ol class="breadcrumb premium-breadcrumb">
                    <li class="breadcrumb-item"><a href="oldstdboard.php" class="text-primary">Home</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Update Photo</li>
                  </ol>
                </nav>
              </div>
            </div>
          </div>
        </div>
      </section>

      <section class="content">
        <div class="container-fluid">
          <div class="row justify-content-center">
            <div class="col-lg-12 col-md-12">
              <?php
              $eid = $_SESSION['student_id'];
              $sql = "SELECT * from students where id=:eid";
              $query = $dbh->prepare($sql);
              $query->bindParam(':eid', $eid, PDO::PARAM_STR);
              $query->execute();
              $results = $query->fetchAll(PDO::FETCH_OBJ);
              if ($query->rowCount() > 0):
                foreach ($results as $row):
                  $currentImg = ($row->studentImage == "avatar15.jpg" || empty($row->studentImage))
                    ? "studentimages/avatar15.jpg"
                    : "studentimages/" . $row->studentImage;
                  ?>
                  <div class="card card-primary shadow-sm border-0 rounded-lg">
                    <div class="card-header  border-bottom py-3">
                      <h5 class="mb-0 font-weight-bold">
                        <i class="fas fa-camera mr-2"></i>Update Profile Photo
                      </h5>
                    </div>
                    <div class="card-body p-4">
                      <form method="post" enctype="multipart/form-data" id="photoForm">

                        <div class="form-group">
                          <label class="text-muted small font-weight-bold text-uppercase mb-1">Student Name</label>
                          <input type="text" class="form-control form-control-lg bg-light border-0"
                            value="<?php echo htmlspecialchars($row->studentName); ?>" readonly>
                        </div>

                        <div class="form-group mt-4">
                          <label class="text-muted small font-weight-bold text-uppercase mb-2">Profile Photo</label>
                          <div class="d-flex align-items-center">
                            <div class="mr-4 text-center">
                              <p class="small text-muted mb-1">Current</p>
                              <img id="currentPhoto" src="<?php echo $currentImg; ?>"
                                class="rounded-circle border shadow-sm" style="width:90px;height:90px;object-fit:cover;"
                                alt="Current photo">
                            </div>
                            <div class="text-center" id="previewWrap" style="display:none;">
                              <p class="small text-muted mb-1">New Preview</p>
                              <img id="previewPhoto" class="rounded-circle border border-primary shadow-sm"
                                style="width:90px;height:90px;object-fit:cover;" alt="Preview">
                            </div>
                          </div>
                        </div>

                        <div class="form-group mt-3">
                          <label class="text-muted small font-weight-bold text-uppercase mb-2">Upload New Photo</label>
                          <div id="dropZone" class="border-2 border-dashed rounded-lg p-4 text-center"
                            style="border:2px dashed #ced4da;cursor:pointer;transition:border-color .2s,background .2s;">
                            <i class="fas fa-cloud-upload-alt fa-2x text-muted mb-2"></i>
                            <p class="mb-1 text-muted">Drag &amp; drop a photo here, or <span
                                class="text-primary font-weight-bold">browse</span></p>
                            <p class="small text-muted mb-0">JPG, PNG, GIF &mdash; max 2MB</p>
                            <input type="file" name="studentimage" id="studentimage" accept="image/*"
                              style="position:absolute;width:1px;height:1px;opacity:0;">
                          </div>
                          <div id="fileName" class="small text-success mt-1" style="display:none;">
                            <i class="fas fa-check-circle mr-1"></i><span></span>
                          </div>
                        </div>

                        <div class="d-flex justify-content-between align-items-center mt-4">
                          <a href="oldstdboard.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left mr-1"></i> Back
                          </a>
                          <button type="submit" name="submit" class="btn btn-primary px-4" id="submitBtn" disabled>
                            <i class="fas fa-save mr-1"></i> Save Photo
                          </button>
                        </div>
                      </form>
                    </div>
                  </div>
                <?php endforeach; endif; ?>
            </div>
          </div>
        </div>
      </section>
    </div>
    <?php @include("includes/foot.php"); ?>
    <?php @include("includes/footer.php"); ?>
  </div>

  <style>
    #dropZone:hover,
    #dropZone.dragover {
      border-color: #007bff !important;
      background: #f0f7ff;
    }
  </style>
  <script>
    (function () {
      const zone = document.getElementById('dropZone');
      const input = document.getElementById('studentimage');
      const preview = document.getElementById('previewPhoto');
      const previewWrap = document.getElementById('previewWrap');
      const fileNameBox = document.getElementById('fileName');
      const submitBtn = document.getElementById('submitBtn');

      zone.addEventListener('click', () => input.click());
      zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('dragover'); });
      zone.addEventListener('dragleave', () => zone.classList.remove('dragover'));
      zone.addEventListener('drop', e => {
        e.preventDefault(); zone.classList.remove('dragover');
        if (e.dataTransfer.files.length) { input.files = e.dataTransfer.files; handleFile(e.dataTransfer.files[0]); }
      });
      input.addEventListener('change', () => { if (input.files[0]) handleFile(input.files[0]); });

      function handleFile(file) {
        if (!file.type.startsWith('image/')) { alert('Please select an image file.'); return; }
        const reader = new FileReader();
        reader.onload = e => {
          preview.src = e.target.result;
          previewWrap.style.display = 'block';
          fileNameBox.style.display = 'block';
          fileNameBox.querySelector('span').textContent = file.name;
          submitBtn.disabled = false;
        };
        reader.readAsDataURL(file);
      }
    })();
  </script>
</body>

</html>