<?php

session_start();

include 'config/db.php';

$message = "";

if(isset($_POST['login']))
{
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    $sql = "SELECT * FROM users WHERE email=?";

    $stmt =
    mysqli_prepare($conn,$sql);

    mysqli_stmt_bind_param($stmt,"s",$email);

    mysqli_stmt_execute($stmt);

    $result =
    mysqli_stmt_get_result($stmt);

    if(mysqli_num_rows($result)>0)
    {
        $row =
        mysqli_fetch_assoc($result);

        if(password_verify(
            $password,
            $row['password']
        ))
        {
            session_regenerate_id(true);

            $_SESSION['user_id']
            = $row['id'];

            $_SESSION['email']
            = $row['email'];

            $_SESSION['fullname']
            = $row['fullname'];

            $_SESSION['role']
            = $row['role'];

            $_SESSION['zone_name'] = $row['zone_name'];

            header(
            "Location: dashboard.php");

            exit();
        }
        else
        {
            $message =
            "Invalid Password";
        }
    }
    else
    {
        $message =
        "Invalid Username";
    }
}
?>

<?php include 'includes/header.php'; ?>

    <div class="container">

    <div class="row
    justify-content-center
    align-items-center"
    style="height:100vh;">

    <div class="col-md-5">

    <div class="card shadow">

    <div class="card-body p-4">

    <h2 class="text-center mb-4">

    School Survey System

    </h2>

    <?php
    if($message!="")
    {
    ?>
    <div class="alert alert-danger">
    <?= $message ?>
    </div>
    <?php
    }
    ?>

    <form method="POST">

    <div class="mb-3">

    <label>Email Address</label>

    <input type="email"
    name="email"
    class="form-control"
    required>

    </div>

    <div class="mb-3">

    <label>
    Password
    </label>

    <input
    type="password"
    name="password"
    class="form-control"
    required>

    </div>

    <button
    type="submit"
    name="login"
    class="btn btn-primary
    w-100">

    Login

    </button>

    <a href="forgot_password.php">
        Forgot Password?
    </a>

    <div class="text-center mt-3">

    <a href="register.php">

    Create New Account

    </a>

    </div>

</form>

</div>

</div>

</div>

</div>

</div>

<?php include 'includes/footer.php'; ?>