<?php
// File: public/miniapp/api/admin_configs.php
declare(strict_types=1);
require __DIR__.'/config.php';

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

// بررسی درخواست POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed'], JSON_UNESCAPED_UNICODE);
    exit;
}

// دریافت داده‌های JSON از بدنه درخواست
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON'], JSON_UNESCAPED_UNICODE);
    exit;
}

// بررسی initData
$initData = $input['initData'] ?? null;
if (!$initData) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Missing initData'], JSON_UNESCAPED_UNICODE);
    exit;
}

// اعتبارسنجی کاربر از طریق initData
parse_str($initData, $data);
if (!isset($data['user'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Invalid initData'], JSON_UNESCAPED_UNICODE);
    exit;
}

$userJson = json_decode($data['user'], true);
if (!is_array($userJson) || !isset($userJson['id'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Invalid user data'], JSON_UNESCAPED_UNICODE);
    exit;
}

$user_id = (int)$userJson['id'];

// بررسی ادمین بودن
if (!isAdmin($user_id)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Only admin allowed'], JSON_UNESCAPED_UNICODE);
    exit;
}

// پارامترهای فیلتر و صفحه‌بندی
$plan_code = $input['plan_code'] ?? null;
$is_used = isset($input['is_used']) ? (int)$input['is_used'] : null;
$page = max(1, (int)($input['page'] ?? 1));
$limit = min(100, max(10, (int)($input['limit'] ?? 20)));
$offset = ($page - 1) * $limit;

try {
    // آمار کلی
    $stats_sql = "
        SELECT 
            COUNT(*) as total,
            SUM(is_used = 0) as available,
            SUM(is_used = 1) as used
        FROM configs
    ";
    $stats_params = [];
    
    if ($plan_code) {
        $stats_sql .= " WHERE plan_code = :plan_code";
        $stats_params[':plan_code'] = $plan_code;
    }
    
    $stmt = $pdo->prepare($stats_sql);
    $stmt->execute($stats_params);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // لیست کانفیگ‌ها
    $configs_sql = "
        SELECT 
            c.*,
            u.first_name as used_by_name,
            u.username as used_by_username,
            creator.first_name as creator_name,
            creator.username as creator_username
        FROM configs c
        LEFT JOIN users u ON c.used_by = u.id
        LEFT JOIN users creator ON c.created_by = creator.id
        WHERE 1=1
    ";
    $configs_params = [];
    
    if ($plan_code) {
        $configs_sql .= " AND c.plan_code = :plan_code";
        $configs_params[':plan_code'] = $plan_code;
    }
    
    if ($is_used !== null) {
        $configs_sql .= " AND c.is_used = :is_used";
        $configs_params[':is_used'] = $is_used;
    }
    
    $configs_sql .= " ORDER BY c.created_at DESC LIMIT :limit OFFSET :offset";
    
    $stmt = $pdo->prepare($configs_sql);
    foreach ($configs_params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $configs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // آمار به تفکیک plan_code
    $plan_stats_sql = "
        SELECT 
            plan_code,
            COUNT(*) as total,
            SUM(is_used = 0) as available,
            SUM(is_used = 1) as used
        FROM configs
        GROUP BY plan_code
        ORDER BY plan_code
    ";
    $stmt = $pdo->prepare($plan_stats_sql);
    $stmt->execute();
    $plan_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // پاسخ موفقیت‌آمیز
    echo json_encode([
        'ok' => true,
        'data' => [
            'configs' => $configs,
            'stats' => [
                'total' => (int)($stats['total'] ?? 0),
                'available' => (int)($stats['available'] ?? 0),
                'used' => (int)($stats['used'] ?? 0),
            ],
            'plan_stats' => $plan_stats,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => (int)($stats['total'] ?? 0),
                'total_pages' => ceil((int)($stats['total'] ?? 0) / $limit)
            ]
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    error_log("❌ Error in admin_configs.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}

