<?php
$pageTitle = 'Pricing Plans';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
$plans = $db->query("SELECT * FROM pricing_plans ORDER BY sort_order ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Website Pricing Plans</h6>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#pricingModal" onclick="resetPricingForm()"><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>Plan Name</th><th>Monthly</th><th>Annual</th><th>Description</th><th>Features</th><th>Recommended</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['plan_name']); ?></strong></td>
                        <td><?php echo formatCurrency($plan['monthly_price']); ?></td>
                        <td><?php echo formatCurrency($plan['annual_price']); ?></td>
                        <td><?php echo sanitize(truncate($plan['description'] ?? '', 60)); ?></td>
                        <td><?php
                            $feats = $plan['features'];
                            if (is_string($feats)) { $feats = json_decode($feats, true); }
                            echo is_array($feats) ? count($feats) . ' features' : '0 features';
                        ?></td>
                        <td><?php echo $plan['is_recommended'] ? '<i class="fas fa-star text-warning"></i>' : '-'; ?></td>
                        <td><span class="badge bg-<?php echo $plan['is_active'] ? 'success' : 'secondary'; ?>"><?php echo $plan['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action edit-pricing-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-pricing-btn" data-id="<?php echo $plan['id']; ?>" data-name="<?php echo sanitize($plan['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="pricingModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="pricingModalTitle">Add Pricing Plan</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="pricingForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" id="pricing_csrf" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="plan_id" id="pricing_plan_id" value="">
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label">Plan Name <span class="text-danger">*</span></label><input type="text" class="form-control" name="plan_name" id="pricing_name" required></div>
                        <div class="col-md-3"><label class="form-label">Monthly Price</label><input type="number" step="0.01" class="form-control" name="monthly_price" id="pricing_monthly" value="0"></div>
                        <div class="col-md-3"><label class="form-label">Annual Price</label><input type="number" step="0.01" class="form-control" name="annual_price" id="pricing_annual" value="0"></div>
                        <div class="col-md-12"><label class="form-label">Description</label><textarea class="form-control" name="description" id="pricing_description" rows="2"></textarea></div>
                        <div class="col-md-12"><label class="form-label">Features (one per line)</label><textarea class="form-control" name="features" id="pricing_features" rows="5"></textarea></div>
                        <div class="col-md-4"><label class="form-label">Sort Order</label><input type="number" class="form-control" name="sort_order" id="pricing_sort" 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="pricing_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="pricing_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</button></div>
            </form>
        </div>
    </div>
</div>

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

function resetPricingForm() {
    document.getElementById('pricingModalTitle').textContent = 'Add Pricing Plan';
    document.getElementById('pricingForm').reset();
    document.getElementById('pricing_plan_id').value = '';
}

document.querySelectorAll('.edit-pricing-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var p = pricingData.find(function(x) { return x.id == btn.dataset.id; });
        if (!p) return;
        document.getElementById('pricingModalTitle').textContent = 'Edit Pricing Plan';
        document.getElementById('pricing_plan_id').value = p.id;
        document.getElementById('pricing_name').value = p.plan_name;
        document.getElementById('pricing_monthly').value = p.monthly_price;
        document.getElementById('pricing_annual').value = p.annual_price;
        document.getElementById('pricing_description').value = p.description || '';
        document.getElementById('pricing_sort').value = p.sort_order;
        document.getElementById('pricing_recommended').checked = p.is_recommended == 1;
        document.getElementById('pricing_active').checked = p.is_active == 1;
        var f = p.features;
        if (typeof f === 'string') { try { f = JSON.parse(f); } catch(e) { f = []; } }
        document.getElementById('pricing_features').value = Array.isArray(f) ? f.join('\n') : '';
        new bootstrap.Modal(document.getElementById('pricingModal')).show();
    });
});

document.getElementById('pricingForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var fd = new FormData(this);
    var fArr = document.getElementById('pricing_features').value.split('\n').filter(function(l) { return l.trim() !== ''; });
    fd.set('features', JSON.stringify(fArr));
    fetch(BASE_URL + '/admin/pricing_save.php', { method: 'POST', body: new URLSearchParams(fd) })
    .then(function(r) { return r.json(); })
    .then(function(d) { if (d.success) { showAlert('success', d.message); setTimeout(function() { location.reload(); }, 1000); } else { showAlert('danger', d.message); } });
});

document.querySelectorAll('.delete-pricing-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        if (confirm('Delete "' + this.dataset.name + '"?')) {
            ajaxPost(BASE_URL + '/admin/pricing_save.php', 'action=delete&plan_id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(d) {
                if (d.success) { showAlert('success', d.message); setTimeout(function() { location.reload(); }, 1000); } else { showAlert('danger', d.message); }
            });
        }
    });
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
