40 lines
1.5 KiB
PHP
40 lines
1.5 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/../db/config.php';
|
|
session_start();
|
|
|
|
// Security: Only Super Users can allocate credits
|
|
if (!isset($_SESSION["user_id"]) || ($_SESSION["user_role"] ?? '') !== 'Super User') {
|
|
echo json_encode(['success' => false, 'error' => 'Unauthorized access.']);
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$target_user_id = isset($_POST['user_id']) ? (int)$_POST['user_id'] : null;
|
|
$credits = isset($_POST['credits']) ? (int)$_POST['credits'] : 0;
|
|
$action = $_POST['action'] ?? 'set'; // 'set' or 'add'
|
|
|
|
if (!$target_user_id) {
|
|
echo json_encode(['success' => false, 'error' => 'User ID is required.']);
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
if ($action === 'add') {
|
|
$stmt = db()->prepare("UPDATE users SET credits = credits + ? WHERE id = ?");
|
|
$stmt->execute([$credits, $target_user_id]);
|
|
$message = "Successfully added $credits credits.";
|
|
} else {
|
|
$stmt = db()->prepare("UPDATE users SET credits = ? WHERE id = ?");
|
|
$stmt->execute([$credits, $target_user_id]);
|
|
$message = "Successfully set credits to $credits.";
|
|
}
|
|
|
|
echo json_encode(['success' => true, 'message' => $message]);
|
|
} catch (PDOException $e) {
|
|
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
|
|
}
|
|
} else {
|
|
echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
|
|
}
|