<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) { mkdir(dirname(__DIR__) . '/session_data/super', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);

include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName    = $stResult['term_name'];

include('includes/flash.php');
require_once 'vendor/autoload.php';

  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\Exception;
  use Dotenv\Dotenv;

  require 'phpmailer/src/Exception.php';
  require 'phpmailer/src/PHPMailer.php';
  require 'phpmailer/src/SMTP.php';

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

$school_name = $_ENV['SCHOOL_NAME'];
$school_address = $_ENV['SCHOOL_ADDRESS'];
$prefix = strtoupper($_ENV['Admission_prefix']);
$site = $_ENV['BASE_URL'];

if (isset($_POST['submit'])) {
  // Default password generation
  $default_password = $prefix . "1234";
  $hashed_password = password_hash($default_password, PASSWORD_DEFAULT);

  // Collect form data
  $name = $_POST['name'];
  $lastname = $_POST['lastname'];
  $username = $_POST['username'];
  $email = $_POST['email'];
  $permission = $_POST['permission'];
  $sex = $_POST['sex'];
  $mobile = $_POST['mobile'];
  $title = $_POST['title'];
  $status = 2;

  // Insert into database
  $sql = "INSERT INTO tblusers(name, username, email, password, status, mobile, sex, lastname, permission,title)
            VALUES(:name, :username, :email, :password, :status, :mobile, :sex, :lastname, :permission, :title)";
  $query = $dbh->prepare($sql);
  $query->bindParam(':name', $name, PDO::PARAM_STR);
  $query->bindParam(':lastname', $lastname, PDO::PARAM_STR);
  $query->bindParam(':sex', $sex, PDO::PARAM_STR);
  $query->bindParam(':mobile', $mobile, PDO::PARAM_STR);
  $query->bindParam(':status', $status, PDO::PARAM_STR);
  $query->bindParam(':username', $username, PDO::PARAM_STR);
  $query->bindParam(':email', $email, PDO::PARAM_STR);
  $query->bindParam(':permission', $permission, PDO::PARAM_STR);
  $query->bindParam(':password', $hashed_password, PDO::PARAM_STR);
  $query->bindParam(':title', $title, PDO::PARAM_STR);
  $query->execute();
  $lastInsertId = $dbh->lastInsertId();

  if ($lastInsertId) {
    // Send Email
    try {
      $mail = new PHPMailer(true);
      $mail->isSMTP();
      $mail->Host       = $_ENV['SMTP_HOST'];
      $mail->SMTPAuth   = true;
      $mail->Username   = $_ENV['SMTP_NO_REPLY'];
      $mail->Password   = $_ENV['SMTP_NO_REPLY_PASSWORD'];
      $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
      $mail->Port       = $_ENV['SMTP_PORT'];
      $mail->Timeout = 10;

      $mail->setFrom($_ENV['SMTP_NO_REPLY'], $_ENV['SCHOOL_NAME']);
      $mail->addAddress($email, "$name $lastname");
      $mail->isHTML(true);
      $mail->Subject = "$school_name - Teacher Account Created";

      $mail->Body = "
            <html>
            <body>
                <div style='max-width: 600px; margin: auto; font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
                    <h1 style='color: #ffffff; text-align: center; padding: 10px 0; background-color: #4CAF50;'>Account Created</h1>
                    <p>Dear $title. $name $lastname,</p>
                    <p>We are pleased to inform you that your teacher account has been successfully created with <strong>$school_name</strong>.</p>
                    <hr>
                    <h5>Account Details</h5>
                    <hr>
                    <p><strong>Username:</strong> $username</p>
                    <p><strong>Default Password:</strong> $default_password</p>
                    <p><strong>Permission:</strong> $permission</p>
                    <p>Please login to your teacher portal using the button below. Make sure to <strong>change your password</strong> immediately after your first login.</p>

                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='$site/portal/teacher.php' style='display: inline-block; background-color: #4CAF50; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px;'>Login Now</a>
                    </div>

                    <p>If you need any assistance, feel free to contact the school admin.</p>
                    <hr>
                    <center>
                        <p>$school_name &copy; " . date("Y") . ". All Rights Reserved.</p>
                    </center>
                </div>
            </body>
            </html>";

      $mail->send();
      flash_alert('Teacher registered successfully. Email sent. Default password: ' . $default_password);
    } catch (Exception $e) {
      flash_alert('Teacher registered but email not sent. Error: ' . $mail->ErrorInfo);
    }

    header('Location: add_teacher.php'); exit;
  } else {
    flash_alert('Something went wrong. Please try again');
  }
}
?>




<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>

<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <!-- Navbar -->
    <?php @include("includes/header.php"); ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php @include("includes/sidebar.php"); ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
<section class="content-header premium-header">
    <div class="container-fluid">
        <div class="header-glass-card">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="title-section">
                        <div class="icon-box bg-primary-gradient shadow-sm">
                            <i class="fas fa-user-tie"></i>
                        </div>
                        <div>
                            <h1 class="premium-title text-primary">
                                Teacher Information Management
                                <span class="premium-subtitle text-secondary">Manage Teacher</span>
                            </h1>
                            <div class="mt-1">
                              <?php if ($currentSessionName): ?>
                                <span class="badge badge-primary mr-1">
                                  <i class="fas fa-calendar-alt"></i>
                                  <?= htmlspecialchars($currentSessionName) ?>
                                </span>
                              <?php endif; ?>
                              <?php if ($currentTermName): ?>
                                <span class="badge badge-success">
                                  <i class="fas fa-bookmark"></i>
                                  <?= htmlspecialchars($currentTermName) ?>
                                </span>
                              <?php else: ?>
                                <span class="badge badge-warning">
                                  <i class="fas fa-exclamation-triangle"></i> No active term
                                </span>
                              <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb premium-breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php" class="text-primary">Home</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Add Teacher</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</section>      
      


      <!-- Main content -->
      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">
          <div class="row ">
            <div class="col-md-12">
              <!-- general form elements -->
              <div class="card card-primary">
                <div class="card-header">
                  <h5 class="card-title font-weight-bold"><i class="fas fa-user-tie"></i> Add New Teacher</h5>
                </div>
                <!-- /.card-header -->
                <!-- form start -->

                <form role="form" id="" method="post" enctype="multipart/form-data" class="form-horizontal">
                  <div class="card-body">
                    <div class="row">
                      <div class="form-group col-md-6">
                        <label class="" for="register1-email">Title</label>
                        <select name="title" id="title" class="form-control" required>
                          <option value="">---Select Title---</option>
                          <option value="Mr">Mr</option>
                          <option value="Mrs">Mrs</option>
                          <option value="Miss">Miss</option>
                          <option value="Ms">Ms</option>
                          <option value="Master">Master</option>
                          <option value="Madam">Madam</option>
                        </select>
                      </div>                      
                      <div class="form-group col-md-6">
                        <label for="feFirstName">First Name</label>
                        <input type="text" name="name" class="form-control" placeholder="First Name" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label for="feLastName">Last Name</label>
                        <input type="text" name="lastname" class="form-control" placeholder="Last Name" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label for="feLastName">Username</label>
                        <input type="text" name="username" class="form-control" placeholder="Username" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" name="email" class="form-control" placeholder="Enter email" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label for="exampleInputEmail1">Mobile No.</label>
                        <input type="text" name="mobile" class="form-control" placeholder="Enter mobile" required>
                      </div>
                      <div class="form-group col-md-6">
                        <label class="" for="register1-email">Gender</label>
                        <select name="sex" id="sex" class="form-control" required>
                          <option value="">---Select Gender---</option>
                          <option value="Male">Male</option>
                          <option value="Female">Female</option>
                        </select>
                      </div>
                      <div class="form-group col-md-6">
                        <label class="" for="register1-email">Permission</label>
                        <input type="text" name="permission" id="permission" class="form-control" placeholder="permission" value="Teacher" required Readonly>

                      </div>
                    </div>
                    <div class="form-group text-center">
                      <button type="submit" name="submit" class="btn btn-primary"><i class="fas fa-check-circle"></i> Submit</button>
                    </div>

                  </div>
                  <!-- /.card-body -->

                </form>
              </div>
              <!-- /.card -->
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->
        </div>
        <!-- /.container-fluid -->
      </section>
      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php @include("includes/footer.php"); ?>

  </div>
  <script>
    // In your Javascript (external .js resource or <script> tag)
    $(document).ready(function() {

      $('#sex,#title').select2();

    });
  </script>
  <!-- ./wrapper -->
  <?php @include("includes/foot.php"); ?>
</body>

</html>
