<?php
session_start(); // Start session at the beginning of the script

include_once 'connect.php'; // Database connection file

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $emis_code = $_POST['emis_code'];
    $password = $_POST['password'];

    // Fetch the user's hashed password and school name from the database
    $query = $conn->prepare("SELECT password, school_name FROM registrations WHERE emis_code = ?");
    $query->bind_param("s", $emis_code);
    $query->execute();
    $query->store_result();
    
    if ($query->num_rows > 0) {
        $query->bind_result($hashed_password, $school_name);
        $query->fetch();

        // Verify the entered password with the hashed password
        if (password_verify($password, $hashed_password)) {
            // Store school name in session
            $_SESSION['school_name'] = $school_name;
            $query->close();
            $conn->close();
            header("Location: dashboard_school.php");
            exit();
        } else {
            echo "<script>alert('Incorrect password!');</script>";
        }
    } else {
        echo "<script>alert('EMIS Code not found!');</script>";
    }

    $query->close();
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
<!--    <link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">-->
	
    <link rel="stylesheet" href="login.css">
    <link href="css/boxicons.min.css" rel="stylesheet" type="text/css">
	<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">

</head>
<body>
    <div class="wrapper">
        <form action="login.php" method="post">
            <h1>LOGIN</h1>
            <div class="input-box">
                <input type="text" name="emis_code" placeholder="Enter School EMIS Code" required>
                <box-icon type="solid" name="user"></box-icon>
            </div>
            <div class="input-box">
                <input type="password" name="password" placeholder="Enter Password" required>
                <box-icon type="solid" name="lock-alt"></box-icon>
            </div>
            <div class="remember-forget">
                <label><input type="checkbox">Remember me</label>
                <a href="#">Forgot Password?</a>
            </div>
            <button type="submit" class="btn">Login</button> <br> <br>
            <button type="button" class="btn" onclick="resetForm()">Reset</button> <br> <br>
            <button type="button" class="btn" onclick="cancelRegistration()">Cancel</button>
            <div class="register-link">
                <p>Don't have an account? <a href="register.php">Register</a></p>
            </div>
        </form>
    </div>
</body>
</html>
