<?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 all actions (add, edit, delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];
        
        switch ($action) {
            case 'add':
                // Add new subject
                if (isset($_POST['subject']) && !empty(trim($_POST['subject']))) {
                    $subject = trim($_POST['subject']);
                    
                    // Check if subject already exists
                    $exists = sql($DBH, "SELECT COUNT(*) FROM tbl_subject WHERE subject = ?", [$subject], "rows")[0][0];
                    
                    if ($exists == 0) {
                        $result = sql($DBH, "INSERT INTO tbl_subject (subject) VALUES (?)", [$subject], "count");
                        $_SESSION['msg'] = $result ? "subject_added" : "error";
                    } else {
                        $_SESSION['msg'] = "subject_exists";
                    }
                }
                break;
                
            case 'edit':
                // Edit existing subject
                if (isset($_POST['id']) && isset($_POST['subject']) && !empty(trim($_POST['subject']))) {
                    $id = (int)$_POST['id'];
                    $subject = trim($_POST['subject']);
                    
                    // Check if new name already exists
                    $exists = sql($DBH, "SELECT COUNT(*) FROM tbl_subject WHERE subject = ? AND id != ?", [$subject, $id], "rows")[0][0];
                    
                    if ($exists == 0) {
                        $result = sql($DBH, "UPDATE tbl_subject SET subject = ? WHERE id = ?", [$subject, $id], "count");
                        $_SESSION['msg'] = $result ? "subject_updated" : "error";
                    } else {
                        $_SESSION['msg'] = "subject_exists";
                    }
                }
                break;
        }
        
        header("Location: post_subjects.php");
        exit();
    }
} elseif (isset($_GET['delete_id'])) {
    // Handle delete action
    $delete_id = (int)$_GET['delete_id'];
    if ($delete_id > 0) {
        $result = sql($DBH, "DELETE FROM tbl_subject WHERE id = ?", [$delete_id], "count");
        $_SESSION['msg'] = $result ? "subject_deleted" : "error";
    }
    header("Location: post_subjects.php");
    exit();
}

// Message handling
$msg = '';
if(isset($_SESSION['msg'])) {
    $messages = [
        "subject_added" => "Subject added successfully",
        "subject_updated" => "Subject updated successfully",
        "subject_deleted" => "Subject deleted successfully",
        "subject_exists" => "Subject already exists",
        "error" => "An error occurred, please try again"
    ];
    
    if(isset($messages[$_SESSION['msg']])) {
        $is_success = in_array($_SESSION['msg'], ["subject_added", "subject_updated", "subject_deleted"]);
        $alert_type = $is_success ? 'success' : 'danger';
        $msg = "<div class='alert alert-$alert_type text-center mb-4'>"
             . $messages[$_SESSION['msg']]
             . "</div>";
    }
    unset($_SESSION['msg']);
}

