<?php
/**
 * /api/admin/pricing_control.php
 * GET:  كل الإعدادات (مجمَّعة بالفئة)
 * POST: تحديث إعداد واحد أو مجموعة
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
require_once '../../engine/PricingEngine.php';

// session_start() removed — Kernel::handle manages sessions

if (empty($_SESSION['admin'])) {
    http_response_code(403);
    die(json_encode(['error' => 'unauthorized']));
}

$adminId = (int)($_SESSION['admin']['id'] ?? 0);
$method  = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        $settings = db()->query(
            "SELECT setting_key, value, value_type, label_ar, category, unit
             FROM platform_settings ORDER BY category, id"
        )->fetchAll();

        $grouped = [];
        foreach ($settings as $s) {
            $grouped[$s['category']][] = $s;
        }

        $docs = db()->query(
            "SELECT * FROM document_prices WHERE is_active=1 ORDER BY id"
        )->fetchAll();

        $corp_services = db()->query(
            "SELECT * FROM corporate_services_catalog WHERE is_active=1 ORDER BY sort_order"
        )->fetchAll();

        echo json_encode([
            'settings'          => $grouped,
            'document_prices'   => $docs,
            'corporate_services'=> $corp_services,
            'current_pricing'   => PricingEngine::getAll(),
        ], JSON_UNESCAPED_UNICODE);

    } catch (Throwable $e) {
        http_response_code(500);
        echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
    }

} elseif ($method === 'POST') {
    $b = json_decode(file_get_contents('php://input'), true) ?? [];
    $action = $b['action'] ?? 'update_setting';
    $errors = [];
    $updated = [];

    if ($action === 'update_setting') {
        $key   = preg_replace('/[^a-z0-9_]/', '', $b['key'] ?? '');
        $value = trim($b['value'] ?? '');
        if (!$key || $value === '') {
            http_response_code(400);
            die(json_encode(['error' => 'key_and_value_required']));
        }
        $ok = PricingEngine::updateSetting($key, $value, $adminId);
        echo json_encode(['ok' => $ok, 'key' => $key, 'value' => $value]);

    } elseif ($action === 'update_document_price') {
        $docType = preg_replace('/[^a-z_]/', '', $b['doc_type'] ?? '');
        $free    = max(0, (int)($b['price_free'] ?? 0));
        $plus    = max(0, (int)($b['price_plus'] ?? 0));
        $pro     = max(0, (int)($b['price_pro']  ?? 0));
        try {
            db()->prepare(
                "UPDATE document_prices SET price_free_sdg=?, price_plus_sdg=?, price_pro_sdg=?
                 WHERE doc_type=?"
            )->execute([$free, $plus, $pro, $docType]);
            PricingEngine::flushCache();
            echo json_encode(['ok' => true, 'doc_type' => $docType]);
        } catch (Throwable $e) {
            echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
        }

    } elseif ($action === 'update_bulk') {
        $updates = $b['updates'] ?? [];
        foreach ($updates as $upd) {
            $key   = preg_replace('/[^a-z0-9_]/', '', $upd['key'] ?? '');
            $value = trim($upd['value'] ?? '');
            if ($key && $value !== '') {
                if (PricingEngine::updateSetting($key, $value, $adminId)) {
                    $updated[] = $key;
                } else {
                    $errors[] = $key;
                }
            }
        }
        echo json_encode(['ok' => count($errors) === 0, 'updated' => $updated, 'errors' => $errors]);
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'unknown_action']);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'method_not_allowed']);
}
