<?php
$pageTitle = 'Offers';
require_once __DIR__ . '/includes/header.php';

$offers = $db->query("SELECT * FROM offers WHERE restaurant_id = ? ORDER BY created_at DESC", [$restaurantId])->fetchAll();
$categories = $db->query("SELECT id, name FROM categories WHERE restaurant_id = ? AND status = 1 ORDER BY name ASC", [$restaurantId])->fetchAll();
$menuItems = $db->query("SELECT id, name, regular_price FROM menu_items WHERE restaurant_id = ? AND is_available = 1 ORDER BY name ASC", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Offers & Promotions</h6>
        <small class="text-muted">Manage offers, coupons, and promotions</small>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#offerModal" onclick="resetOfferForm()">
        <i class="fas fa-plus me-1"></i>Add Offer
    </button>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable mb-0">
                <thead class="table-light">
                    <tr><th>Title</th><th>Type</th><th>Discount</th><th>Coupon</th><th>Start</th><th>End</th><th>Uses</th><th>Status</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($offers as $off): ?>
                        <tr>
                            <td><strong><?php echo sanitize($off['title']); ?></strong></td>
                            <td><span class="badge bg-info"><?php echo ucfirst($off['offer_type']); ?></span></td>
                            <td><?php echo $off['offer_type'] === 'percentage' ? $off['discount_value'] . '%' : formatCurrency($off['discount_value'], $currency); ?></td>
                            <td><?php echo $off['coupon_code'] ? '<code>' . sanitize($off['coupon_code']) . '</code>' : '-'; ?></td>
                            <td><?php echo $off['start_date'] ? formatDate($off['start_date']) : '-'; ?></td>
                            <td><?php echo $off['end_date'] ? formatDate($off['end_date']) : '-'; ?></td>
                            <td><?php echo $off['used_count']; ?><?php echo $off['max_uses'] ? '/' . $off['max_uses'] : ''; ?></td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-offer-status" type="checkbox" data-id="<?php echo $off['id']; ?>" <?php echo $off['is_active'] ? 'checked' : ''; ?>>
                                </div>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editOffer(<?php echo $off['id']; ?>)"><i class="fas fa-edit"></i></button>
                                <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/offer_save.php" data-name="<?php echo sanitize($off['title']); ?>" data-id="<?php echo $off['id']; ?>"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="offerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="offerForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="offAction" value="add">
                <input type="hidden" name="offer_id" id="offId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="offModalTitle">Add Offer</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label">Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title" id="offTitle" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Offer Type <span class="text-danger">*</span></label>
                            <select class="form-select" name="offer_type" id="offType">
                                <option value="percentage">Percentage</option>
                                <option value="fixed">Fixed Amount</option>
                                <option value="bogo">BOGO</option>
                                <option value="combo">Combo</option>
                                <option value="coupon">Coupon</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Description</label>
                            <textarea class="form-control" name="description" id="offDescription" rows="2"></textarea>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Banner Image</label>
                            <input type="file" class="form-control" name="banner_image" accept="image/*" data-preview="#offBannerPreview">
                            <img src="" id="offBannerPreview" class="img-preview-lg mt-2" style="display:none;">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Discount Value <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" class="form-control" name="discount_value" id="offDiscount" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Coupon Code</label>
                            <input type="text" class="form-control" name="coupon_code" id="offCoupon" placeholder="e.g., SAVE20" style="text-transform:uppercase;">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Min Order</label>
                            <input type="number" step="0.01" class="form-control" name="min_order" id="offMinOrder" value="0">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" class="form-control" name="start_date" id="offStartDate">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">End Date</label>
                            <input type="date" class="form-control" name="end_date" id="offEndDate">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Start Time</label>
                            <input type="time" class="form-control" name="start_time" id="offStartTime">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">End Time</label>
                            <input type="time" class="form-control" name="end_time" id="offEndTime">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Max Uses</label>
                            <input type="number" class="form-control" name="max_uses" id="offMaxUses" placeholder="Leave empty for unlimited">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" name="is_active" id="offStatus">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Applicable Categories</label>
                            <select class="form-select" name="categories[]" id="offCategories" multiple style="height:120px;">
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo sanitize($cat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Hold Ctrl/Cmd to select multiple</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Applicable Items</label>
                            <select class="form-select" name="items[]" id="offItems" multiple style="height:120px;">
                                <?php foreach ($menuItems as $mi): ?>
                                <option value="<?php echo $mi['id']; ?>"><?php echo sanitize($mi['name']); ?> (<?php echo formatCurrency($mi['regular_price'], $currency); ?>)</option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Hold Ctrl/Cmd to select multiple</small>
                        </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 Offer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetOfferForm() {
    document.getElementById('offAction').value = 'add';
    document.getElementById('offId').value = '';
    document.getElementById('offTitle').value = '';
    document.getElementById('offType').value = 'percentage';
    document.getElementById('offDescription').value = '';
    document.getElementById('offDiscount').value = '';
    document.getElementById('offCoupon').value = '';
    document.getElementById('offMinOrder').value = '0';
    document.getElementById('offStartDate').value = '';
    document.getElementById('offEndDate').value = '';
    document.getElementById('offStartTime').value = '';
    document.getElementById('offEndTime').value = '';
    document.getElementById('offMaxUses').value = '';
    document.getElementById('offStatus').value = '1';
    document.getElementById('offBannerPreview').style.display = 'none';
    document.getElementById('offModalTitle').textContent = 'Add Offer';
    document.getElementById('offCategories').selectedIndex = -1;
    document.getElementById('offItems').selectedIndex = -1;
}

function editOffer(id) {
    fetch(BASE_URL + '/restaurant-admin/offer_save.php?action=get&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var o = data.offer;
            document.getElementById('offAction').value = 'edit';
            document.getElementById('offId').value = o.id;
            document.getElementById('offTitle').value = o.title;
            document.getElementById('offType').value = o.offer_type;
            document.getElementById('offDescription').value = o.description || '';
            document.getElementById('offDiscount').value = o.discount_value;
            document.getElementById('offCoupon').value = o.coupon_code || '';
            document.getElementById('offMinOrder').value = o.min_order;
            document.getElementById('offStartDate').value = o.start_date || '';
            document.getElementById('offEndDate').value = o.end_date || '';
            document.getElementById('offStartTime').value = o.start_time || '';
            document.getElementById('offEndTime').value = o.end_time || '';
            document.getElementById('offMaxUses').value = o.max_uses || '';
            document.getElementById('offStatus').value = o.is_active;
            document.getElementById('offModalTitle').textContent = 'Edit Offer';
            if(o.banner_image){document.getElementById('offBannerPreview').src=BASE_URL+'/'+o.banner_image;document.getElementById('offBannerPreview').style.display='block';}
            if(o.applicable_categories){var cats=o.applicable_categories.split(',');for(var i=0;i<document.getElementById('offCategories').options.length;i++){document.getElementById('offCategories').options[i].selected=cats.indexOf(document.getElementById('offCategories').options[i].value)!==-1;}}
            if(o.applicable_items){var items=o.applicable_items.split(',');for(var i=0;i<document.getElementById('offItems').options.length;i++){document.getElementById('offItems').options[i].selected=items.indexOf(document.getElementById('offItems').options[i].value)!==-1;}}
            new bootstrap.Modal(document.getElementById('offerModal')).show();
        }
    });
}

document.getElementById('offerForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var form = this;
    var formData = new FormData(form);
    formData.append('csrf_token', CSRF_TOKEN);
    var cats = [];
    document.getElementById('offCategories').selectedOptions.forEach(function(o){cats.push(o.value);});
    formData.append('selected_categories', cats.join(','));
    var items = [];
    document.getElementById('offItems').selectedOptions.forEach(function(o){items.push(o.value);});
    formData.append('selected_items', items.join(','));
    fetch(BASE_URL + '/restaurant-admin/offer_save.php', {method:'POST',body:formData,headers:{'X-Requested-With':'XMLHttpRequest'}})
    .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);}
    });
});

document.querySelectorAll('.toggle-offer-status').forEach(function(toggle) {
    toggle.addEventListener('change', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        ajaxPost(BASE_URL + '/restaurant-admin/offer_save.php', 'action=toggle_status&id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) showAlert('success', data.message);
            else showAlert('danger', data.message);
        });
    });
});

document.querySelectorAll('.btn-ajax-delete[data-id]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        var name = this.dataset.name || 'this offer';
        if (confirm('Delete "' + name + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/offer_save.php', 'action=delete&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'; ?>
