<?php
session_start();
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header("Location: admin-login.php");
    exit();
}
require_once("auth/db.php");

$id = $_GET['id'] ?? '';
if ($id) {
    $user = $conn->query("SELECT * FROM archived_users WHERE id='$id' LIMIT 1")->fetch_assoc();
    if ($user) {
        // Make sure balances are not null
        $mining_balance   = $user['mining_balance']   ?? 0.0000;
        $task_balance     = $user['task_balance']     ?? 0.0000;
        $referral_balance = $user['referral_balance'] ?? 0.0000;

        $stmt = $conn->prepare("
            INSERT INTO users 
            (id, first_name, middle_name, surname, email, country, dob, referred_by, created_at,
             mining_balance, task_balance, referral_balance, kyc_status, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param(
            "issssssssddsss",
            $user['id'],
            $user['first_name'],
            $user['middle_name'],
            $user['surname'],
            $user['email'],
            $user['country'],
            $user['dob'],
            $user['referred_by'],
            $user['created_at'],
            $mining_balance,
            $task_balance,
            $referral_balance,
            $user['kyc_status'],
            $user['status']
        );
        $stmt->execute();

        // Remove from archive
        $conn->query("DELETE FROM archived_users WHERE id='$id'");
    }
}
header("Location: archived-users.php");
exit();