<?php
session_start();
require __DIR__ . "/../db.php";

// پسورد مشترک
$SHARED_PASS = "147258";

$username = trim($_POST["username"] ?? "");
$password = trim($_POST["password"] ?? "");

if ($username === "" || mb_strlen($username) > 30 || $password !== $SHARED_PASS) {
  header("Location: /?err=1");
  exit;
}

$usernameSafe = htmlspecialchars($username, ENT_QUOTES, "UTF-8");

// اگر وجود داشت بگیر، اگر نه بساز
$stmt = $conn->prepare("SELECT id FROM users WHERE username=?");
$stmt->bind_param("s", $usernameSafe);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if (!$row) {
  $ins = $conn->prepare("INSERT INTO users (username) VALUES (?)");
  $ins->bind_param("s", $usernameSafe);
  $ins->execute();
  $userId = (int)$ins->insert_id;
} else {
  $userId = (int)$row["id"];
}


$upd = $conn->prepare("UPDATE users SET last_login = NOW() WHERE id=?");
$upd->bind_param("i", $userId);
$upd->execute();


$_SESSION["user_id"] = $userId;
header("Location: /");
