<?php
session_name('super_admin_session');
error_reporting(0);
include('includes/dbconnection.php');
include('includes/flash.php');

$tid = isset($_POST['edit_id']) ? intval($_POST['edit_id']) : 0;

require_once 'vendor/autoload.php';


use Dotenv\Dotenv;

// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$prefix = strtoupper($_ENV['Admission_prefix']);
$pass = $prefix . "1234";


// Update basic info
if (isset($_POST['update_teacher'])) {
  $tid = intval($_POST['teacher_id']);
  $firstname = $_POST['firstname'];
  $lastname = $_POST['lastname'];
  $username = $_POST['username'];
  $email = $_POST['email'];
  $mobile = $_POST['mobile'];
  $title = $_POST['title'];


  mysqli_query($con, "UPDATE tblusers SET name='$firstname', lastname='$lastname', username='$username', email='$email', mobile='$mobile', title = '$title' WHERE id='$tid'");
  echo "<script>alert('Teacher information updated successfully.');window.location.href='teacher_list.php';</script>"; exit;
}


// Update profile image
if (isset($_POST['update_image'])) {
  $tid = intval($_POST['teacher_id']);
  $imageName = $_FILES["teacher_image"]["name"];
  move_uploaded_file($_FILES["teacher_image"]["tmp_name"], "staff_images/" . $imageName);
  mysqli_query($con, "UPDATE tblusers SET userimage='$imageName' WHERE id='$tid'");
  echo "<script>alert('Profile image updated successfully.');window.location.href='teacher_list.php';</script>"; exit;
}


// Reset password
if (isset($_POST['reset_password'])) {
  $tid = intval($_POST['teacher_id']);
  $newPassword = password_hash($pass, PASSWORD_BCRYPT);
  mysqli_query($con, "UPDATE tblusers SET password='$newPassword' WHERE id='$tid'");
  echo "<script>alert('Password reset to default successfully.');window.location.href='teacher_list.php';</script>"; exit;
}


// Delete assignment
if (isset($_POST['delete_assignment'])) {
  $assignment_id = $_POST['assignment_id'];
  mysqli_query($con, "DELETE FROM teacher_assignments WHERE id='$assignment_id'");
  echo "<script>alert('Assignment deleted successfully.');window.location.href='teacher_list.php';</script>"; exit;
}

