<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

// Handle both edit and delete actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        $id = $_POST['id'] ?? null;
        $session = $_POST['session'] ?? null;

        if ($action === 'edit' && $id && $session) {
            // Update the session
            $result = sql($DBH, "UPDATE tbl_session SET session = ? WHERE id = ?", [$session, $id], "rows");
            $_SESSION['msg'] = $result ? "post" : "error";
            header("Location: post_session.php");
            exit;
        } elseif ($action === 'delete' && $id) {
            // Delete the session
            $result = sql($DBH, "DELETE FROM tbl_session WHERE id = ?", [$id], "rows");
            $_SESSION['msg'] = $result ? "post" : "error";
            header("Location: post_session.php");
            exit;
        }
    }
}

// Get admin full name
$admin_fullname = '';
$rows = sql($DBH, "SELECT fullname FROM tbl_admin WHERE status = ?", ["Active"], "rows");
if(!empty($rows)) {
    $admin_fullname = $rows[0]['fullname'];
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- ... (keep all the head content from previous code) ... -->
</head>

<body>
  <!-- Top Navigation -->
  <!-- ... (keep all navigation content from previous code) ... -->

  <!-- Main Content -->
  <main class="main-content">
    <div class="container-fluid px-4 pt-4">
      <!-- ... (keep all heading/breadcrumb content from previous code) ... -->

      <!-- Session Form -->
      <!-- ... (keep the create session form from previous code) ... -->
      
      <!-- Current Sessions -->
      <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
          <h6 class="m-0 font-weight-bold">Existing Academic Sessions</h6>
          <span class="badge bg-primary">
            Total: <?php 
              $count = sql($DBH, "SELECT COUNT(*) as total FROM tbl_session", [], "rows")[0]['total'];
              echo $count;
            ?>
          </span>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-hover">
              <thead class="table-light">
                <tr>
                  <th>#</th>
                  <th>Academic Session</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $rows1 = sql($DBH, "SELECT * FROM tbl_session ORDER BY session DESC", [], "rows");
                $count = 1;
                foreach($rows1 as $row1):
                ?>
                <tr>
                  <td><?php echo $count++; ?></td>
                  <td><?php echo htmlspecialchars($row1['session']); ?></td>
                  <td>
                    <div class="d-flex gap-2 action-btns">
                      <button class="btn btn-sm btn-primary edit-btn" 
                              data-id="<?php echo $row1['id']; ?>" 
                              data-session="<?php echo htmlspecialchars($row1['session']); ?>">
                        <i class="fas fa-edit me-1"></i> Edit
                      </button>
                      <button class="btn btn-sm btn-danger delete-btn" 
                              data-id="<?php echo $row1['id']; ?>">
                        <i class="fas fa-trash-alt me-1"></i> Delete
                      </button>
                    </div>
                  </td>
                </tr>
                <?php endforeach; ?>
                
                <?php if(empty($rows1)): ?>
                <tr>
                  <td colspan="3" class="text-center py-4">
                    <i class="fas fa-calendar-alt fa-2x mb-3 text-muted"></i>
                    <p class="text-muted">No academic sessions found</p>
                  </td>
                </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- Edit Session Modal -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="editModalLabel">Edit Academic Session</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="post" action="edit_session.php">
          <input type="hidden" name="action" value="edit">
          <input type="hidden" name="id" id="editId">
          <div class="modal-body">
            <div class="mb-3">
              <label for="editSession" class="form-label">Academic Session</label>
              <input type="text" class="form-control" id="editSession" name="session" required>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Save Changes</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Delete Confirmation Modal -->
  <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="post" action="edit_session.php">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" id="deleteId">
          <div class="modal-body">
            Are you sure you want to delete this academic session? This action cannot be undone.
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-danger">Delete</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Footer -->
  <!-- ... (keep footer content from previous code) ... -->

  <!-- Scripts -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  
  <script>
    // Toggle sidebar on mobile
    document.getElementById('sidebarToggle').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
        document.querySelector('.main-content').classList.toggle('active');
    });
    
    // Focus on session input field
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelector('input[name="session"]').focus();
    });
    
    // Delete modal handling
    $(document).ready(function() {
        $('.delete-btn').click(function() {
            var id = $(this).data('id');
            $('#deleteId').val(id);
            $('#deleteModal').modal('show');
        });
        
        // Edit modal handling
        $('.edit-btn').click(function() {
            var id = $(this).data('id');
            var session = $(this).data('session');
            
            $('#editId').val(id);
            $('#editSession').val(session);
            $('#editModal').modal('show');
        });
        
        // Form validation
        $('#editForm').submit(function(e) {
            if($('#editSession').val().trim() === '') {
                e.preventDefault();
                $('#editSession').addClass('is-invalid');
            } else {
                $('#editSession').removeClass('is-invalid');
            }
        });
    });
  </script>
</body>
</html>