<?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') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_version') {
        $version = trim($_POST['version'] ?? '');
        $versionCode = (int)($_POST['version_code'] ?? 0);
        $updateType = $_POST['update_type'] ?? 'optional';
        $message = trim($_POST['message'] ?? '');
        $downloadUrl = trim($_POST['download_url'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($version) || $versionCode <= 0) {
            $error = 'فیلدهای الزامی را پر کنید';
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO app_versions (version, version_code, update_type, message, download_url, is_active) 
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            if ($stmt->execute([$version, $versionCode, $updateType, $message, $downloadUrl, $isActive])) {
                $success = "نسخه جدید با موفقیت اضافه شد";
            } else {
                $error = "خطا در اضافه کردن نسخه";
            }
        }
    } elseif ($action === 'update_version') {
        $versionId = (int)($_POST['version_id'] ?? 0);
        $version = trim($_POST['version'] ?? '');
        $versionCode = (int)($_POST['version_code'] ?? 0);
        $updateType = $_POST['update_type'] ?? 'optional';
        $message = trim($_POST['message'] ?? '');
        $downloadUrl = trim($_POST['download_url'] ?? '');
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        if ($versionId > 0 && !empty($version) && $versionCode > 0) {
            $stmt = $pdo->prepare("
                UPDATE app_versions 
                SET version = ?, version_code = ?, update_type = ?, message = ?, download_url = ?, is_active = ?
                WHERE id = ?
            ");
            if ($stmt->execute([$version, $versionCode, $updateType, $message, $downloadUrl, $isActive, $versionId])) {
                $success = "نسخه با موفقیت ویرایش شد";
            } else {
                $error = "خطا در ویرایش نسخه";
            }
        }
    } elseif ($action === 'delete_version') {
        $versionId = (int)($_POST['version_id'] ?? 0);
        
        if ($versionId > 0) {
            $stmt = $pdo->prepare("DELETE FROM app_versions WHERE id = ?");
            if ($stmt->execute([$versionId])) {
                $success = "نسخه با موفقیت حذف شد";
            } else {
                $error = "خطا در حذف نسخه";
            }
        }
    } elseif ($action === 'toggle_active') {
        $versionId = (int)($_POST['version_id'] ?? 0);
        
        if ($versionId > 0) {
            $stmt = $pdo->prepare("UPDATE app_versions SET is_active = NOT is_active WHERE id = ?");
            if ($stmt->execute([$versionId])) {
                $success = "وضعیت نسخه با موفقیت تغییر کرد";
            } else {
                $error = "خطا در تغییر وضعیت نسخه";
            }
        }
    }
}

// Get all versions
$stmt = $pdo->query("SELECT * FROM app_versions ORDER BY version_code DESC");
$versions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get current active version
$stmt = $pdo->query("SELECT * FROM app_versions WHERE is_active = 1 ORDER BY version_code DESC LIMIT 1");
$currentVersion = $stmt->fetch(PDO::FETCH_ASSOC);

// Get version statistics
$stmt = $pdo->query("SELECT COUNT(*) as total_versions FROM app_versions");
$totalVersions = $stmt->fetch(PDO::FETCH_ASSOC)['total_versions'];

$stmt = $pdo->query("SELECT COUNT(*) as active_versions FROM app_versions WHERE is_active = 1");
$activeVersions = $stmt->fetch(PDO::FETCH_ASSOC)['active_versions'];

$stmt = $pdo->query("SELECT COUNT(*) as forced_updates FROM app_versions WHERE update_type = 'forced'");
$forcedUpdates = $stmt->fetch(PDO::FETCH_ASSOC)['forced_updates'];
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت نسخه‌های اپلیکیشن - پنل مدیریت</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 = 'مدیریت نسخه‌های اپلیکیشن';
                $admin_page_icon = 'fas fa-mobile-alt';
                include 'includes/topbar.php';
                ?>

                    <div class="p-0">
                        <?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 -->
                        <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-code-branch fa-2x mb-2"></i>
                                        <h4><?= number_format($totalVersions) ?></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-check-circle fa-2x mb-2"></i>
                                        <h4><?= number_format($activeVersions) ?></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-exclamation-triangle fa-2x mb-2"></i>
                                        <h4><?= number_format($forcedUpdates) ?></h4>
                                        <p class="mb-0">آپدیت‌های اجباری</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Current Version Info -->
                        <?php if ($currentVersion): ?>
                        <div class="card fade-in-up mb-4">
                            <div class="card-header">
                                <h6><i class="fas fa-star me-2"></i>نسخه فعلی فعال</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h5 class="text-primary"><?= htmlspecialchars($currentVersion['version']) ?></h5>
                                        <p class="text-muted">کد نسخه: <?= $currentVersion['version_code'] ?></p>
                                        <span class="badge bg-<?= $currentVersion['update_type'] === 'forced' ? 'danger' : 'success' ?>">
                                            <?= $currentVersion['update_type'] === 'forced' ? 'آپدیت اجباری' : 'آپدیت اختیاری' ?>
                                        </span>
                                    </div>
                                    <div class="col-md-6">
                                        <p><strong>پیام آپدیت:</strong></p>
                                        <p class="text-muted"><?= htmlspecialchars($currentVersion['message']) ?: 'پیامی تنظیم نشده' ?></p>
                                        <?php if ($currentVersion['download_url']): ?>
                                        <a href="<?= htmlspecialchars($currentVersion['download_url']) ?>" class="btn btn-sm btn-primary" target="_blank">
                                            <i class="fas fa-download me-2"></i>دانلود
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <!-- Add New Version -->
                        <div class="card fade-in-up mb-4">
                            <div class="card-header">
                                <h6><i class="fas fa-plus me-2"></i>افزودن نسخه جدید</h6>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <input type="hidden" name="action" value="add_version">
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="version" class="form-label">نام نسخه *</label>
                                                <input type="text" class="form-control" id="version" name="version" 
                                                       placeholder="مثال: 1.2.3" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="version_code" class="form-label">کد نسخه *</label>
                                                <input type="number" class="form-control" id="version_code" name="version_code" 
                                                       placeholder="مثال: 123" min="1" required>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="update_type" class="form-label">نوع آپدیت</label>
                                                <select class="form-control" id="update_type" name="update_type">
                                                    <option value="optional">اختیاری</option>
                                                    <option value="forced">اجباری</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label for="download_url" class="form-label">لینک دانلود</label>
                                                <input type="url" class="form-control" id="download_url" name="download_url" 
                                                       placeholder="https://example.com/app.apk">
                                            </div>
                                        </div>
                                    </div>

                                    <div class="mb-3">
                                        <label for="message" class="form-label">پیام آپدیت</label>
                                        <textarea class="form-control" id="message" name="message" rows="3" 
                                                  placeholder="توضیحات آپدیت..."></textarea>
                                    </div>

                                    <div class="mb-3">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" checked>
                                            <label class="form-check-label" for="is_active">
                                                فعال بودن نسخه
                                            </label>
                                        </div>
                                    </div>

                                    <div class="text-end">
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-plus me-2"></i>افزودن نسخه
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Versions List -->
                        <div class="card fade-in-up">
                            <div class="card-header">
                                <h6><i class="fas fa-list me-2"></i>لیست نسخه‌ها</h6>
                            </div>
                            <div class="card-body">
                                <?php if (empty($versions)): ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="fas fa-mobile-alt fa-3x mb-3"></i>
                                        <p>هیچ نسخه‌ای ثبت نشده است</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>نام نسخه</th>
                                                    <th>کد نسخه</th>
                                                    <th>نوع آپدیت</th>
                                                    <th>وضعیت</th>
                                                    <th>تاریخ ایجاد</th>
                                                    <th>عملیات</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($versions as $version): ?>
                                                <tr>
                                                    <td>
                                                        <strong><?= htmlspecialchars($version['version']) ?></strong>
                                                        <?php if ($version['message']): ?>
                                                        <br><small class="text-muted"><?= htmlspecialchars($version['message']) ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?= $version['version_code'] ?></td>
                                                    <td>
                                                        <span class="badge bg-<?= $version['update_type'] === 'forced' ? 'danger' : 'success' ?>">
                                                            <?= $version['update_type'] === 'forced' ? 'اجباری' : 'اختیاری' ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?= $version['is_active'] ? 'success' : 'secondary' ?>">
                                                            <?= $version['is_active'] ? 'فعال' : 'غیرفعال' ?>
                                                        </span>
                                                    </td>
                                                    <td><?= date('Y/m/d H:i', strtotime($version['created_at'])) ?></td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button type="button" class="btn btn-sm btn-primary" 
                                                                    data-bs-toggle="modal" data-bs-target="#editVersionModal" 
                                                                    data-version='<?= json_encode($version) ?>'>
                                                                <i class="fas fa-edit"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-<?= $version['is_active'] ? 'warning' : 'info' ?>" 
                                                                    onclick="toggleVersion(<?= $version['id'] ?>, '<?= htmlspecialchars($version['version']) ?>', <?= $version['is_active'] ? 'false' : 'true' ?>)">
                                                                <i class="fas fa-<?= $version['is_active'] ? 'ban' : 'check' ?>"></i>
                                                            </button>
                                                            <button type="button" class="btn btn-sm btn-danger" 
                                                                    onclick="deleteVersion(<?= $version['id'] ?>, '<?= htmlspecialchars($version['version']) ?>')">
                                                                <i class="fas fa-trash"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
        </div>
    </main>

    <!-- Edit Version Modal -->
    <div class="modal fade" id="editVersionModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">ویرایش نسخه</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_version">
                        <input type="hidden" name="version_id" id="editVersionId">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editVersion" class="form-label">نام نسخه *</label>
                                    <input type="text" class="form-control" id="editVersion" name="version" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editVersionCode" class="form-label">کد نسخه *</label>
                                    <input type="number" class="form-control" id="editVersionCode" name="version_code" min="1" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editUpdateType" class="form-label">نوع آپدیت</label>
                                    <select class="form-control" id="editUpdateType" name="update_type">
                                        <option value="optional">اختیاری</option>
                                        <option value="forced">اجباری</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="editDownloadUrl" class="form-label">لینک دانلود</label>
                                    <input type="url" class="form-control" id="editDownloadUrl" name="download_url">
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="editMessage" class="form-label">پیام آپدیت</label>
                            <textarea class="form-control" id="editMessage" name="message" rows="3"></textarea>
                        </div>

                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="editIsActive" name="is_active">
                                <label class="form-check-label" for="editIsActive">
                                    فعال بودن نسخه
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                        <button type="submit" class="btn btn-primary">ذخیره تغییرات</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <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'; ?>
    <script>
        // Edit Version Modal
        document.getElementById('editVersionModal').addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var version = JSON.parse(button.getAttribute('data-version'));
            
            document.getElementById('editVersionId').value = version.id;
            document.getElementById('editVersion').value = version.version;
            document.getElementById('editVersionCode').value = version.version_code;
            document.getElementById('editUpdateType').value = version.update_type;
            document.getElementById('editDownloadUrl').value = version.download_url || '';
            document.getElementById('editMessage').value = version.message || '';
            document.getElementById('editIsActive').checked = version.is_active == 1;
        });

        // Toggle Version Status
        function toggleVersion(versionId, versionName, newStatus) {
            var statusText = newStatus ? 'فعال' : 'غیرفعال';
            if (confirm('آیا از تغییر وضعیت نسخه "' + versionName + '" به "' + statusText + '" اطمینان دارید؟')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_active">
                    <input type="hidden" name="version_id" value="${versionId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Delete Version
        function deleteVersion(versionId, versionName) {
            if (confirm('آیا از حذف نسخه "' + versionName + '" اطمینان دارید؟ این عمل غیرقابل بازگشت است.')) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_version">
                    <input type="hidden" name="version_id" value="${versionId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Add fade-in animation to cards
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.fade-in-up');
            cards.forEach((card, index) => {
                card.style.animationDelay = (index * 0.1) + 's';
            });
        });
    </script>
</body>
</html>
