<?php

session_name('small_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/small')) {
  mkdir(dirname(__DIR__) . '/session_data/small', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/small');

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





use Dotenv\Dotenv;



// Load Composer dependencies

require_once 'vendor/autoload.php';

// Load environment variables

$dotenv = Dotenv::createImmutable(__DIR__);

$dotenv->load();



$school_name = $_ENV['SCHOOL_NAME'];

$school_address = $_ENV['SCHOOL_ADDRESS'];

$prefix = $_ENV['Admission_prefix'];

$logo = $_ENV['WEBSITE_LOGO'];

$logo1 = $_ENV['WEBSITE_LOGO1'];



if (isset($_POST['login'])) {

  $username = $_POST['username'];

  $password = $_POST['password'];

  $permission = 'Student Search';





  // Fetch user details

  $sql = "SELECT * FROM tblusers WHERE username=:username AND permission=:permission";

  $query = $dbh->prepare($sql);

  $query->bindParam(':username', $username, PDO::PARAM_STR);

  $query->bindParam(':permission', $permission, PDO::PARAM_STR);

  $query->execute();

  $result = $query->fetch(PDO::FETCH_OBJ);



  if ($result) {

    // Verify password (Supports MD5 & Password Hashing)

    if (password_verify($password, $result->password) || md5($password) === $result->password) {

      if ($result->status == "1") {

        // Set session variables

        $_SESSION['sid'] = $result->id;

        $_SESSION['name'] = $result->name;

        $_SESSION['lastname'] = $result->lastname;

        $_SESSION['permission'] = $result->permission;

        $_SESSION['email'] = $result->email;

        $_SESSION['login'] = $username;



        session_regenerate_id(true); // prevent session fixation and ID collision



        // Remember Me (Stores only username securely)

        if (!empty($_POST["remember"])) {

          setcookie("small_user_login", $username, time() + (10 * 365 * 24 * 60 * 60), "/");

        } else {

          setcookie("small_user_login", "", time() - 3600, "/");

        }



        // Insert login record

        $uip = $_SERVER['REMOTE_ADDR'];

        $status = 1;

        $sql = "INSERT INTO userlog(userEmail, userip, status, username, name, lastname) 

                        VALUES(:email, :uip, :status, :username, :name, :lastname)";

        $query = $dbh->prepare($sql);

        $query->bindParam(':username', $username, PDO::PARAM_STR);

        $query->bindParam(':name', $result->name, PDO::PARAM_STR);

        $query->bindParam(':lastname', $result->lastname, PDO::PARAM_STR);

        $query->bindParam(':email', $result->email, PDO::PARAM_STR);

        $query->bindParam(':uip', $uip, PDO::PARAM_STR);

        $query->bindParam(':status', $status, PDO::PARAM_INT);

        $query->execute();



        // Redirect to dashboard

        header("Location: dashboard2.php");

        exit();

      } else {

        $_SESSION['error'] = 'Your account is blocked. Contact Admin.';

        header("Location: student_search.php");

        exit();

      }

    } else {

      $_SESSION['error'] = 'Incorrect Login Credentials.';

      header("Location: student_search.php");

      exit();

    }

  } else {

    // Log failed attempt

    $uip = $_SERVER['REMOTE_ADDR'];

    $status = 0;

    $sql = "INSERT INTO userlog(userEmail, userip, status, username, name) 

                VALUES('Not registered', :uip, :status, :username, :name)";

    $query = $dbh->prepare($sql);

    $query->bindParam(':username', $username, PDO::PARAM_STR);

    $query->bindParam(':name', $username, PDO::PARAM_STR);

    $query->bindParam(':uip', $uip, PDO::PARAM_STR);

    $query->bindParam(':status', $status, PDO::PARAM_INT);

    $query->execute();



    $_SESSION['error'] = 'Incorrect Login Credentials.';

    header("Location: student_search.php");

    exit();

  }

}

?>



<!DOCTYPE html>

<html lang="en">

<head>

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

  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

  <style>
    *,
    *::before,
    *::after {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    body.login-page {
      font-family: 'Inter', sans-serif;
      background: #eef2ff;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    .login-wrapper {
      display: flex;
      width: 860px;
      max-width: 100%;
      height: 500px;
      border-radius: 24px;
      overflow: hidden;
      box-shadow: 0 25px 60px rgba(79, 70, 229, 0.18);
    }

    /* LEFT PANEL */
    .panel-left {
      flex: 1;
      position: relative;
      background: linear-gradient(160deg, #3730a3 0%, #4f46e5 55%, #7c3aed 100%);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 2rem;
      overflow: hidden;
    }

    .panel-left::before {
      content: '';
      position: absolute;
      width: 280px;
      height: 280px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.15);
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .panel-left::after {
      content: '';
      position: absolute;
      width: 180px;
      height: 180px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.1);
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .panel-left .school-logo {
      width: 72px;
      height: 72px;
      object-fit: contain;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.15);
      padding: 8px;
      margin-bottom: 1.25rem;
      position: relative;
      z-index: 2;
    }

    .panel-left .portal-label {
      color: rgba(255, 255, 255, 0.7);
      font-size: 0.7rem;
      font-weight: 600;
      letter-spacing: 0.15em;
      text-transform: uppercase;
      margin-bottom: 0.4rem;
      position: relative;
      z-index: 2;
    }

    .panel-left .portal-title {
      color: #fff;
      font-size: 1.5rem;
      font-weight: 700;
      text-align: center;
      line-height: 1.2;
      position: relative;
      z-index: 2;
    }

    .panel-left .portal-title span {
      display: block;
      font-size: 0.85rem;
      font-weight: 400;
      color: rgba(255, 255, 255, 0.65);
      margin-top: 0.4rem;
    }

    .blob {
      position: absolute;
      border-radius: 50%;
      opacity: 0.12;
    }

    .blob-1 {
      width: 120px;
      height: 120px;
      background: #a5b4fc;
      top: -30px;
      left: -30px;
    }

    .blob-2 {
      width: 80px;
      height: 80px;
      background: #c7d2fe;
      bottom: -20px;
      right: -20px;
    }

    /* RIGHT PANEL */
    .panel-right {
      width: 360px;
      background: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 2.25rem 2rem;
    }

    .form-title {
      font-size: 1.25rem;
      font-weight: 700;
      color: #1e1b4b;
      margin-bottom: 0.3rem;
    }

    .form-subtitle {
      font-size: 0.8rem;
      color: #64748b;
      margin-bottom: 1.5rem;
    }

    .field-label {
      display: block;
      font-size: 0.78rem;
      font-weight: 600;
      color: #374151;
      margin-bottom: 0.35rem;
    }

    .field-wrap {
      position: relative;
      margin-bottom: 1rem;
    }

    .field-wrap input {
      width: 100%;
      height: 42px;
      border: 1.5px solid #e2e8f0;
      border-radius: 10px;
      padding: 0 40px 0 14px;
      font-size: 0.875rem;
      color: #1e293b;
      background: #f8fafc;
      transition: border-color 0.2s, box-shadow 0.2s;
      outline: none;
    }

    .field-wrap input:focus {
      border-color: #4f46e5;
      background: #fff;
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
    }

    .field-wrap .fi {
      position: absolute;
      right: 13px;
      top: 50%;
      transform: translateY(-50%);
      color: #94a3b8;
      font-size: 0.8rem;
      cursor: pointer;
    }

    .remember-row {
      display: flex;
      align-items: center;
      gap: 7px;
      margin-bottom: 1.25rem;
      font-size: 0.78rem;
      color: #64748b;
    }

    .btn-login {
      width: 100%;
      height: 42px;
      background: linear-gradient(135deg, #3730a3 0%, #4f46e5 100%);
      color: #fff;
      border: none;
      border-radius: 10px;
      font-size: 0.875rem;
      font-weight: 600;
      cursor: pointer;
      transition: opacity 0.2s, transform 0.2s;
    }

    .btn-login:hover {
      opacity: 0.92;
      transform: translateY(-1px);
    }

    .alert-err {
      background: #fef2f2;
      color: #dc2626;
      border: 1px solid #fee2e2;
      border-radius: 8px;
      padding: 9px 12px;
      font-size: 0.78rem;
      margin-bottom: 1rem;
    }

    /* RESPONSIVE */
    @media (max-width: 680px) {
      body.login-page {
        padding: 16px;
        align-items: flex-start;
      }

      .login-wrapper {
        flex-direction: column;
        width: 100%;
        height: auto;
        border-radius: 20px;
      }

      .panel-left {
        flex: none;
        width: 100%;
        padding: 1.5rem 1.25rem;
        border-radius: 0;
      }

      .panel-left::before {
        width: 180px;
        height: 180px;
      }

      .panel-left::after {
        width: 110px;
        height: 110px;
      }

      .panel-left .school-logo {
        width: 52px;
        height: 52px;
        margin-bottom: 0.75rem;
      }

      .panel-left .portal-label {
        font-size: 0.65rem;
      }

      .panel-left .portal-title {
        font-size: 1.15rem;
      }

      .panel-left .portal-title span {
        font-size: 0.78rem;
      }

      .panel-right {
        width: 100%;
        padding: 1.75rem 1.25rem;
      }
    }
  </style>

</head>

<body class="hold-transition login-page">

  <div class="login-wrapper">

    <!-- LEFT -->
    <div class="panel-left">
      <div class="blob blob-1"></div>
      <div class="blob blob-2"></div>
      <img src="<?php echo $logo; ?>" alt="Logo" class="school-logo">
      <p class="portal-label"><?php echo $school_name; ?></p>
      <h1 class="portal-title">
        Student Search<span>Find. View. Manage.</span>
      </h1>
    </div>

    <!-- RIGHT -->
    <div class="panel-right">
      <h2 class="form-title">Sign In</h2>
      <p class="form-subtitle">Enter your credentials to access the student search portal.</p>

      <?php if (isset($_SESSION['error'])) { ?>
        <div class="alert-err">
          <i class="fas fa-exclamation-circle mr-1"></i>
          <?php echo $_SESSION['error'];
          unset($_SESSION['error']); ?>
        </div>
      <?php } ?>

      <form action="" method="post">
        <div class="field-wrap">
          <label class="field-label">Username</label>
          <input type="text" name="username" placeholder="enter your username" required
            value="<?php echo isset($_COOKIE["small_user_login"]) ? $_COOKIE["small_user_login"] : ''; ?>">
          <i class="fas fa-user-shield fi"></i>
        </div>

        <div class="field-wrap">
          <label class="field-label">Password</label>
          <input type="password" name="password" id="passwordField" placeholder="enter your password" required>
          <i class="fas fa-eye-slash fi" id="togglePassword"></i>
        </div>

        <div class="remember-row">
          <input type="checkbox" id="remember" name="remember" <?php echo isset($_COOKIE["small_user_login"]) ? 'checked' : ''; ?>>
          <label for="remember">Remember Me</label>
        </div>

        <button type="submit" name="login" class="btn-login">Sign In</button>
      </form>
    </div>

  </div>

  <script>
    document.getElementById('togglePassword').addEventListener('click', function () {
      const f = document.getElementById('passwordField');
      const show = f.type === 'password';
      f.type = show ? 'text' : 'password';
      this.classList.toggle('fa-eye', show);
      this.classList.toggle('fa-eye-slash', !show);
    });
  </script>

  <?php @include("includes/foot.php"); ?>

</body>

</html>