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

require_once("auth/db.php");

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';

if ($action && $id) {
    // Fetch the user
    $user = $conn->query("SELECT * FROM users WHERE id = '$id' LIMIT 1")->fetch_assoc();

    if ($user) {
        if ($action === 'freeze') {
            $conn->query("UPDATE users SET is_frozen = 1, status = 'frozen' WHERE id = '$id'");
        }
        elseif ($action === 'unfreeze') {
            $conn->query("UPDATE users SET is_frozen = 0, status = 'active' WHERE id = '$id'");
        }
        elseif ($action === 'delete') {
            // Move to archived_users before deleting
            $stmt = $conn->prepare("
                INSERT INTO archived_users 
                (id, first_name, middle_name, surname, dob, country, email, password,
                 referred_by, kyc_status, gov_id_path, face_photo_path, created_at,
                 task_balance, mining_balance, phone, face_capture_path,
                 mining_start_time, last_mining_update, referral_balance, status, is_frozen) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param(
                "isssssssssssddsssssssi",
                $user['id'],
                $user['first_name'],
                $user['middle_name'],
                $user['surname'],
                $user['dob'],
                $user['country'],
                $user['email'],
                $user['password'],
                $user['referred_by'],
                $user['kyc_status'],
                $user['gov_id_path'],
                $user['face_photo_path'],
                $user['created_at'],
                $user['task_balance'],
                $user['mining_balance'],
                $user['phone'],
                $user['face_capture_path'],
                $user['mining_start_time'],
                $user['last_mining_update'],
                $user['referral_balance'],
                $user['status'],
                $user['is_frozen']
            );
            $stmt->execute();

            // Delete from main table
            $conn->query("DELETE FROM users WHERE id = '$id'");
        }
    }
}

header("Location: admin-dashboard.php");
exit();