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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['error'] = "CSRF Token Tidak Valid.";
        header("Location: /");
        exit();
    }

    $username = htmlspecialchars(trim($_POST['username']), ENT_QUOTES, 'UTF-8');
    $password = trim($_POST['password']);

    if (!empty($username) && !empty($password)) {
        $checkUser = "SELECT id, username, extplayer, password, status FROM user WHERE username = :username LIMIT 1";
        $stmt = $db->prepare($checkUser);
        $stmt->bindParam(':username', $username, PDO::PARAM_STR);
        $stmt->execute();

        if ($stmt->rowCount() === 1) {
            $users = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($users['status'] === 0) {
                $_SESSION['error'] = "Akun dinonaktifkan.";
                header("Location: /");
                exit();
            }

            if (password_verify($password, $users['password'])) {
                $_SESSION['user_id'] = $users['id'];
                $_SESSION['username'] = $users['username'];
                $_SESSION['extplayer'] = $users['extplayer'];
                $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
                session_regenerate_id(true);

                header("Location: /");
                exit();
            } else {
                $_SESSION['error'] = "Invalid username or password.";
                header("Location: /");
                exit();
            }
        } else {
            $_SESSION['error'] = "Invalid username or password.";
            header("Location: /");
            exit();
        }
    } else {
        $_SESSION['error'] = "Please enter both username and password.";
        header("Location: /");
        exit();
    }
}
