<?php
require_once 'config.php';
header('Content-Type: application/json; charset=utf-8');
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$adminId = miniapp_require_admin();
function ar_ok(array $data=[]): void { echo json_encode(['ok'=>true,'data'=>$data], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
function ar_err(string $e): void { echo json_encode(['ok'=>false,'error'=>$e], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }
try {
    $action = (string)($input['action'] ?? $_GET['action'] ?? 'list');
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $action !== 'list') {
        $uid = (int)($input['target_user_id'] ?? 0);
        if (!$uid) ar_err('شناسه کاربر الزامی است');
        if ($action === 'save') {
            $percent = max(0, min(100, (float)($input['discount_percent'] ?? 0)));
            $fixed = max(0, (int)preg_replace('/\D+/', '', (string)($input['fixed_discount'] ?? 0)));
            $active = !empty($input['is_active']) ? 1 : 0;
            $notes = trim((string)($input['notes'] ?? ''));
            $pdo->prepare("INSERT INTO users(id) VALUES(?) ON DUPLICATE KEY UPDATE id=id")->execute([$uid]);
            $pdo->prepare("INSERT INTO users(id,is_admin) VALUES(?,0) ON DUPLICATE KEY UPDATE is_admin=0")->execute([$uid]);
            $pdo->prepare("INSERT INTO resellers(user_id,discount_percent,fixed_discount,is_active,notes) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE discount_percent=VALUES(discount_percent), fixed_discount=VALUES(fixed_discount), is_active=VALUES(is_active), notes=VALUES(notes)")->execute([$uid,$percent,$fixed,$active,$notes]);
            ar_ok(['message'=>'فروشنده ذخیره شد']);
        }
        if ($action === 'delete') { $pdo->prepare("DELETE FROM resellers WHERE user_id=?")->execute([$uid]); ar_ok(['message'=>'فروشنده حذف شد']); }
        ar_err('Action نامعتبر است');
    }
    $st = $pdo->query("SELECT r.*, u.username,u.first_name,u.last_name,u.balance FROM resellers r LEFT JOIN users u ON u.id=r.user_id ORDER BY r.created_at DESC");
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
    foreach ($rows as &$r) { $r['user_id']=(int)$r['user_id']; $r['fixed_discount']=(int)$r['fixed_discount']; $r['balance']=(int)($r['balance']??0); $r['discount_percent']=(float)$r['discount_percent']; }
    ar_ok(['resellers'=>$rows]);
} catch (Throwable $e) { error_log('[admin_resellers] '.$e->getMessage()); ar_err($e->getMessage()); }
