<?php
$id = $_GET['id'];

// JSON path
$jsonPath = 'users.json';

// Check if file exists
if (!file_exists($jsonPath)) {
    die("User data file not found.");
}

// Read user data
$data = json_decode(file_get_contents($jsonPath), true);

// Check if user exists at that index
if (isset($data['users'][$id])) {

    // Get image path
    $imagePath = $data['users'][$id]['image']; // Example: uploads/user1.jpg

    // Delete image if it exists and is inside 'uploads/' folder
    if (!empty($imagePath) && file_exists($imagePath) && strpos($imagePath, 'uploads/') === 0) {
        unlink($imagePath);
    }

    // Delete user
    unset($data['users'][$id]);

    // Re-index array
    $data['users'] = array_values($data['users']);

    // Save updated data
    file_put_contents($jsonPath, json_encode($data, JSON_PRETTY_PRINT));
}

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