<?php
// authenticate.php — validates login credentials

session_name('mhp_purchasing_session');
session_start();
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit;
}

$site_id  = 'site1';
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';

if ($username === '' || $password === '') {
    header('Location: login.php?error=1');
    exit;
}

// ------------------------------------------------------------
// NOTE: passwords should be stored as bcrypt hashes.
// If your passwords are currently plain-text, run a one-time
// migration: UPDATE users SET password = PASSWORD_HASH(password, PASSWORD_BCRYPT)
// Then switch the check below to: password_verify($password, $user['password'])
// ------------------------------------------------------------
$stmt = $pdo->prepare(
    "SELECT id, password FROM users
     WHERE username = :username
       AND site_id  = :site_id
     LIMIT 1"
);
$stmt->execute([':username' => $username, ':site_id' => $site_id]);
$user = $stmt->fetch();

// Support both plain-text (legacy) and hashed passwords
$authenticated = false;
if ($user) {
    if (password_verify($password, $user['password'])) {
        $authenticated = true;          // bcrypt hash
    } elseif ($user['password'] === $password) {
        $authenticated = true;          // plain-text fallback (migrate ASAP)
    }
}

if ($authenticated) {
    session_regenerate_id(true);        // prevent session fixation
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['LAST_ACTIVITY'] = time();
    header('Location: transaction_details.php');
    exit;
}

header('Location: login.php?error=1');
exit;
