<?php
$pageTitle = 'Subscription Plans';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
$plans = $db->query("SELECT sp.*, COUNT(r.id) as restaurant_count FROM subscription_plans sp LEFT JOIN restaurants r ON r.plan_id = sp.id GROUP BY sp.id ORDER BY sp.sort_order ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Manage Subscription Plans</h6>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#planModal" onclick="resetPlanForm()"><i class="fas fa-plus me-1"></i>Add Plan</button>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable">
                <thead class="table-light">
                    <tr>
                        <th>Sort</th><th>Name</th><th>Slug</th><th>Monthly</th><th>Annual</th>
                        <th>Items</th><th>Staff</th><th>Tables</th><th>Branches</th>
                        <th>Restaurants</th><th>Featured</th><th>Active</th><th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($plans as $plan): ?>
                    <tr>
                        <td><?php echo $plan['sort_order']; ?></td>
                        <td><strong><?php echo sanitize($plan['name']); ?></strong></td>
                        <td><?php echo sanitize($plan['slug']); ?></td>
                        <td><?php echo formatCurrency($plan['monthly_price']); ?></td>
                        <td><?php echo formatCurrency($plan['annual_price']); ?></td>
                        <td><?php echo $plan['max_menu_items'] == -1 ? 'Unlimited' : $plan['max_menu_items']; ?></td>
                        <td><?php echo $plan['max_staff'] == -1 ? 'Unlimited' : $plan['max_staff']; ?></td>
                        <td><?php echo $plan['max_tables'] == -1 ? 'Unlimited' : $plan['max_tables']; ?></td>
                        <td><?php echo $plan['max_branches'] == -1 ? 'Unlimited' : $plan['max_branches']; ?></td>
                        <td><span class="badge bg-info"><?php echo $plan['restaurant_count']; ?></span></td>
                        <td><?php echo $plan['is_recommended'] ? '<i class="fas fa-star text-warning"></i>' : '-'; ?></td>
                        <td>
                            <div class="form-check form-switch">
                                <input class="form-check-input toggle-active" type="checkbox" data-id="<?php echo $plan['id']; ?>" <?php echo $plan['is_active'] ? 'checked' : ''; ?>>
                            </div>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action edit-plan-btn" data-id="<?php echo $plan['id']; ?>" title="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-sm btn-outline-danger btn-action delete-plan-btn" data-id="<?php echo $plan['id']; ?>" data-name="<?php echo sanitize($plan['name']); ?>" title="Delete"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="planModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="planModalTitle">Add Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="planForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" id="plan_csrf" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="plan_id" id="plan_id" value="">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="name" id="plan_name" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Slug</label>
                            <input type="text" class="form-control" name="slug" id="plan_slug">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" id="plan_description" rows="2"></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Monthly Price</label>
                            <input type="number" step="0.01" class="form-control" name="monthly_price" id="plan_monthly_price" value="0">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Annual Price</label>
                            <input type="number" step="0.01" class="form-control" name="annual_price" id="plan_annual_price" value="0">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Max Menu Items</label>
                            <input type="number" class="form-control" name="max_menu_items" id="plan_max_menu_items" value="50">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Max Staff</label>
                            <input type="number" class="form-control" name="max_staff" id="plan_max_staff" value="3">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Max Tables</label>
                            <input type="number" class="form-control" name="max_tables" id="plan_max_tables" value="10">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Max Branches</label>
                            <input type="number" class="form-control" name="max_branches" id="plan_max_branches" value="1">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Features (one per line)</label>
                            <textarea class="form-control" name="features" id="plan_features" rows="4"></textarea>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" id="plan_sort_order" value="0">
                        </div>
                        <div class="col-md-4">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" name="is_recommended" id="plan_is_recommended" value="1">
                                <label class="form-check-label">Recommended</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" name="is_active" id="plan_is_active" value="1" checked>
                                <label class="form-check-label">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var plansData = <?php echo json_encode($plans, JSON_HEX_TAG | JSON_HEX_AMP); ?>;

function resetPlanForm() {
    document.getElementById('planModalTitle').textContent = 'Add Plan';
    document.getElementById('planForm').reset();
    document.getElementById('plan_id').value = '';
    document.getElementById('plan_is_active').checked = true;
}

document.querySelectorAll('.edit-plan-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        var plan = plansData.find(function(p) { return p.id == id; });
        if (!plan) return;
        document.getElementById('planModalTitle').textContent = 'Edit Plan';
        document.getElementById('plan_id').value = plan.id;
        document.getElementById('plan_name').value = plan.name;
        document.getElementById('plan_slug').value = plan.slug;
        document.getElementById('plan_description').value = plan.description || '';
        document.getElementById('plan_monthly_price').value = plan.monthly_price;
        document.getElementById('plan_annual_price').value = plan.annual_price;
        document.getElementById('plan_max_menu_items').value = plan.max_menu_items;
        document.getElementById('plan_max_staff').value = plan.max_staff;
        document.getElementById('plan_max_tables').value = plan.max_tables;
        document.getElementById('plan_max_branches').value = plan.max_branches;
        document.getElementById('plan_sort_order').value = plan.sort_order;
        document.getElementById('plan_is_recommended').checked = plan.is_recommended == 1;
        document.getElementById('plan_is_active').checked = plan.is_active == 1;
        var features = plan.features;
        if (typeof features === 'string') {
            try { features = JSON.parse(features); } catch(e) { features = []; }
        }
        document.getElementById('plan_features').value = Array.isArray(features) ? features.join('\n') : '';
        var modal = new bootstrap.Modal(document.getElementById('planModal'));
        modal.show();
    });
});

document.getElementById('planForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    var featuresText = document.getElementById('plan_features').value;
    var featuresArr = featuresText.split('\n').filter(function(l) { return l.trim() !== ''; });
    formData.set('features', JSON.stringify(featuresArr));

    fetch(BASE_URL + '/admin/plan_save.php', {
        method: 'POST',
        body: new URLSearchParams(formData)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            showAlert('success', data.message);
            setTimeout(function() { location.reload(); }, 1000);
        } else {
            showAlert('danger', data.message);
        }
    })
    .catch(function() {
        showAlert('danger', 'An error occurred.');
    });
});

document.querySelectorAll('.toggle-active').forEach(function(el) {
    el.addEventListener('change', function() {
        var id = this.dataset.id;
        var active = this.checked ? 1 : 0;
        ajaxPost(BASE_URL + '/admin/plan_save.php', 'action=toggle_active&plan_id=' + id + '&is_active=' + active + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (!data.success) {
                showAlert('danger', data.message);
                setTimeout(function() { location.reload(); }, 500);
            }
        });
    });
});

document.querySelectorAll('.delete-plan-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        var name = this.dataset.name;
        if (confirm('Are you sure you want to delete "' + name + '"?')) {
            ajaxPost(BASE_URL + '/admin/plan_save.php', 'action=delete&plan_id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) {
                    showAlert('success', data.message);
                    setTimeout(function() { location.reload(); }, 1000);
                } else {
                    showAlert('danger', data.message);
                }
            });
        }
    });
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
