<?php include __DIR__ . '/../header.php'; ?>

<div class="container-fluid py-4">
    <div class="d-flex align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">Manage APKs</h1>
        <form action="/admin/apks" method="GET" class="d-flex gap-2 ms-auto me-3">
            <input type="text" name="search" class="form-control form-control-sm" placeholder="Search APKs..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
            <button type="submit" class="btn btn-sm btn-outline-secondary"><i class="bi bi-search"></i></button>
        </form>
        <a href="/admin/apks/add" class="btn btn-primary shadow-sm">
            <i class="bi bi-plus-lg me-1"></i> Add New APK
        </a>
    </div>

    <div id="reorderAlert" class="alert alert-success alert-dismissible fade show" style="display: none;" role="alert">
        Order updated successfully!
        <button type="button" class="btn-close" onclick="this.parentElement.style.display='none'"></button>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">APK List (Drag to Reorder)</h6>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="apkTable">
                    <thead class="table-light">
                        <tr>
                            <th width="50"></th>
                            <th>Icon</th>
                            <th>Title</th>
                            <th>Version</th>
                            <th>Category</th>
                            <th>Downloads</th>
                            <th>Status</th>
                            <th>VIP</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="sortableList">
                        <?php foreach ($apks as $apk): ?>
                            <tr data-id="<?php echo $apk['id']; ?>">
                                <td class="align-middle text-center cursor-move">
                                    <i class="bi bi-grip-vertical text-muted fs-5"></i>
                                </td>
                                <td class="align-middle">
                                    <?php 
                                        $icon = !empty($apk['icon_path']) ? '/'.$apk['icon_path'] : $apk['image_url'];
                                    ?>
                                    <img src="<?php echo $icon; ?>" class="rounded" width="40" height="40" alt="">
                                </td>
                                <td class="align-middle fw-bold"><?php echo $apk['title']; ?></td>
                                <td class="align-middle"><?php echo $apk['version']; ?></td>
                                <td class="align-middle">
                                    <?php 
                                        $db = db_pdo();
                                        $cat = $db->query("SELECT name FROM categories WHERE id = " . ($apk['category_id'] ?: 0))->fetchColumn();
                                        echo $cat ?: 'Uncategorized';
                                    ?>
                                </td>
                                <td class="align-middle"><?php echo number_format($apk['total_downloads']); ?></td>
                                <td class="align-middle">
                                    <span class="badge bg-<?php echo $apk['status'] === 'published' ? 'success' : 'secondary'; ?>">
                                        <?php echo ucfirst($apk['status']); ?>
                                    </span>
                                </td>
                                <td class="align-middle">
                                    <?php if ($apk['is_vip']): ?>
                                        <span class="badge bg-warning text-dark"><i class="bi bi-star-fill"></i> VIP</span>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="align-middle">
                                    <div class="btn-group btn-group-sm">
                                        <a href="/admin/apks/edit/<?php echo $apk['id']; ?>" class="btn btn-outline-primary">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        <a href="/admin/apks/delete/<?php echo $apk['id']; ?>" class="btn btn-outline-danger" onclick="return confirm('Are you sure?')">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
    const el = document.getElementById('sortableList');
    const sortable = Sortable.create(el, {
        animation: 150,
        handle: '.cursor-move',
        onEnd: function (evt) {
            const rows = el.querySelectorAll('tr');
            const order = Array.from(rows).map(row => row.dataset.id);
            const alertBox = document.getElementById('reorderAlert');
            
            fetch('/admin/apks/reorder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'order[]=' + order.join('&order[]=')
            })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    console.log('Order updated');
                    alertBox.style.display = 'block';
                    setTimeout(() => {
                        alertBox.style.display = 'none';
                    }, 3000);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Failed to update order. Please check your connection.');
            });
        }
    });
</script>

<style>
    .cursor-move { cursor: move; }
    .sortable-ghost { opacity: 0.4; background-color: #f8f9fa; }
</style>

<?php include __DIR__ . '/../footer.php'; ?>