<?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');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');

if (strlen($_SESSION['sid'] == 0)) {

  header('location:logout.php');

} else {

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

    $subject = $_POST['subject'];

    $class = $_POST['class'];

    $arm = $_POST['arm'];

    $subject_type = $_POST['subject_type'];

$query = mysqli_query($con, "INSERT INTO subjectcombination(Class, Subject_name, section, subject_type, status) 

VALUES ('$class', '$subject', '$arm', '$subject_type', '1')");

    if ($query) {

      flash_alert('Subject Combination added Successfully.');

      header('Location: add_subject.php'); exit;

      $msg = "";

    } else {

      flash_alert('Something Went Wrong. Please try again.');

      header('Location: add_subject.php'); exit;

    }

  }

  // Handle adding session

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

    $subject_namee = trim($_POST['subject_name']);

    if (!empty($subject_namee)) {

      // Check if fee name already exists

      $check_stmt = $con->prepare("SELECT id FROM subject_name WHERE name = ?");

      $check_stmt->bind_param("s", $subject_namee);

      $check_stmt->execute();

      $check_stmt->store_result();



      if ($check_stmt->num_rows == 0) {

        // Insert new fee name

        $stmt = $con->prepare("INSERT INTO subject_name (name) VALUES (?)");

        $stmt->bind_param("s", $subject_namee);

        if ($stmt->execute()) {

          flash_alert('Subject added successfully!');

          header('Location: add_subject.php'); exit;

        } else {

          flash_alert('Failed to add subject. Please try again.');

          header('Location: add_subject.php'); exit;

        }

      } else {

        flash_alert('Subject name already exists.');

        header('Location: add_subject.php'); exit;

      }

    } else {

      flash_alert('Please enter a subject.');

      header('Location: add_subject.php'); exit;

    }

  }





  // Fetch classes

  $sql = "SELECT DISTINCT class FROM class_section ORDER BY class ASC";

  $result = $con->query($sql);

?>

  <!DOCTYPE html>

  <html>

  <?php @include("includes/head.php"); ?>



  <body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

      <!-- Navbar -->

      <?php @include("includes/header.php"); ?>

      <!-- /.navbar -->



      <!-- Main Sidebar Container -->

      <?php @include("includes/sidebar.php"); ?>



      <!-- Content Wrapper. Contains page content -->

      <div class="content-wrapper">

        <!-- Content Header (Page header) -->

<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-book"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Subject Management

                                <span class="premium-subtitle text-secondary">Manage Subject</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="dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Add Subject</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section>      

        





        <!-- Main content -->

        <section class="content">

          <div class="container-fluid">

            <div class="row">

              <!-- Add Subject -->

              <div class="col-md-6">

                <div class="card shadow">

                  <div class="card-header bg-primary text-white">

                    <h5 class="card-title mb-0 font-weight-bold"> <i class="fas fa-book-open"></i> Add New Subject</h5>

                  </div>

                  <div class="card-body">

                    <h5 style="color: brown">Subject Details</h5>

                    <hr>

                    <form method="POST" enctype="multipart/form-data">

                      <div class="form-group col-md-12">

                        <label for="session">Subject Name (eg. Mathematics)</label>

                        <input type="text" class="form-control" name="subject_name" placeholder="Enter subject name" required>

                      </div>

                      <div class="form-group text-center">

                        <button type="submit" name="add_subject" class="btn btn-primary"><i class="fas fa-check-circle"></i> Add subject</button>

                      </div>

                    </form>

                  </div>

                </div>

              </div>

              <div class="col-md-6">

                <div class="card card-primary">

                  <div class="card-header">

                    <h3 class="card-title font-weight-bold"><i class="fas fa-chalkboard"></i> Class and Subject Combination</h3>

                  </div>

                  <div class="card-body">

                    <h5 style="color: brown">Class and Subject Details</h5>

                    <hr>

                    <form method="POST" action="add_subject.php">

                      <div class="row">

                        <div class="form-group col-md-6">

                          <label for="session">Subject</label>

                          <select class="form-control" name="subject" id="subject" required>

                            <option value="">-- Select Subject--</option>

                            <?php

                            $query = $con->query("SELECT id, name FROM subject_name ORDER BY name ASC");

                            while ($row = $query->fetch_assoc()) {



                              echo "<option value='{$row['name']}'>{$row['name']}</option>";

                            }

                            ?>

                          </select>

                        </div>

                        <div class="form-group col-md-6">

                          <label for="class">Class</label>

                          <select name="class" id="class" class="form-control" onchange="fetchArms()" required>

                            <option value="">Select Class</option>

                            <?php

                            $query = "SELECT DISTINCT class FROM class_section ORDER BY class";

                            $result = $con->query($query);

                            while ($row = $result->fetch_assoc()) {

                              echo "<option value='{$row['class']}'>{$row['class']}</option>";

                            }

                            ?>

                          </select>

                        </div>

                        <div class="form-group col-md-6">

                          <label for="arm">Arm</label>

                          <select name="arm" id="arm" class="form-control">

                            <option value="">Select Arm</option>

                          </select>

                        </div>



                        <div class="form-group col-md-6">

                          <label for="subject_type">Subject Type</label>

                          <select name="subject_type" id="subject_type" class="form-control">

                            <option value="">Select Type</option>

                            <option value="Compulsory">Compulsory Subject</option>

                            <option value="Elective">Elective Subject</option>

                          </select>

                        </div>

                      </div>







                      <div class="form-group text-center">

                        <button type="submit" name="submit" class="btn btn-primary"> <i class="fas fa-check-circle"></i>Submit</button>

                      </div>



                    </form>

                  </div>

                </div>

              </div>

              <!-- /.col -->

            </div>

          </div>

          <!-- /.row -->

          <!-- /.container-fluid -->

        </section>

        <!-- /.content -->





        <!-- Main content -->

        <section class="content">

          <div class="container-fluid">

            <div class="row">

              <div class="col-12">

                <div class="card card-primary">

                  <div class="card-header">

                    <h3 class="card-title font-weight-bold"> <i class="fas fa-book"></i> Manage Class & Subject Combination</h3>

                    <div class="card-tools">

                    </div>

                  </div>



                  <!-- /.card-header -->

                  <div id="editData" class="modal fade">

                    <div class="modal-dialog modal-lg">

                      <div class="modal-content">

                        <div class="modal-header">

                          <h5 class="modal-title">Edit Class & Subject</h5>

                          <button type="button" class="close" data-dismiss="modal" aria-label="Close">

                            <span aria-hidden="true">&times;</span>

                          </button>

                        </div>

                        <div class="modal-body" id="info_update">
