<?php
/**
 * login.php — LOGIC ONLY (used by index.php)
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);
}

$error = $error ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {

    $username = trim($_POST['member_email'] ?? '');
    $password = trim($_POST['member_password'] ?? '');

    if ($username === '' || $password === '') {
        $error = 'Username or Password is invalid';
        return;
    }

    // DB connection must exist ($connection from configuration.php)

    $stmt = mysqli_prepare(
        $connection,
        "SELECT memberid, member_email, member_password 
         FROM member 
         WHERE member_active = 1 
         AND member_email = ? 
         LIMIT 1"
    );

    if ($stmt) {

        mysqli_stmt_bind_param($stmt, 's', $username);
        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_get_result($stmt);
        $user   = mysqli_fetch_assoc($result);

        mysqli_stmt_close($stmt);

        if ($user && password_verify($password, $user['member_password'])) {

            session_regenerate_id(true);

            $_SESSION['login_member'] = $user['member_email'];
            $_SESSION['memberid']     = (int)$user['memberid'];

            header('Location: member_homepage.php');
            exit();

        } else {

            // ✅ md5 fallback (auto upgrade)
            if ($user && md5($password) === $user['member_password']) {

                $newHash = password_hash($password, PASSWORD_DEFAULT);

                $update = mysqli_prepare(
                    $connection,
                    "UPDATE member SET member_password = ? WHERE memberid = ?"
                );

                mysqli_stmt_bind_param($update, 'si', $newHash, $user['memberid']);
                mysqli_stmt_execute($update);
                mysqli_stmt_close($update);

                session_regenerate_id(true);

                $_SESSION['login_member'] = $user['member_email'];
                $_SESSION['memberid']     = (int)$user['memberid'];

                header('Location: member_homepage.php');
                exit();

            } else {
                $error = 'Invalid email or password.';
            }
        }

    } else {
        error_log('Login prepare() failed: ' . mysqli_error($connection));
        $error = 'A system error occurred. Please try again later.';
    }
}