<?php
session_start();
require_once '../config/database.php';
require_once '../includes/smm_api.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

$smmApiKey = '';
$smmBalance = null;
$smmError = null;

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_api_key'");
$smmApiKey = $stmt->fetchColumn() ?: '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_smm_settings') {
        $apiKey = trim($_POST['smm_api_key'] ?? '');
        
        if (!empty($apiKey)) {
            $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute(['smm_api_key', $apiKey, $apiKey]);
            $smmApiKey = $apiKey;
            $success = "تنظیمات SMM با موفقیت ذخیره شد";
        }
    } elseif ($action === 'check_balance') {
        if (!empty($smmApiKey)) {
            $api = new SMMApi($smmApiKey);
            $balance = $api->balance();
            if ($balance && isset($balance->balance)) {
                $smmBalance = $balance;
            } else {
                $smmError = "خطا در دریافت موجودی: " . (isset($balance->error) ? $balance->error : 'خطای نامشخص');
            }
        } else {
            $smmError = "لطفا ابتدا API Key را وارد کنید";
        }
    }
}

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'smm_orders'");
$smmOrdersData = $stmt->fetchColumn();
$smmOrders = [];
if ($smmOrdersData) {
    $smmOrders = json_decode($smmOrdersData, true) ?: [];
}

$stmt = $pdo->query("SELECT setting_value FROM app_settings WHERE setting_key = 'orders_sent_to_smm'");
$sentToSmmData = $stmt->fetchColumn();
$sentToSmm = [];
if ($sentToSmmData) {
    $sentToSmm = json_decode($sentToSmmData, true) ?: [];
}

$orderIds = array_keys($smmOrders);
$ordersDetails = [];

if (!empty($orderIds)) {
    $placeholders = implode(',', array_fill(0, count($orderIds), '?'));
    $stmt = $pdo->prepare("
        SELECT o.id, o.quantity, o.total_coins, o.status, o.created_at, o.telegram_link, o.coin_type,
               u.username, u.full_name,
               p.name as product_name
        FROM orders o
        JOIN users u ON o.user_id = u.id
        JOIN products p ON o.product_id = p.id
        WHERE o.id IN ($placeholders)
        ORDER BY o.created_at DESC
    ");
    $stmt->execute($orderIds);
    $ordersDetails = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تنظیمات SMM - پنل مدیریت</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Vazirmatn:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="assets/css/admin.css" rel="stylesheet">
</head>
<body class="admin-app">
    <?php include 'includes/menu.php'; ?>
    <?php include 'includes/header_bar.php'; ?>

    <main class="main">
        <div class="main-content">
                <?php
                $admin_page_title = 'تنظیمات SMM';
                $admin_page_icon = 'fas fa-server';
                include 'includes/topbar.php';
                ?>

                    <?php if (isset($success)): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle me-2"></i>
                            <?= htmlspecialchars($success) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <?= htmlspecialchars($error) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <div class="card fade-in-up">
                        <div class="card-header">
                            <h6><i class="fas fa-cog me-2"></i>تنظیمات API</h6>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action" value="update_smm_settings">
                                
                                <div class="mb-3">
                                    <label for="smm_api_key" class="form-label">API Key</label>
                                    <input type="text" class="form-control" id="smm_api_key" name="smm_api_key" 
                                           value="<?= htmlspecialchars($smmApiKey) ?>" 
                                           placeholder="API Key خود را از صفحه Account در smmstone.com دریافت کنید">
                                    <div class="form-text">API Key را از صفحه Account در smmstone.com دریافت کنید</div>
                                </div>

                                <div class="text-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>ذخیره تنظیمات
                                    </button>
                                    <?php if (!empty($smmApiKey)): ?>
                                    <button type="submit" formaction="?action=check_balance" name="action" value="check_balance" class="btn btn-info ms-2">
                                        <i class="fas fa-wallet me-2"></i>بررسی موجودی
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </form>

                            <?php if ($smmBalance): ?>
                                <div class="alert alert-info mt-3">
                                    <i class="fas fa-wallet me-2"></i>
                                    <strong>موجودی حساب:</strong> <?= number_format($smmBalance->balance, 2) ?> <?= $smmBalance->currency ?? 'USD' ?>
                                </div>
                            <?php endif; ?>

                            <?php if ($smmError): ?>
                                <div class="alert alert-danger mt-3">
                                    <i class="fas fa-exclamation-triangle me-2"></i>
                                    <?= htmlspecialchars($smmError) ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="card fade-in-up mt-4">
                        <div class="card-header">
                            <h6><i class="fas fa-list me-2"></i>سفارشات ارسال شده به SMM</h6>
                        </div>
                        <div class="card-body">
                            <?php if (empty($ordersDetails)): ?>
                                <p class="text-muted text-center py-4">هیچ سفارشی به SMM ارسال نشده است</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>ID سفارش</th>
                                                <th>کاربر</th>
                                                <th>محصول</th>
                                                <th>تعداد</th>
                                                <th>لینک تلگرام</th>
                                                <th>Order ID در SMM</th>
                                                <th>وضعیت SMM</th>
                                                <th>تاریخ ارسال</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($ordersDetails as $order): 
                                                $smmOrderId = $smmOrders[$order['id']]['smm_order_id'] ?? null;
                                                $smmStatus = $smmOrders[$order['id']]['status'] ?? 'نامشخص';
                                                $smmCharge = $smmOrders[$order['id']]['charge'] ?? null;
                                                $smmRemains = $smmOrders[$order['id']]['remains'] ?? null;
                                                $smmStartCount = $smmOrders[$order['id']]['start_count'] ?? null;
                                                $sentAt = $smmOrders[$order['id']]['sent_at'] ?? null;
                                            ?>
                                                <tr>
                                                    <td>#<?= $order['id'] ?></td>
                                                    <td>
                                                        <strong><?= htmlspecialchars($order['full_name']) ?></strong>
                                                        <br><small class="text-muted">@<?= htmlspecialchars($order['username']) ?></small>
                                                    </td>
                                                    <td><?= htmlspecialchars($order['product_name']) ?></td>
                                                    <td><?= $order['quantity'] ?></td>
                                                    <td>
                                                        <a href="https://<?= htmlspecialchars($order['telegram_link']) ?>" target="_blank" class="text-decoration-none">
                                                            <?= htmlspecialchars($order['telegram_link']) ?>
                                                        </a>
                                                    </td>
                                                    <td>
                                                        <?php if ($smmOrderId): ?>
                                                            <span class="badge bg-primary"><?= $smmOrderId ?></span>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($smmStatus === 'Completed'): ?>
                                                            <span class="badge bg-success">تکمیل شده</span>
                                                        <?php elseif ($smmStatus === 'In progress' || $smmStatus === 'Partial'): ?>
                                                            <span class="badge bg-warning">در حال انجام</span>
                                                        <?php elseif ($smmStatus === 'Cancelled'): ?>
                                                            <span class="badge bg-danger">لغو شده</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-secondary"><?= htmlspecialchars($smmStatus) ?></span>
                                                        <?php endif; ?>
                                                        <?php if ($smmRemains !== null): ?>
                                                            <br><small class="text-muted">باقیمانده: <?= $smmRemains ?></small>
                                                        <?php endif; ?>
                                                        <?php if ($smmCharge !== null): ?>
                                                            <br><small class="text-muted">هزینه: <?= number_format($smmCharge, 2) ?> USD</small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?= $sentAt ? date('Y/m/d H:i', strtotime($sentAt)) : '-' ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <?php include 'includes/admin_shell_scripts.php'; ?>
</body>
</html>

