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

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $appId = trim($_POST['app_id'] ?? '');
    $videoAdUnitId = trim($_POST['video_ad_unit_id'] ?? '');
    $bannerAdUnitId = trim($_POST['banner_ad_unit_id'] ?? '');
    $rewardCoins = (int)($_POST['reward_coins'] ?? 10);
    $dailyLimit = (int)($_POST['daily_limit'] ?? 10);
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    $isBannerActive = isset($_POST['is_banner_active']) ? 1 : 0;
    
    if (empty($appId) || empty($videoAdUnitId) || empty($bannerAdUnitId)) {
        $error = 'فیلدهای App ID، Video Ad Unit ID و Banner Ad Unit ID الزامی هستند';
    } else {
        // Update or insert AdMob settings
        $stmt = $pdo->prepare("SELECT id FROM admob_settings LIMIT 1");
        $stmt->execute();
        
        if ($stmt->fetch()) {
            // Update existing settings
            $stmt = $pdo->prepare("UPDATE admob_settings SET app_id = ?, video_ad_unit_id = ?, banner_ad_unit_id = ?, reward_coins = ?, daily_limit = ?, is_active = ?, is_banner_active = ? WHERE id = 1");
            $stmt->execute([$appId, $videoAdUnitId, $bannerAdUnitId, $rewardCoins, $dailyLimit, $isActive, $isBannerActive]);
        } else {
            // Insert new settings
            $stmt = $pdo->prepare("INSERT INTO admob_settings (app_id, video_ad_unit_id, banner_ad_unit_id, reward_coins, daily_limit, is_active, is_banner_active) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$appId, $videoAdUnitId, $bannerAdUnitId, $rewardCoins, $dailyLimit, $isActive, $isBannerActive]);
        }
        
        $success = "تنظیمات AdMob با موفقیت ذخیره شد";
    }
}

// Get current AdMob settings
$stmt = $pdo->query("SELECT * FROM admob_settings LIMIT 1");
$admobSettings = $stmt->fetch(PDO::FETCH_ASSOC);

