<?php
session_start();

if (isset($_POST['pids'])) {
    if (isset($_SESSION['token'])) {
        $token = $_SESSION['token'];
        $pids = json_decode($_POST['pids'], true); // Decode JSON array of PIDs

        // Ensure $pids is an array
        if (is_array($pids) && !empty($pids)) {
            // Load API endpoints
            $jsonFilePath = __DIR__ . '/../urls/api_endpoints.json';
            $jsonData = file_get_contents($jsonFilePath);
            $endpoints = json_decode($jsonData, true);

            if (isset($endpoints['delete_user'])) {
                // Process each PID
                foreach ($pids as $pid) {
                    $url = $endpoints['delete_user'] . $pid;

                    $headers = [
                        "Authorization: Bearer $token",
                    ];

                    $options = [
                        'http' => [
                            'header'  => implode("\r\n", $headers),
                            'method'  => 'DELETE',
                            'ignore_errors' => true
                        ],
                        'ssl' => [
                            'verify_peer' => false,
                            'verify_peer_name' => false
                        ]
                    ];

                    $context = stream_context_create($options);
                    $response = file_get_contents($url, false, $context);

                    if ($response === false) {
                        $message = '<div class="message error">Failed to delete some users</div>';
                        echo '<link rel="stylesheet" type="text/css" href="../css/message.css">' . $message;
                        exit;
                    }
                }

                // Success message with styling
                $message = '<div class="message success">Users deleted successfully</div>';
                echo '<link rel="stylesheet" type="text/css" href="../css/message.css">' . $message;
                
                // Adding a delay before redirecting
                header("Refresh: 3; url=userlist.php");
                exit;
            } 
        } 
    } 
} 
?>