// Add assignment
if (isset($_POST['add_assignment_ajax'])) {
  $teacher_id = intval($_POST['teacher_id']);
  $class = trim($_POST['class']);
  $section = trim($_POST['section']);
  $subject_ids = $_POST['subject_ids'] ?? [];
  $class_teacher_class_id = $_POST['class_id'];

  // Get class_section ID for subject assignment
  $classQuery = mysqli_query($con, "SELECT id, class, section FROM class_section 
                                    WHERE class='$class' AND section='$section' LIMIT 1");
  $classRow = mysqli_fetch_assoc($classQuery);
  $subject_class_id = $classRow['id'] ?? null;
  $subject_class_name = $classRow ? $classRow['class'] . ' ' . $classRow['section'] : 'Unknown';

  // ✅ Assign subject(s)
  if ($subject_class_id && !empty($subject_ids)) {
    foreach ($subject_ids as $subject_id) {
      // Get subject name
      $subjectQuery = mysqli_query($con, "SELECT Subject_name FROM subjectcombination 
                                          WHERE id = '$subject_id' LIMIT 1");
      $subjectData = mysqli_fetch_assoc($subjectQuery);
      $subject_name = $subjectData['Subject_name'] ?? 'Unknown Subject';

      // Check if assigned to another teacher
      $check = mysqli_query($con, "SELECT * FROM teacher_assignments 
                                   WHERE subject_id='$subject_id' AND class_id='$subject_class_id' 
                                   AND teacher_id != '$teacher_id'");
      if (mysqli_num_rows($check) > 0) {
        echo "<script>alert('The subject \\\"$subject_name\\\" is already assigned to another teacher for $subject_class_name.');window.location.href='teacher_list.php';</script>"; exit;
        exit();
      }

      // Skip duplicates
      $exists = mysqli_query($con, "SELECT * FROM teacher_assignments 
                                    WHERE subject_id='$subject_id' AND class_id='$subject_class_id' 
                                    AND teacher_id='$teacher_id'");
      if (mysqli_num_rows($exists) == 0) {
        mysqli_query($con, "INSERT INTO teacher_assignments (teacher_id, subject_id, class_id, is_class_teacher) 
                            VALUES ('$teacher_id', '$subject_id', '$subject_class_id', 0)");
      }
    }
    echo "<script>alert('Subject(s) assigned successfully.');window.location.href='teacher_list.php';</script>"; exit;
  }

  // ✅ Assign as class teacher (optional)
  if (!empty($class_teacher_class_id)) {
    // Get class name
    $classQuery = mysqli_query($con, "SELECT class, section FROM class_section WHERE id = '$class_teacher_class_id' LIMIT 1");
    $classData = mysqli_fetch_assoc($classQuery);
    $class_name = $classData ? $classData['class'] . ' ' . $classData['section'] : 'Unknown';

    // ❌ Check if another teacher is already class teacher for this class
    $checkCT = mysqli_query($con, "SELECT * FROM teacher_assignments 
                                   WHERE class_id='$class_teacher_class_id' AND subject_id IS NULL 
                                   AND teacher_id != '$teacher_id' AND is_class_teacher = 1");
    if (mysqli_num_rows($checkCT) > 0) {
      echo "<script>alert('Another teacher is already assigned as class teacher for $class_name.');window.location.href='teacher_list.php';</script>"; exit;
      exit();
    }

    // ❌ Check if this teacher is already a class teacher elsewhere
    $checkAlreadyCT = mysqli_query($con, "SELECT class_id FROM teacher_assignments 
                                          WHERE teacher_id='$teacher_id' AND is_class_teacher = 1 
                                          AND subject_id IS NULL AND class_id != '$class_teacher_class_id'");
    if (mysqli_num_rows($checkAlreadyCT) > 0) {
      echo "<script>alert('This teacher is already a class teacher for another class. A teacher can only be assigned to one class as class teacher.');window.location.href='teacher_list.php';</script>"; exit;
      exit();
    }

    // ✅ Assign or update
    $existing = mysqli_query($con, "SELECT * FROM teacher_assignments 
                                    WHERE teacher_id='$teacher_id' AND class_id='$class_teacher_class_id' 
                                    AND subject_id IS NULL");
    if (mysqli_num_rows($existing) > 0) {
      mysqli_query($con, "UPDATE teacher_assignments SET is_class_teacher=1 
                          WHERE teacher_id='$teacher_id' AND class_id='$class_teacher_class_id' 
                          AND subject_id IS NULL");
      echo "<script>alert('Updated class teacher assignment for $class_name.');window.location.href='teacher_list.php';</script>"; exit;
    } else {
      mysqli_query($con, "INSERT INTO teacher_assignments (teacher_id, subject_id, class_id, is_class_teacher) 
                          VALUES ('$teacher_id', NULL, '$class_teacher_class_id', 1)");
      echo "<script>alert('Assigned as class teacher for $class_name.');window.location.href='teacher_list.php';</script>"; exit;
    }
    exit();
  }
}




$classes = [];
$res_classlist = mysqli_query($con, "SELECT * FROM class_section ORDER BY class, section");
while ($cl = mysqli_fetch_assoc($res_classlist)) {
  $classes[] = $cl;
}



// Load data
if (isset($_POST['edit_id'])) {
  $tid = intval($_POST['edit_id']);
  $teacher_id = $tid;
  $result = mysqli_query($con, "SELECT * FROM tblusers WHERE id='$tid'");
  $row = mysqli_fetch_array($result);

  // Fetch all current assignments (use subjectcombination for class & section)
  $assignment_list = mysqli_query($con, "
  SELECT 
    ta.id, 
    s.Subject_name, 
    s.Class AS sub_class, 
    s.section AS sub_section,
    cs.class AS class_class, 
    cs.section AS class_section,
    ta.is_class_teacher
  FROM teacher_assignments ta
  LEFT JOIN subjectcombination s ON ta.subject_id = s.id
  LEFT JOIN class_section cs ON ta.class_id = cs.id
  WHERE ta.teacher_id = '$tid'
");


  // Fetch options
  $subject_options = mysqli_query($con, "SELECT id, Subject_name FROM subjectcombination");
  $class_options = mysqli_query($con, "SELECT id, class, section FROM class_section");
?>

  <div class="card card-primary card-outline">
    <div class="card-body">
      <div class="row">
        <div class="col-md-3 text-center">
          <img class="img-circle" src="staff_images/<?php echo $row['userimage']; ?>" width="150" height="150" alt="Teacher Image">
          <h5 class="mt-2"><?php echo $row['name'] . ' ' . $row['lastname']; ?></h5>
          <p class="text-muted"><?php echo $row['email']; ?></p>
        </div>

        <div class="col-md-9">
          <div class="card">
            <div class="card-header p-2">
              <ul class="nav nav-pills">
                <li class="nav-item"><a class="nav-link active" href="#basic" data-toggle="tab">Basic Info</a></li>
                <li class="nav-item"><a class="nav-link" href="#photo" data-toggle="tab">Update Image</a></li>
                <li class="nav-item"><a class="nav-link" href="#reset" data-toggle="tab">Reset Password</a></li>
                <li class="nav-item"><a class="nav-link" href="#assignments" data-toggle="tab">Assignments</a></li>
              </ul>
            </div>

            <div class="card-body">
              <div class="tab-content">
                <!-- Basic Info -->
                <div class="tab-pane active" id="basic">
                  <form method="post">
                    <div class="form-group row">
                    <div class="col-md-6">
                      <label>Title</label>
                      <input type="text" name="title" class="form-control" value="<?php echo $row['title']; ?>" required>
                    </div>                      
                    <div class="col-md-6">
                        <input type="hidden" name="teacher_id" value="<?php echo $tid; ?>">
                        <label>First Name</label>
                        <input type="text" name="firstname" class="form-control" value="<?php echo $row['name']; ?>" required>
                      </div>
                      <div class="col-md-6">
                        <label>Last Name</label>
                        <input type="text" name="lastname" class="form-control" value="<?php echo $row['lastname']; ?>" required>
                      </div>
                      <div class="col-md-6">
                        <label>Username</label>
                        <input type="text" name="username" class="form-control" value="<?php echo $row['username']; ?>" required>
                      </div>
                      <div class="col-md-6">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control" value="<?php echo $row['email']; ?>" required>
                      </div>
                    <div class="col-md-6">
                      <label>Mobile</label>
                      <input type="text" name="mobile" class="form-control" value="<?php echo $row['mobile']; ?>" required>
                    </div>
                    </div>
                    <div class="form-group text-right">
                      <button type="submit" name="update_teacher" class="btn btn-primary">Update</button>
                    </div>
                  </form>
                </div>

                <!-- Update Image -->
                <div class="tab-pane" id="photo">
                  <form method="post" enctype="multipart/form-data">
                    <div class="form-group">
                      <input type="hidden" name="teacher_id" value="<?php echo $tid; ?>">
                      <label>Choose New Profile Image</label>
                      <input type="file" name="teacher_image" class="form-control-file" required>
                    </div>
                    <div class="form-group text-right">
                      <button type="submit" name="update_image" class="btn btn-info">Update Image</button>
                    </div>
                  </form>
                </div>

                <!-- Reset Password -->
                <div class="tab-pane" id="reset">
                  <form method="post">
                    <input type="hidden" name="teacher_id" value="<?php echo $tid; ?>">
                    <p>Click the button below to reset the teacher's password to: <strong><?php echo $pass; ?></strong></p>
                    <div class="form-group text-right">
                      <button type="submit" name="reset_password" class="btn btn-danger">Reset Password</button>
                    </div>
                  </form>
                </div>

                <!-- Assignments -->
                <div class="tab-pane" id="assignments">
                  <div class="card">
                    <div class="card-header bg-secondary text-white">
                      <h5 class="card-title"><i class="fas fa-chalkboard-teacher"></i> Teaching Assignments</h5>
                    </div>
                    <div class="card-body">
<form method="post" id="assignmentForm">
  <input type="hidden" name="teacher_id" value="<?php echo $tid; ?>">

  <div class="form-row">
    <!-- Select Class -->
    <div class="form-group col-md-12">
      <label class="form-label">Class:</label>
      <select id="classSelector" name="class" class="form-control" required>
        <option value="">Select Class</option>
        <?php
        $query2 = "SELECT DISTINCT class FROM class_section ORDER BY class";
        $result2 = $con->query($query2);
        while ($row2 = $result2->fetch_assoc()) {
          echo "<option value='{$row2['class']}' data-classname='{$row2['class']}'>{$row2['class']}</option>";
        }
        ?>
      </select>
    </div>

    <!-- Select Section -->
    <div class="form-group col-md-12">
      <label class="form-label">Arm:</label>
      <select id="sectionSelector" name="section" class="form-control" required>
        <option value="">Select Arm</option>
      </select>
    </div>
  </div>

  <!-- Subject list -->
  <div class="form-group col-md-12">
    <label class="form-label">Assign as Subject Teacher (Select Subjects):</label>
    <div id="subjectContainer" class="border p-3 rounded bg-light">
      <p class="text-muted">Select a class and arm first to see subjects.</p>
    </div>
  </div>

  <!-- Assign as Class Teacher -->
  <div class="form-group col-md-12">
    <label class="form-label">Assign as Class Teacher (Optional):</label>
    <select name="class_id" class="form-control">
      <option value="">None</option>
      <?php foreach ($classes as $class): ?>
        <option value="<?= htmlspecialchars($class['id']); ?>">
          <?= htmlspecialchars("{$class['class']} - {$class['section']}"); ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="form-group text-right">
    <button type="submit" name="add_assignment_ajax" class="btn btn-primary">
      Add Assignment
    </button>
  </div>
</form>


                      <hr>
                      <h6 class="mt-4"><strong>Existing Assignments</strong></h6>
                      <table class="table table-bordered">
                        <thead>
                          <tr>
                            <th>Subject</th>
                            <th>Class</th>
                            <th>Is Class Teacher</th>
                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody>
                          <?php while ($rowa = mysqli_fetch_assoc($assignment_list)) { ?>
                            <tr>
                              <td><?php echo htmlentities($rowa['Subject_name'] ?? '-'); ?></td>
                              <?php
                              $class_display = $rowa['sub_class'] && $rowa['sub_section']
                                ? $rowa['sub_class'] . ' ' . $rowa['sub_section']
                                : $rowa['class_class'] . ' ' . $rowa['class_section'];
                              ?>
                              <td><?php echo htmlentities($class_display); ?></td>
                              <td><?php echo $rowa['is_class_teacher'] ? 'Yes' : 'No'; ?></td>
                              <td>
                                <form method="post" onsubmit="return confirm('Delete this assignment?');">
                                  <input type="hidden" name="assignment_id" value="<?php echo $rowa['id']; ?>">
                                  <button type="submit" name="delete_assignment" class="btn btn-danger btn-sm">Delete</button>
                                </form>
                              </td>
                            </tr>
                          <?php } ?>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>

              </div> <!-- tab-content -->
            </div> <!-- card-body -->
          </div> <!-- card -->
        </div> <!-- col-md-9 -->
      </div> <!-- row -->
    </div> <!-- card-body -->
  </div> <!-- card -->

<?php } ?>
<script>
  $(document).ready(function() {
    $('.select2').select2();

    $('#classSelector').change(function() {
      var selectedClassName = $(this).find(':selected').data('classname');

      if (selectedClassName) {
        $.ajax({
          url: 'fetch_sections.php',
          type: 'POST',
          data: {
            class_name: selectedClassName
          },
          success: function(response) {
            $('#sectionSelector').html(response);
          }
        });
      } else {
        $('#sectionSelector').html('<option value="">Select Arm</option>');
        $('#subjectContainer').html('<p>Select a class and arm first to see subjects.</p>');
      }
    });

    $('#sectionSelector').change(function() {
      var selectedClassName = $('#classSelector').find(':selected').data('classname');
      var selectedSection = $(this).val();

      if (selectedClassName && selectedSection) {
        $.ajax({
          url: 'fetch_subjects1.php',
          type: 'POST',
          data: {
            class_name: selectedClassName,
            section: selectedSection
          },
          success: function(response) {
            $('#subjectContainer').html(response);
          }
        });
      } else {
        $('#subjectContainer').html('<p>Select a class and arm first to see subjects.</p>');
      }
    });
  });
</script>