<?php
// ==================== CẤU HÌNH ====================
$main_domain = 'https://168.144.134.222';           // ← ĐỔI thành domain Web mẹ
$api_key     = 'reseller_abc123xyz789secretkey';         // ← ĐỔI thành API Key của Reseller

// ==================== HÀM GỌI API ====================
function callApi($endpoint, $method = 'GET', $data = []) {
    global $main_domain, $api_key;
    $url = rtrim($main_domain, '/') . '/api/v1' . $endpoint;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-Reseller-Key: ' . $api_key,
        'Content-Type: application/json',
        'Accept: application/json'
    ]);

    if (strtoupper($method) === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return [
        'status' => $httpCode,
        'data'   => json_decode($response, true)
    ];
}

// Xử lý tạo user
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_user'])) {
    $result = callApi('/reseller/users', 'POST', [
        'email'    => $_POST['email'],
        'password' => $_POST['password'],
        'plan_id'  => (int)$_POST['plan_id'],
        'days'     => (int)$_POST['days']
    ]);

    if ($result['status'] == 201) {
        $message = '<div class="alert alert-success">Tạo tài khoản khách thành công!</div>';
    } else {
        $message = '<div class="alert alert-danger">Lỗi: ' . ($result['data']['message'] ?? 'Không xác định') . '</div>';
    }
}

// Lấy danh sách user
$users = [];
$result = callApi('/reseller/users', 'GET');
if ($result['status'] == 200 && isset($result['data'])) {
    $users = $result['data'];
}
?>

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Con Reseller - wyx2685</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .card { box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
    </style>
</head>
<body>
<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>🛡️ Web Con Reseller</h2>
        <span class="text-muted">wyx2685</span>
    </div>

    <?= $message ?>

    <div class="row">
        <!-- Form tạo user -->
        <div class="col-lg-5">
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">➕ Tạo tài khoản khách</h5>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="mb-3">
                            <label class="form-label">Email khách</label>
                            <input type="email" name="email" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Mật khẩu</label>
                            <input type="text" name="password" class="form-control" value="<?= bin2hex(random_bytes(4)) ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Gói (Plan ID)</label>
                            <input type="number" name="plan_id" class="form-control" value="1" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Số ngày sử dụng</label>
                            <input type="number" name="days" class="form-control" value="30" required>
                        </div>
                        <button type="submit" name="create_user" class="btn btn-success w-100">Tạo tài khoản</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Danh sách khách hàng -->
        <div class="col-lg-7">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">📋 Danh sách khách hàng của bạn</h5>
                </div>
                <div class="card-body p-0">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Email</th>
                                <th>Còn lại</th>
                                <th>Hết hạn</th>
                                <th>Link Sub</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($users)): ?>
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">Chưa có khách hàng nào</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($users as $user): ?>
                                    <?php 
                                        $remaining = max(0, ($user['transfer_enable'] ?? 0) - (($user['u'] ?? 0) + ($user['d'] ?? 0)));
                                        $remaining_gb = round($remaining / 1073741824, 2);
                                        $sub_link = $main_domain . "/api/v1/client/subscribe?token=" . ($user['token'] ?? '');
                                    ?>
                                    <tr>
                                        <td><?= htmlspecialchars($user['email']) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $remaining_gb > 0 ? 'success' : 'danger' ?>">
                                                <?= $remaining_gb ?> GB
                                            </span>
                                        </td>
                                        <td><?= isset($user['expired_at']) ? date('d/m/Y', strtotime($user['expired_at'])) : '-' ?></td>
                                        <td>
                                            <button onclick="copyToClipboard('<?= $sub_link ?>')" class="btn btn-sm btn-outline-primary">
                                                📋 Copy Link
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert('Đã copy link sub!');
    });
}
</script>
</body>
</html>