<?php
// ============================================================
// Admin/ggg.php
// أداة تشفير وفك تشفير للمشرفين
// ============================================================

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

// نضمن أن الرد دائماً JSON
header('Content-Type: application/json; charset=utf-8');

// 1) قراءة الـ body كـ JSON أو POST
$action = filterRequest('action');
$text   = filterRequest('text');
$adminPhoneParam = filterRequest('admin_phone');

// 2) التحقق من رقم هاتف الأدمن المصرّح له
$phonesRaw = getenv('ADMIN_PHONE_NUMBERS') ?: '';
$ALLOWED_TOOL_PHONES = array_values(
    array_filter(
        array_map(function ($p) {
            return preg_replace('/\D+/', '', $p);
        }, explode(',', $phonesRaw))
    )
);

$adminPhoneParam = $adminPhoneParam ? preg_replace('/\D+/', '', $adminPhoneParam) : '';

if ($adminPhoneParam === '' || !in_array($adminPhoneParam, $ALLOWED_TOOL_PHONES, true)) {
    securityLog("Unauthorized encrypt/decrypt attempt", ['phone' => $adminPhoneParam]);
    jsonError('Access denied for this admin phone.', 403);
}

if (empty($text) || ($action !== 'encrypt' && $action !== 'decrypt')) {
    jsonError('Invalid input: need action=encrypt|decrypt and non-empty text.', 400);
}

// 4) تنفيذ التشفير / الفك (التوافق مع CBC الحالي)
try {
    if ($action === 'encrypt') {
        $result = $encryptionHelper->encryptData($text);
    } else { // decrypt
        $result = $encryptionHelper->decryptData($text);
    }

    jsonSuccess([
        'action' => $action,
        'result' => (string) $result,
    ]);
} catch (Exception $e) {
    securityLog("Encryption tool failed", ['error' => $e->getMessage()]);
    jsonError('Operation failed.', 500);
}