<?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 teacher ID from URL
$teacher_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Fetch teacher data
$teacher = [];
if ($teacher_id > 0) {
    $rows = sql($DBH, "SELECT * FROM tbl_user WHERE id = ? AND teacher = ?", [$teacher_id, "true"], "rows");
    if (!empty($rows)) {
        $teacher = $rows[0];
    } else {
        header("Location: teachers.php");
        exit();
    }
} else {
    header("Location: teachers.php");
    exit();
}

// Handle form submission
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_info'])) {
        // Update teacher information
        $fullname = strip_tags($_POST['fullname']);
        $email = strip_tags($_POST['email']);
        $phone = strip_tags($_POST['phone']);
        $gender = strip_tags($_POST['gender']);
        $class = strip_tags($_POST['class']);
        $subclass = strip_tags($_POST['subclass']);
        $subject = strip_tags($_POST['subject']);
        
        try {
            $result = sql($DBH, "UPDATE tbl_user SET fullname = ?, email = ?, phone = ?, gender = ?, class = ?, subclass = ?, subject = ? WHERE id = ?", 
                         [$fullname, $email, $phone, $gender, $class, $subclass, $subject, $teacher_id], "count");
            
            if ($result > 0) {
                $success = "Teacher information updated successfully";
                // Refresh teacher data
                $teacher = sql($DBH, "SELECT * FROM tbl_user WHERE id = ?", [$teacher_id], "rows")[0];
            } else {
                $error = "No changes were made";
            }
        } catch (Exception $e) {
            $error = "Error updating teacher: " . $e->getMessage();
        }
    } elseif (isset($_POST['change_password'])) {
        // Change password
        $new_password = strip_tags($_POST['new_password']);
        $confirm_password = strip_tags($_POST['confirm_password']);
        
        if ($new_password !== $confirm_password) {
            $error = "Passwords do not match";
        } else {
            $password = md5(md5($salt . md5($new_password)) . $salt);
            try {
                $result = sql($DBH, "UPDATE tbl_user SET password = ? WHERE id = ?", 
                             [$password, $teacher_id], "count");
                
                if ($result > 0) {
                    $success = "Password changed successfully";
                } else {
                    $error = "Failed to change password";
                }
            } catch (Exception $e) {
                $error = "Error changing password: " . $e->getMessage();
            }
        }
    }
}