// 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>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Manage Subjects - VERBUM DEI INT'L COLLEGE</title>
  <link rel="icon" type="image/png" href="https://portal.vda.com.ng/coll_admin/coll_logo.jpg">
  
  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-blue: #1976d2;
      --dark-blue: #0d47a1;
      --light-blue: #64b5f6;
      --accent-blue: #bbdefb;
      --bg-light: #e3f2fd;
      --text-dark: #212529;
    }
    
    body {
      font-family: 'Poppins', sans-serif;
      background-color: var(--bg-light);
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    
    /* Navbar Styles */
    .navbar {
      background-color: var(--primary-blue);
      box-shadow: 0 0.15rem 1.75rem 0 rgba(33, 37, 41, 0.1);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
      color: white;
    }
    
    .navbar-brand {
      font-weight: 800;
      font-size: 1.2rem;
      color: white;
    }
    
    /* Sidebar Styles */
    .sidebar {
      background: linear-gradient(180deg, var(--dark-blue) 0%, var(--primary-blue) 100%);
      position: fixed;
      top: 56px;
      left: -250px;
      width: 250px;
      height: calc(100vh - 56px);
      transition: all 0.3s;
      z-index: 1000;
      overflow-y: auto;
    }
    
    .sidebar.active {
      left: 0;
    }
    
    .sidebar .nav-link {
      color: rgba(255, 255, 255, 0.85);
      font-weight: 600;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
      transition: all 0.2s;
    }
    
    .sidebar .nav-link:hover {
      color: #fff;
      background-color: rgba(255, 255, 255, 0.15);
    }
    
    .sidebar .nav-link.active {
      color: #fff;
      background-color: var(--light-blue);
      box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .sidebar .nav-link i {
      margin-right: 0.5rem;
      width: 20px;
      text-align: center;
    }
    
    /* Main Content Styles */
    .main-content {
      margin-left: 0;
      width: 100%;
      transition: all 0.3s;
      flex: 1 0 auto;
      padding-top: 56px;
    }
    
    @media (min-width: 992px) {
      .sidebar {
        left: 0;
      }
      .main-content {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    /* Card Styles */
    .card {
      border: none;
      border-radius: 12px;
      box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
      margin-bottom: 1.5rem;
      transition: transform 0.3s, box-shadow 0.3s;
    }
    
    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
    }
    
    .card-header {
      background-color: var(--accent-blue);
      border-bottom: 1px solid var(--light-blue);
      font-weight: 700;
      color: var(--dark-blue);
      padding: 1rem 1.5rem;
    }
    
    /* Button Styles */
    .btn-primary {
      background-color: var(--primary-blue);
      border-color: var(--primary-blue);
      padding: 0.5rem 1.5rem;
      font-weight: 600;
    }
    
    .btn-primary:hover {
      background-color: var(--dark-blue);
      border-color: var(--dark-blue);
    }
    
    /* Form Styles */
    .form-control, .form-select {
      height: 50px;
      border-radius: 8px;
      padding: 0.5rem 1rem;
      border: 1px solid #ced4da;
      transition: all 0.3s;
    }
    
    .form-control:focus, .form-select:focus {
      border-color: var(--light-blue);
      box-shadow: 0 0 0 0.25rem rgba(100, 181, 246, 0.25);
    }
    
    /* Table Styles */
    .table-responsive {
      overflow-x: auto;
    }
    
    .table-hover tbody tr:hover {
      background-color: rgba(0, 0, 0, 0.03);
    }
    
    /* Admin Info Styles */
    .admin-info {
      display: flex;
      align-items: center;
      background-color: rgba(255,255,255,0.2);
      padding: 8px 12px;
      border-radius: 8px;
      color: white;
    }
    
    .admin-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .admin-access {
      font-style: italic;
      opacity: 0.8;
      margin-right: 10px;
      font-size: 0.9rem;
    }
    
    .admin-icon {
      font-size: 1.5rem;
      color: white;
    }
    
    /* Footer styles */
    .footer {
      background-color: var(--dark-blue);
      color: white;
      padding: 20px 0;
      flex-shrink: 0;
      width: 100%;
    }
    
    @media (min-width: 992px) {
      .footer {
        margin-left: 250px;
        width: calc(100% - 250px);
      }
    }
    
    .copyright-text {
      font-weight: 600;
      font-size: 1rem;
    }
    
    /* Support badge */
    .support-badge {
      background-color: var(--accent-blue);
      color: var(--dark-blue);
      font-weight: 600;
      padding: 0.5rem 1rem;
    }
    
    /* Breadcrumbs */
    .breadcrumb-custom .breadcrumb {
      background-color: transparent;
      padding: 0;
    }
    
    .breadcrumb-custom .breadcrumb-item a {
      color: var(--primary-blue);
      text-decoration: none;
    }
    
    .breadcrumb-custom .breadcrumb-item.active {
      color: var(--dark-blue);
      font-weight: 500;
    }
    
    /* Action buttons */
    .action-btns .btn {
      min-width: 90px;
    }
    
    /* Modal styles */
    .modal-header {
      background-color: var(--primary-blue);
      color: white;
    }
    
    .modal-danger .modal-header {
      background-color: #dc3545;
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
      <button id="sidebarToggle" class="btn btn-link d-lg-none me-2">
        <i class="fas fa-bars"></i>
      </button>
      <a class="navbar-brand d-none d-lg-block" href="#">
        VERBUM DEI INT'L COLLEGE
      </a>
      <div class="ms-auto d-flex align-items-center">
        <div class="admin-info me-3">
          <span class="admin-name"><?php echo htmlspecialchars($admin_fullname); ?></span>
          <span class="admin-access">(Administrator)</span>
          <i class="fas fa-user-circle admin-icon"></i>
        </div>
        <a href="logout.php" class="btn btn-sm btn-outline-light">
          <i class="fas fa-sign-out-alt"></i>
        </a>
      </div>
    </div>
  </nav>

  <!-- Sidebar -->
  <nav id="sidebar" class="sidebar">
    <div class="position-sticky pt-3">
      <div class="text-center mb-4 d-none d-lg-block">
        <img src="https://portal.vda.com.ng/coll_admin/coll_logo.jpg" alt="School Logo" class="rounded-circle" width="80">
        <h5 class="mt-2 text-white">VERBUM DEI INT'L COLLEGE</h5>
        <p class="text-white-50 small">Admin Dashboard</p>
      </div>
      
      <ul class="nav flex-column">
        <li class="nav-item">
          <a class="nav-link" href="main.php">
            <i class="fas fa-fw fa-tachometer-alt"></i>
            Admin Centre
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="post_session.php">
            <i class="fas fa-fw fa-calendar-alt"></i>
            School Year/Session
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="post_classes.php">
            <i class="fas fa-fw fa-building"></i>
            Manage Classes
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="add_students.php">
            <i class="fas fa-fw fa-user-plus"></i>
            Register New Student
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="post_subjects.php">
            <i class="fas fa-fw fa-book"></i>
            Manage Subjects
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="teachers.php">
            <i class="fas fa-fw fa-chalkboard-teacher"></i>
            Manage Teachers
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="students.php">
            <i class="fas fa-fw fa-users"></i>
            Manage Students
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="deactivate_students.php">
            <i class="fas fa-fw fa-user-lock"></i>
            Activate/Deactivate
          </a>
        </li>
      </ul>
    </div>
  </nav>

  <!-- Main Content -->
  <main class="main-content">
    <div class="container-fluid px-4 pt-4">
      <!-- Page Heading -->
      <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Subject Management</h1>
        <div class="d-none d-sm-inline-block">
          <span class="badge support-badge p-2">
            <i class="fas fa-phone-alt me-1"></i> Support: 08032929756
          </span>
        </div>
      </div>

      <!-- Messages -->
      <?php echo $msg; ?>

      <!-- Breadcrumbs -->
      <div class="breadcrumb-custom mb-4">
        <nav aria-label="breadcrumb">
          <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="main.php">Admin Dashboard</a></li>
            <li class="breadcrumb-item active">Manage Subjects</li>
          </ol>
        </nav>
      </div>

      <!-- Subject Form -->
      <div class="card shadow mb-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold">Add New Subject</h6>
        </div>
        <div class="card-body">
          <form method="post" action="post_subjects.php">
            <input type="hidden" name="action" value="add">
            <div class="row mb-4">
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="form-label">Subject Name <span class="text-danger">*</span></label>
                  <input type="text" name="subject" class="form-control" placeholder="e.g. Mathematics" required>
                  <small class="text-muted">Enter the full name of the subject</small>
                </div>
              </div>
            </div>
            
            <div class="row">
              <div class="col-12 text-center">
                <button type="submit" class="btn btn-primary btn-lg px-5 py-3">
                  <i class="fas fa-plus-circle me-2"></i>Add Subject
                </button>
                <button type="reset" class="btn btn-secondary btn-lg px-5 py-3 ms-3">
                  <i class="fas fa-undo me-2"></i>Reset
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
      
      <!-- Current Subjects -->
      <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 Subjects</h6>
          <span class="badge bg-primary">
            Total: <?php 
              $count = sql($DBH, "SELECT COUNT(*) as total FROM tbl_subject", [], "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>Subject Name</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                <?php
                $rows1 = sql($DBH, "SELECT * FROM tbl_subject ORDER BY subject ASC", [], "rows");
                $count = 1;
                foreach($rows1 as $row1):
                ?>
                <tr>
                  <td><?php echo $count++; ?></td>
                  <td><?php echo htmlspecialchars($row1['subject']); ?></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-subject="<?php echo htmlspecialchars($row1['subject']); ?>">
                        <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-book fa-2x mb-3 text-muted"></i>
                    <p class="text-muted">No subjects found</p>
                  </td>
                </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </main>

  <!-- Edit Subject 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 Subject</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="post" action="post_subjects.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="editSubject" class="form-label">Subject Name</label>
              <input type="text" class="form-control" id="editSubject" name="subject" 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>
        <div class="modal-body">
          Are you sure you want to delete this subject? This action cannot be undone.
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
          <a href="#" id="confirmDelete" class="btn btn-danger">Delete</a>
        </div>
      </div>
    </div>
  </div>

  <!-- Footer -->
  <footer class="footer">
    <div class="container-fluid">
      <div class="row align-items-center">
        <div class="col-md-6">
          <span class="copyright-text">Copyright &copy; VERBUM DEI INT'L COLLEGE <?php echo date("Y"); ?></span>
        </div>
        <div class="col-md-6">
          <div class="text-md-end">
            <a href="https://dataswift.com.ng" target="_blank" rel="noopener noreferrer" class="text-white">
              <span>Powered by DataSwift</span>
              <img src="datalogo.png" alt="DataSwift Logo" class="ms-2" height="24">
            </a>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <!-- Bootstrap 5 JS Bundle with Popper -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  
  <!-- Custom Scripts -->
  <script>
    // Toggle sidebar on mobile
    document.getElementById('sidebarToggle').addEventListener('click', function() {
        document.getElementById('sidebar').classList.toggle('active');
        document.querySelector('.main-content').classList.toggle('active');
    });
    
    // Delete modal handling
    $(document).ready(function() {
        $('.delete-btn').click(function() {
            var id = $(this).data('id');
            var deleteUrl = 'post_subjects.php?delete_id=' + id;
            $('#confirmDelete').attr('href', deleteUrl);
            $('#deleteModal').modal('show');
        });
        
        // Edit modal handling
        $('.edit-btn').click(function() {
            var id = $(this).data('id');
            var subject = $(this).data('subject');
            
            $('#editId').val(id);
            $('#editSubject').val(subject);
            $('#editModal').modal('show');
        });
    });
  </script>
</body>
</html>