// Get video reward statistics
$stmt = $pdo->query("SELECT COUNT(*) as total_views, SUM(coins_earned) as total_coins FROM video_rewards");
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Get recent video rewards
$stmt = $pdo->query("
    SELECT vr.*, u.username, u.full_name 
    FROM video_rewards vr 
    JOIN users u ON vr.user_id = u.id 
    ORDER BY vr.viewed_at DESC 
    LIMIT 10
");
$recentRewards = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get daily video rewards count
$stmt = $pdo->query("
    SELECT COUNT(*) as today_views 
    FROM video_rewards 
    WHERE DATE(viewed_at) = CURDATE()
");
$todayStats = $stmt->fetch(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>تنظیمات AdMob - پنل مدیریت</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 = 'تنظیمات AdMob';
                $admin_page_icon = 'fas fa-video';
                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; ?>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card stat-card info">
                            <div class="card-body text-center">
                                <i class="fas fa-play-circle fa-2x mb-2"></i>
                                <h4><?= number_format($stats['total_views'] ?? 0) ?></h4>
                                <p class="mb-0">کل بازدید ویدئو</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card success">
                            <div class="card-body text-center">
                                <i class="fas fa-coins fa-2x mb-2"></i>
                                <h4><?= number_format($stats['total_coins'] ?? 0) ?></h4>
                                <p class="mb-0">کل سکه‌های اهدا شده</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card warning">
                            <div class="card-body text-center">
                                <i class="fas fa-calendar-day fa-2x mb-2"></i>
                                <h4><?= number_format($todayStats['today_views'] ?? 0) ?></h4>
                                <p class="mb-0">بازدید امروز</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card">
                            <div class="card-body text-center">
                                <i class="fas fa-toggle-<?= ($admobSettings['is_active'] ?? false) ? 'on' : 'off' ?> fa-2x mb-2"></i>
                                <h4><?= ($admobSettings['is_active'] ?? false) ? 'فعال' : 'غیرفعال' ?></h4>
                                <p class="mb-0">وضعیت Video Ad</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card stat-card">
                            <div class="card-body text-center">
                                <i class="fas fa-toggle-<?= ($admobSettings['is_banner_active'] ?? false) ? 'on' : 'off' ?> fa-2x mb-2"></i>
                                <h4><?= ($admobSettings['is_banner_active'] ?? false) ? 'فعال' : 'غیرفعال' ?></h4>
                                <p class="mb-0">وضعیت Banner Ad</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- AdMob Settings Form -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">تنظیمات AdMob</h6>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="app_id" class="form-label">App ID *</label>
                                        <input type="text" class="form-control" id="app_id" name="app_id" 
                                               value="<?= htmlspecialchars($admobSettings['app_id'] ?? '') ?>" 
                                               placeholder="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy" required>
                                        <div class="form-text">شناسه اپلیکیشن AdMob شما</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="video_ad_unit_id" class="form-label">Video Ad Unit ID *</label>
                                        <input type="text" class="form-control" id="video_ad_unit_id" name="video_ad_unit_id" 
                                               value="<?= htmlspecialchars($admobSettings['video_ad_unit_id'] ?? '') ?>" 
                                               placeholder="ca-app-pub-xxxxxxxxxxxxxxxx/zzzzzzzzzz" required>
                                        <div class="form-text">شناسه واحد تبلیغ ویدئویی</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="banner_ad_unit_id" class="form-label">Banner Ad Unit ID *</label>
                                        <input type="text" class="form-control" id="banner_ad_unit_id" name="banner_ad_unit_id" 
                                               value="<?= htmlspecialchars($admobSettings['banner_ad_unit_id'] ?? 'ca-app-pub-3940256099942544/6300978111') ?>" 
                                               placeholder="ca-app-pub-xxxxxxxxxxxxxxxx/aaaaaaaaaa" required>
                                        <div class="form-text">شناسه واحد تبلیغ بنری</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="reward_coins" class="form-label">سکه‌های پاداش</label>
                                        <input type="number" class="form-control" id="reward_coins" name="reward_coins" 
                                               value="<?= $admobSettings['reward_coins'] ?? 10 ?>" min="1" max="1000">
                                        <div class="form-text">تعداد سکه‌هایی که کاربر بعد از تماشای ویدئو دریافت می‌کند</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="daily_limit" class="form-label">محدودیت روزانه</label>
                                        <input type="number" class="form-control" id="daily_limit" name="daily_limit" 
                                               value="<?= $admobSettings['daily_limit'] ?? 10 ?>" min="1" max="100">
                                        <div class="form-text">حداکثر تعداد ویدئوهایی که هر کاربر در روز می‌تواند تماشا کند</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" 
                                                   <?= ($admobSettings['is_active'] ?? false) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="is_active">
                                                فعال کردن Video Ad
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" id="is_banner_active" name="is_banner_active" 
                                                   <?= ($admobSettings['is_banner_active'] ?? true) ? 'checked' : '' ?>>
                                            <label class="form-check-label" for="is_banner_active">
                                                فعال کردن Banner Ad
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>ذخیره تنظیمات
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Recent Video Rewards -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">آخرین پاداش‌های ویدئویی</h6>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>کاربر</th>
                                        <th>Ad Unit ID</th>
                                        <th>سکه‌های دریافت شده</th>
                                        <th>تاریخ تماشا</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentRewards as $reward): ?>
                                    <tr>
                                        <td>
                                            <strong><?= htmlspecialchars($reward['username']) ?></strong><br>
                                            <small class="text-muted"><?= htmlspecialchars($reward['full_name']) ?></small>
                                        </td>
                                        <td>
                                            <code><?= htmlspecialchars($reward['ad_unit_id']) ?></code>
                                        </td>
                                        <td>
                                            <span class="badge bg-success">
                                                +<?= number_format($reward['coins_earned']) ?> سکه
                                            </span>
                                        </td>
                                        <td><?= date('Y/m/d H:i', strtotime($reward['viewed_at'])) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($recentRewards)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center text-muted">
                                            هنوز هیچ پاداش ویدئویی ثبت نشده است
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </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>
