<?php

session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
  mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);

include('includes/dbconnection.php');
include('includes/flash.php');

$isAjax = !empty($_POST['is_ajax'])
  || (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest');

// Handle form submission — return JSON
if ($isAjax && isset($_POST['submit'])) {

  header('Content-Type: application/json');

  $sid         = $_SESSION['edid'];
  $studentname = $_POST['studentname'];
  $email       = $_POST['email'];
  $class       = $_POST['class'];
  $stream      = $_POST['stream'];
  $acsession   = $_POST['acsession'];
  $term        = $_POST['term'];

  $sql = "UPDATE students
          SET studentName      = :studentname,
              email            = :email,
              class            = :class,
              stream           = :stream,
              academic_session = :acsession,
              admission_term   = :term
          WHERE id = :sid";

  $query = $dbh->prepare($sql);
  $query->bindParam(':studentname', $studentname, PDO::PARAM_STR);
  $query->bindParam(':email',       $email,       PDO::PARAM_STR);
  $query->bindParam(':class',       $class,       PDO::PARAM_STR);
  $query->bindParam(':stream',      $stream,      PDO::PARAM_STR);
  $query->bindParam(':acsession',   $acsession,   PDO::PARAM_STR);
  $query->bindParam(':term',        $term,        PDO::PARAM_STR);
  $query->bindParam(':sid',         $sid,         PDO::PARAM_INT);

  $success = $query->execute();

  echo json_encode(['success' => (bool) $success]);
  exit;
}
?>

<div class="card-body">
  <section class="content">
    <div class="container-fluid">
      <div class="row">

        <?php
        $eid = $_POST['edit_id'];
        $ret = mysqli_query($con, "SELECT * FROM students WHERE id = '$eid'");

        while ($row = mysqli_fetch_array($ret)):
          $_SESSION['edid'] = $row['id'];
        ?>

        <!-- Profile sidebar -->
        <div class="col-md-4">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title font-weight-bold text-white">
                <i class="fas fa-user-graduate"></i> Student Details
              </h5>
            </div>
            <div class="card-body box-profile">
              <div class="text-center">
                <img class="img-circle d-block mx-auto"
                     src="studentimages/<?php echo htmlspecialchars($row['studentImage']); ?>"
                     width="150" height="150" alt="Student photo">
              </div>
              <h3 class="profile-username text-center">
                <?php echo htmlspecialchars($row['studentName']); ?>
              </h3>
              <ul class="list-group list-group-unbordered mb-3">
                <li class="list-group-item">
                  <b>Form No.</b>
                  <span class="float-right"><?php echo htmlspecialchars($row['FormNo']); ?></span>
                </li>
                <li class="list-group-item">
                  <b>Email</b>
                  <span class="float-right"><?php echo htmlspecialchars($row['email']); ?></span>
                </li>
                <li class="list-group-item">
                  <b>Class</b>
                  <span class="float-right"><?php echo htmlspecialchars($row['class']); ?></span>
                </li>
                <li class="list-group-item">
                  <b>School Type</b>
                  <span class="float-right"><?php echo htmlspecialchars($row['stream']); ?></span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!-- /.col sidebar -->

        <!-- Edit form -->
        <div class="col-md-8">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title font-weight-bold text-white">
                <i class="fas fa-edit"></i> Edit Student Details
              </h5>
            </div>
            <div class="card-body">

              <form role="form" method="post" class="form-horizontal">
                <div class="row">

                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Student's Fullname <span class="text-danger">*</span></label>
                      <input name="studentname" class="form-control"
                             value="<?php echo htmlspecialchars($row['studentName']); ?>" required>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>Form No.</label>
                      <input class="form-control"
                             value="<?php echo htmlspecialchars($row['FormNo']); ?>" readonly>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>Email <span class="text-danger">*</span></label>
                      <input name="email" type="email" class="form-control"
                             value="<?php echo htmlspecialchars($row['email']); ?>" required>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>Class <span class="text-danger">*</span></label>
                      <select name="class" id="es2_class" class="form-control" required>
                        <option value="">-- Select Class --</option>
                        <?php
                        $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class ASC");
                        while ($cr = $classResult->fetch_assoc()):
                          $sel = ($row['class'] == $cr['class']) ? 'selected' : '';
                          echo "<option value='{$cr['class']}' $sel>{$cr['class']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>School Type <span class="text-danger">*</span></label>
                      <select name="stream" id="es2_stream" class="form-control" required>
                        <option value="">-- Select --</option>
                        <option value="Day"      <?php if ($row['stream'] == 'Day')      echo 'selected'; ?>>Day</option>
                        <option value="Boarding" <?php if ($row['stream'] == 'Boarding') echo 'selected'; ?>>Boarding</option>
                      </select>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>Session to Resume <span class="text-danger">*</span></label>
                      <select name="acsession" id="es2_session" class="form-control" required>
                        <option value="">-- Select Session --</option>
                        <?php
                        $sessResult = $con->query("SELECT DISTINCT session_name FROM school_sessions ORDER BY session_name DESC");
                        while ($sr = $sessResult->fetch_assoc()):
                          $sel = ($row['academic_session'] == $sr['session_name']) ? 'selected' : '';
                          echo "<option value='{$sr['session_name']}' $sel>{$sr['session_name']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>
                  </div>

                  <div class="col-md-6">
                    <div class="form-group">
                      <label>Term to Resume <span class="text-danger">*</span></label>
                      <select name="term" id="es2_term" class="form-control" required>
                        <option value="">-- Select Term --</option>
                        <?php
                        $termResult = $con->query("SELECT DISTINCT term_name FROM school_terms ORDER BY term_name ASC");
                        while ($tr = $termResult->fetch_assoc()):
                          $sel = ($row['admission_term'] == $tr['term_name']) ? 'selected' : '';
                          echo "<option value='{$tr['term_name']}' $sel>{$tr['term_name']}</option>";
                        endwhile;
                        ?>
                      </select>
                    </div>
                  </div>

                </div><!-- /.row -->

                <div class="modal-footer text-right">
                  <button type="submit" name="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> Update
                  </button>
                </div>

              </form>

            </div><!-- /.card-body -->
          </div><!-- /.card -->
        </div><!-- /.col-md-9 -->

        <?php endwhile; ?>

      </div><!-- /.row -->
    </div><!-- /.container-fluid -->
  </section>
</div>

<script>
  // Init select2 on the dropdowns inside the modal after content loads
  $(function () {
    $('#es2_class').select2({ dropdownParent: $('#editData'), width: '100%' }).trigger('change');
    $('#es2_stream').select2({ dropdownParent: $('#editData'), width: '100%' }).trigger('change');
    $('#es2_session').select2({ dropdownParent: $('#editData'), width: '100%' }).trigger('change');
    $('#es2_term').select2({ dropdownParent: $('#editData'), width: '100%' }).trigger('change');
  });
</script>
