<?php
require_once __DIR__ . '/core/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

// التحقق من صلاحية الأدمن عبر JWT
$jwtService = new JwtService($redis ?? null);
$admin = $jwtService->authenticate();
if ($admin->role !== 'admin' && $admin->role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized. Admin access required.']);
    exit;
}

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

if (!is_array($data)) {
    $data = $_POST;
}

$action = $data['action'] ?? '';
$text   = trim($data['text'] ?? '');

if ($text === '' || ($action !== 'encrypt' && $action !== 'decrypt')) {
    http_response_code(400);
    echo json_encode([
        'status'  => 'error',
        'message' => 'Invalid input: need action=encrypt|decrypt and non-empty text.',
    ]);
    exit;
}

try {
    if ($action === 'encrypt') {
        $result = $encryptionHelper->encryptData($text);
    } else {
        $result = $encryptionHelper->decryptData($text);
    }

    echo json_encode([
        'status' => 'success',
        'action' => $action,
        'result' => (string) $result,
    ]);
} catch (Exception $e) {
    error_log("[ggg.php] " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'status'  => 'error',
        'message' => 'Operation failed.',
    ]);
}
