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

if (isset($_POST['loggin'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $remember = isset($_POST['rememberMe']); // true if checked

    $stmt = $conn->prepare("SELECT * FROM tbl_user WHERE username = ? and password = ?");
    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $result = $stmt->get_result();

if ($result->num_rows > 0) {
	if ($user = $result->fetch_assoc()) {

            echo "success";
            // ✅ Store session
            $_SESSION['role'] = $user['role_type'];
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['fname'] = $user['first_name'];
            $_SESSION['mname'] = $user['middle_name'];
            $_SESSION['lname'] = $user['last_name'];

            // ✅ If "Remember me" is checked
            if ($remember) {
                $token = bin2hex(random_bytes(32)); // random secure token
                $hashedToken = hash('sha256', $token);

                // Save hashed token in database
                $update = $conn->prepare("UPDATE tbl_user SET remember_token=? WHERE user_id=?");
                $update->bind_param("si", $hashedToken, $user['user_id']);
                $update->execute();

                // Store plain token in cookie (expires in 30 days)
                setcookie("remember_token", $token, time() + (86400 * 30), "/", "", false, true);
            }

            // header("Location: index.php");
            exit();
      
    } else {
        echo "❌ Username not found.";
    }
}
    
}
?>
