<?php
/**
 * Delete Users API
 * Endpoint: /admin/adminapi/delete_users.php
 * Methods: POST
 * Body: { "ids": [1,2,3] } or { "all": true }
 */
require_once(__DIR__ . '/includes/db.php');
require_once(__DIR__ . '/includes/auth.php');

header('Content-Type: application/json');

// Require valid auth token
requireAuth();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        $input = $_POST;
    }

    $deleteAll = isset($input['all']) && $input['all'] === true;
    $ids = isset($input['ids']) ? $input['ids'] : [];

    if (!$deleteAll && empty($ids)) {
        echo json_encode(['success' => false, 'error' => 'No users specified for deletion']);
        exit;
    }

    if ($deleteAll) {
        // Delete all users
        $stmt = $pdo->prepare("DELETE FROM users");
        $stmt->execute();
        $deletedCount = $stmt->rowCount();
    } else {
        // Delete selected users
        $ids = array_map('intval', $ids);
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $stmt = $pdo->prepare("DELETE FROM users WHERE id IN ($placeholders)");
        $stmt->execute($ids);
        $deletedCount = $stmt->rowCount();
    }

    echo json_encode([
        'success' => true,
        'message' => $deletedCount . ' user(s) deleted successfully',
        'deleted_count' => $deletedCount
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
