<?php
session_start();
include '../db_connect.php';

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

    $query = $conn->prepare("SELECT id, password FROM users WHERE email = ?");
    $query->bind_param('s', $email);
    $query->execute();
    $query->store_result();

    if ($query->num_rows > 0) {
        $query->bind_result($id, $hashed_password);
        $query->fetch();

        if (password_verify($password, $hashed_password)) {
            $_SESSION['user_id'] = $id;
            setcookie('user_id', $id, time() + (86400 * 30), "/");
            header("Location: welcome.php");
            exit();
        } else {

            $_SESSION["alert-danger"] = "Invalid password.";
            header("Location: login.php");
            exit();
        }
    } else {
        $_SESSION["alert-danger"] = "No user found with that email.";
        header("Location: login.php");
        exit();
    }
    $conn->close();
    header("Location: login.php");
    exit();
} else {
    header("Location: login.php");
    exit();
}