// 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>Edit Teacher - 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);
    }
    
    /* 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;
    }
    
    /* Warning text */
    .warning-text {
      color: #dc3545;
      font-weight: 600;
    }
    
    /* Password mismatch */
    .pass-mismatch {
      color: #dc3545;
      display: none;
      font-size: 0.875rem;
      margin-top: 0.25rem;
    }
    
    /* 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;
    }
    
    /* Nav tabs */
    .nav-tabs .nav-link {
      color: var(--dark-blue);
      font-weight: 600;
      border: none;
      padding: 0.75rem 1.5rem;
    }
    
    .nav-tabs .nav-link.active {
      color: var(--primary-blue);
      border-bottom: 3px solid var(--primary-blue);
      background-color: transparent;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
      .card-body {
        padding: 1.5rem;
      }
      
      .admin-info {
        padding: 6px 10px;
      }
      
      .admin-name, .admin-access {
        font-size: 0.8rem;
      }
    }
  </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" href="post_subjects.php">
            <i class="fas fa-fw fa-book"></i>
            Create Subjects
          </a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" 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 Teacher</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>

      <!-- 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="teachers.php">Manage Teachers</a></li>
            <li class="breadcrumb-item active">Edit Teacher</li>
          </ol>
        </nav>
      </div>

      <!-- Error Message -->
      <?php if (!empty($error)): ?>
      <div class="alert alert-danger mb-4">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
      </div>
      <?php endif; ?>
      
      <!-- Success Message -->
      <?php if (!empty($success)): ?>
      <div class="alert alert-success mb-4">
        <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success); ?>
      </div>
      <?php endif; ?>

      <!-- Edit Teacher Card -->
      <div class="card shadow mb-4">
        <div class="card-header py-3">
          <h6 class="m-0 font-weight-bold">Edit Teacher: <?php echo htmlspecialchars($teacher['fullname']); ?></h6>
        </div>
        <div class="card-body">
          <ul class="nav nav-tabs mb-4" id="teacherTabs" role="tablist">
            <li class="nav-item" role="presentation">
              <button class="nav-link active" id="info-tab" data-bs-toggle="tab" data-bs-target="#info-tab-pane" type="button" role="tab">
                <i class="fas fa-user-edit me-2"></i>Teacher Information
              </button>
            </li>
            <li class="nav-item" role="presentation">
              <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password-tab-pane" type="button" role="tab">
                <i class="fas fa-key me-2"></i>Change Password
              </button>
            </li>
          </ul>
          
          <div class="tab-content" id="teacherTabsContent">
            <!-- Teacher Information Tab -->
            <div class="tab-pane fade show active" id="info-tab-pane" role="tabpanel" aria-labelledby="info-tab">
              <form method="post" class="form-horizontal">
                <div class="row mb-4">
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">Full Name <span class="text-danger">*</span></label>
                      <input type="text" name="fullname" class="form-control" 
                             value="<?php echo htmlspecialchars($teacher['fullname']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                      <label class="form-label">Email <span class="text-danger">*</span></label>
                      <input type="email" name="email" class="form-control" 
                             value="<?php echo htmlspecialchars($teacher['email']); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                      <label class="form-label">Phone Number</label>
                      <input type="tel" name="phone" class="form-control" 
                             value="<?php echo htmlspecialchars($teacher['phone']); ?>">
                    </div>
                  </div>
                  
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">Gender <span class="text-danger">*</span></label>
                      <select name="gender" class="form-select" required>
                        <option value="MALE" <?php echo ($teacher['gender'] == 'MALE') ? 'selected' : ''; ?>>MALE</option>
                        <option value="FEMALE" <?php echo ($teacher['gender'] == 'FEMALE') ? 'selected' : ''; ?>>FEMALE</option>
                      </select>
                    </div>
                    
                    <div class="mb-3">
                      <label class="form-label">Class <span class="text-danger">*</span></label>
                      <select name="class" class="form-select" required>
                        <option value="">Select Class</option>
                        <?php
                        $rows1 = sql($DBH, "SELECT * FROM tbl_class WHERE id >= ?", [1], "rows");
                        foreach($rows1 as $row1) {
                            $selected = ($row1['class'] == $teacher['class']) ? 'selected' : '';
                            echo "<option value='{$row1['class']}' $selected>{$row1['class']}</option>";
                        }
                        ?>
                      </select>
                    </div>
                    
                    <div class="mb-3">
                      <label class="form-label">Sub-Class <span class="text-danger">*</span></label>
                      <select name="subclass" class="form-select" required>
                        <option value="">Select Sub-Class</option>
                        <?php
                        $rows1 = sql($DBH, "SELECT * FROM tbl_class WHERE id >= ?", [1], "rows");
                        foreach($rows1 as $row1) {
                            $selected = ($row1['subclass'] == $teacher['subclass']) ? 'selected' : '';
                            echo "<option value='{$row1['subclass']}' $selected>{$row1['subclass']}</option>";
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div class="row mb-4">
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">Subject</label>
                      <select name="subject" class="form-select">
                        <option value="ALL">ALL...</option>
                        <?php
                        $rows1 = sql($DBH, "SELECT * FROM tbl_subject WHERE id >= ?", [1], "rows");
                        foreach($rows1 as $row1) {
                            $selected = ($row1['subject'] == $teacher['subject']) ? 'selected' : '';
                            echo "<option value='{$row1['subject']}' $selected>{$row1['subject']}</option>";
                        }
                        ?>
                      </select>
                    </div>
                  </div>
                </div>
                
                <div class="row">
                  <div class="col-12 text-center">
                    <button type="submit" name="update_info" class="btn btn-primary btn-lg px-5 py-3 me-3">
                      <i class="fas fa-save me-2"></i>Save Changes
                    </button>
                    <a href="teachers.php" class="btn btn-outline-secondary btn-lg px-5 py-3">
                      <i class="fas fa-times me-2"></i>Cancel
                    </a>
                  </div>
                </div>
              </form>
            </div>
            
            <!-- Change Password Tab -->
            <div class="tab-pane fade" id="password-tab-pane" role="tabpanel" aria-labelledby="password-tab">
              <form method="post" class="form-horizontal">
                <div class="row mb-4">
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">New Password <span class="text-danger">*</span></label>
                      <input type="password" name="new_password" class="form-control" placeholder="Enter new password" required>
                    </div>
                  </div>
                  
                  <div class="col-md-6">
                    <div class="mb-3">
                      <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                      <input type="password" name="confirm_password" class="form-control" placeholder="Confirm new password" required>
                      <div class="pass-mismatch">
                        <i class="fas fa-exclamation-circle me-1"></i>Passwords do not match!
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="alert alert-warning mb-4">
                  <i class="fas fa-exclamation-triangle me-2"></i>
                  <strong>Important:</strong> Changing the password will immediately update the teacher's login credentials.
                </div>
                
                <div class="row">
                  <div class="col-12 text-center">
                    <button type="submit" name="change_password" class="btn btn-primary btn-lg px-5 py-3 me-3">
                      <i class="fas fa-key me-2"></i>Change Password
                    </button>
                    <a href="teachers.php" class="btn btn-outline-secondary btn-lg px-5 py-3">
                      <i class="fas fa-times me-2"></i>Cancel
                    </a>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </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; 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');
    });
    
    // Password match validation
    $(document).ready(function() {
        $(".pass-mismatch").hide();
        
        $("input[name='confirm_password']").on('input', function() {
            var p1 = $("input[name='new_password']").val();
            var p2 = $(this).val();
            
            if(p1 !== p2 && p2.length > 0) {
                $(".pass-mismatch").slideDown();
                $(this).addClass('is-invalid');
            } else {
                $(".pass-mismatch").slideUp();
                $(this).removeClass('is-invalid');
            }
        });
        
        $("form").submit(function(e) {
            if ($(this).find("input[name='new_password']").length > 0) {
                var p1 = $("input[name='new_password']").val();
                var p2 = $("input[name='confirm_password']").val();
                
                if(p1 !== p2) {
                    $(".pass-mismatch").slideDown();
                    $("input[name='confirm_password']").addClass('is-invalid');
                    e.preventDefault();
                }
            }
        });
    });
  </script>
</body>
</html>