<!-- loaded via AJAX -->
</div>

                        <div class="modal-footer ">

                          <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>

                        </div>

                        <!-- /.modal-content -->

                      </div>

                      <!-- /.modal-dialog -->

                    </div>

                    <!-- /.modal -->

                  </div>

                  <!--   end modal -->



                  <!-- Card Body -->

                  <div class="card-body mt-2">

                    <table id="example1" class="table table-bordered table-hover">

                      <thead>

                        <tr>

                          <th>#</th>

                          <th>Subject</th>

                          <th>Class</th>

                          <th>Arm</th>

                          <th>Subject Type</th>

                          <th>Action</th>

                        </tr>

                      </thead>

                      <tbody>

                        <?php

                        $query = mysqli_query($con, "SELECT * FROM subjectcombination ORDER BY Class ASC");

                        $cnt = 1;

                        while ($row = mysqli_fetch_array($query)) {

                        ?>

                          <tr>

                            <td><?php echo htmlentities($cnt); ?></td>

                            <td><?php echo htmlentities($row['Subject_name']); ?></td>

                            <td><?php echo htmlentities($row['Class']); ?></td>

                            <td><?php echo htmlentities($row['section']); ?></td>

                            <td><?php echo htmlentities($row['subject_type']); ?></td>

                            <td>

                              <button class="btn btn-success btn-xs edit_data" id="<?php echo $row['id']; ?>">

                                <i class="fa fa-edit"></i> Edit

                              </button>

                              <a href="add_subject.php?id=<?php echo $row['id']; ?>&del=1" onClick="return confirm('Are you sure you want to delete?')" class="btn btn-danger btn-xs">

                                <i class="fa fa-trash"></i> Delete

                              </a>

                            </td>

                          </tr>

                        <?php

                          $cnt++;

                        }

                        ?>

                      </tbody>

                    </table>

                  </div>

                  <!-- /.card-body -->

                </div>

                <!-- /.card -->

              </div>

              <!-- /.col -->

            </div>

            <!-- /.row -->

          </div>

          <!-- /.container-fluid -->

        </section>

        <!-- /.content -->







      </div>

      <!-- /.content-wrapper -->

      <?php @include("includes/footer.php"); ?>



    </div>



    <!-- ./wrapper -->

    <?php @include("includes/foot.php"); ?>



    <script src="dist/js/select2.min.js"></script>

    <!-- Scripts -->

    <script type="text/javascript">

      $(document).ready(function() {

        $(document).on('click', '.edit_data', function() {

          var edit_id = $(this).attr('id');

          $.ajax({

            url: "editsubject.php",

            type: "post",

            data: {

              edit_id: edit_id

            },

            success: function(data) {

              $("#info_update").html(data);

              $("#editData").data('ajax-src', 'editsubject.php').modal('show');
            $("#editData").find('form:not([action])').attr('data-ajax-action', 'editsubject.php');

            }

          });

        });

      });

    </script>



    <script>

      // In your Javascript (external .js resource or <script> tag)

      $(document).ready(function() {

        $('#class,#subject,#arm,#subject_type').select2();



      });

      function fetchArms() {

        var classSelected = document.getElementById("class").value;

        var armDropdown = document.getElementById("arm");



        // Clear previous options

        armDropdown.innerHTML = '<option value="">Select Arm</option>';



        if (classSelected) {

          fetch("fetch_arms.php?class=" + classSelected)

            .then(response => response.json())

            .then(data => {

              data.forEach(arm => {

                let option = document.createElement("option");

                option.value = arm;

                option.textContent = arm;

                armDropdown.appendChild(option);

              });

            })

            .catch(error => console.error("Error fetching arms:", error));

        }

      }

    </script>

  </body>



  </html>

<?php

} ?>