<?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');

// 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'];
}

// Get the subject ID from URL
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Fetch the subject details
$subject = [];
if($id) {
    $rows = sql($DBH, "SELECT * FROM tbl_subject WHERE id = ?", [$id], "rows");
    if(!empty($rows)) {
        $subject = $rows[0];
    } else {
        $_SESSION['msg'] = "Subject not found";
        header("Location: post_subjects.php");
        exit();
    }
} else {
    $_SESSION['msg'] = "Invalid subject ID";
    header("Location: post_subjects.php");
    exit();
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_subject'])) {
    $subject_name = trim($_POST['subject']);
    
    // Validate inputs
    if(empty($subject_name)) {
        $_SESSION['msg'] = "Please enter a subject name";
    } else {
        // Check if subject already exists (excluding current record)
        $existing = sql($DBH, "SELECT id FROM tbl_subject WHERE subject = ? AND id != ?", 
                      [$subject_name, $id], "rows");
        
        if(!empty($existing)) {
            $_SESSION['msg'] = "A subject with this name already exists";
        } else {
            $result = sql($DBH, "UPDATE tbl_subject SET subject = ? WHERE id = ?", 
                         [$subject_name, $id], "count");
            
            if($result > 0) {
                $_SESSION['msg'] = "update_success";
            } else {
                $_SESSION['msg'] = "update_failed";
            }
            
            header("Location: post_subjects.php");
            exit();
        }
    }
}

// Message handling
$msg = '';
if(isset($_SESSION['msg'])) {
    $alert_type = 'warning'; // default
    $messages = [
        "update_success" => "Subject updated successfully",
        "update_failed" => "Failed to update subject",
        "Subject not found" => "The requested subject was not found",
        "Invalid subject ID" => "Invalid subject identifier provided",
        "Please enter a subject name" => "Please enter a subject name",
        "A subject with this name already exists" => "A subject with this name already exists"
    ];
    
    if(isset($messages[$_SESSION['msg']])) {
        $is_success = ($_SESSION['msg'] == "update_success");
        $alert_type = $is_success ? 'success' : 'danger';
        $msg = "<div class='alert alert-$alert_type text-center mb-4'>"
             . $messages[$_SESSION['msg']]
             . "</div>";
    }
    unset($_SESSION['msg']);
}
?>
<!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>Edit Subject - BRITISH LEARNERS COLLEGE</title>
  <link rel="icon" type="image/png" href="https://bkms.com.ng/portal/coll_admin/sch_logo.jpeg">
  
  <!-- 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">
  
  <!-- Custom CSS -->
  <style>
    :root {
      --primary-color: #2e7d32; /* Dark green */
      --secondary-color: #4caf50; /* Medium green */
      --accent-color: #8bc34a; /* Light green */
      --dark-color: #1b5e20; /* Very dark green */
      --light-color: #f1f8e9; /* Very light green */
    }
    
    html, body {
      height: 100%;
    }
    
    body {
      font-family: 'Nunito', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background-color: var(--light-color);
      display: flex;
      flex-direction: column;
    }
    
    /* Navbar Styles */
    .navbar {
      background-color: var(--light-color);
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      position: fixed;
      top: 0;
      width: 100%;
      z-index: 1030;
    }
    
    .navbar-brand {
      font-weight: 800;
      font-size: 1.2rem;
      color: var(--dark-color);
    }
    
    /* Sidebar Styles */
    .sidebar {
      background: linear-gradient(180deg, var(--dark-color) 0%, var(--primary-color) 100%);
      position: fixed;
      top: 56px; /* Below navbar */
      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.8);
      font-weight: 600;
      padding: 0.75rem 1rem;
      margin-bottom: 0.2rem;
    }
    
    .sidebar .nav-link:hover {
      color: #fff;
      background-color: rgba(255, 255, 255, 0.1);
    }
    
    .sidebar .nav-link.active {
      color: #fff;
      background-color: var(--secondary-color);
    }
    
    .sidebar .nav-link i {
      margin-right: 0.5rem;
    }
    
    /* 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: 0.5rem;
      box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
      margin-bottom: 1.5rem;
    }
    
    .card-header {
      background-color: #f8f9fc;
      border-bottom: 1px solid #e3e6f0;
      font-weight: 700;
    }
    
    /* Button Styles */
    .btn-primary {
      background-color: var(--primary-color);
      border-color: var(--primary-color);
    }
    
    .btn-primary:hover {
      background-color: var(--dark-color);
      border-color: var(--dark-color);
    }
    
    /* Admin Info Styles */
    .admin-info {
      display: flex;
      align-items: center;
      background-color: var(--light-color);
      padding: 10px 15px;
      border-radius: 0.5rem;
    }
    
    .admin-name {
      margin-right: 5px;
      font-weight: 600;
    }
    
    .admin-access {
      font-style: italic;
      color: #6c757d;
      margin-right: 10px;
    }
    
    .admin-icon {
      font-size: 1.5rem;
      color: var(--primary-color);
    }
    
    /* Footer styles */
    .footer {
      background-color: var(--dark-color);
      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;
    }
    
    .powered-by {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      color: white;
    }
    
    .powered-by-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      color: inherit;
      transition: opacity 0.3s ease;
    }
    
    .powered-by-link:hover {
      opacity: 0.8;
      text-decoration: none;
      color: white;
    }
    
    /* Breadcrumb styles */
    .breadcrumb-custom {
      background-color: var(--light-color);
      padding: 15px;
      border-radius: 0.5rem;
    }
    
    /* Support badge */
    .support-badge {
      background-color: var(--accent-color);
      color: var(--dark-color);
    }
    
    /* Form styles */
    .form-control:focus {
      border-color: var(--accent-color);
      box-shadow: 0 0 0 0.25rem rgba(139, 195, 74, 0.25);
    }
  </style>
</head>

<body>
  <!-- Top Navigation -->
  <nav class="navbar navbar-expand-lg navbar-light">
    <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="#">
        BRITISH LEARNERS 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-danger">
          <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://bkms.com.ng/portal/coll_admin/sch_logo.jpeg" alt="School Logo" class="rounded-circle" width="80">
        <h5 class="mt-2 text-white">BRITISH LEARNERS 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" 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">Edit Subject</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"><a href="post_subjects.php">Manage Subjects</a></li>
            <li class="breadcrumb-item active">Edit Subject</li>
          </ol>
        </nav>
      </div>

      <!-- Edit Subject Form -->
      <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 text-primary">Edit Subject Details</h6>
          <span class="badge bg-secondary">ID: <?php echo $id; ?></span>
        </div>
        <div class="card-body">
          <form method="post" class="form-horizontal">
            <div class="form-group row mb-4">
              <label class="col-sm-2 col-form-label">Subject Name <span class="text-danger">*</span></label>
              <div class="col-sm-6">
                <input type="text" class="form-control" name="subject" 
                       value="<?php echo htmlspecialchars($subject['subject']); ?>" required>
                <small class="form-text text-muted">Example: English Language, Mathematics, etc.</small>
              </div>
            </div>

            <div class="form-group row">
              <div class="col-sm-10 offset-sm-2">
                <button type="submit" name="update_subject" class="btn btn-primary">
                  <i class="fas fa-save me-2"></i>Save Changes
                </button>
                <a href="post_subjects.php" class="btn btn-outline-secondary ml-2">
                  <i class="fas fa-times me-2"></i>Cancel
                </a>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </main>

  <!-- 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; BRITISH LEARNERS 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>
            </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');
    });
    
    // Focus on first input field
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelector('form input').focus();
    });
  </script>
</body>
</html>