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

$advertisements = $db->query("SELECT * FROM advertisements WHERE restaurant_id = ? ORDER BY created_at DESC", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Advertisements</h6>
        <small class="text-muted">Manage promotional banners and ads</small>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#adModal" onclick="resetAdForm()">
        <i class="fas fa-plus me-1"></i>Add Advertisement
    </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>Image</th><th>Title</th><th>Position</th><th>Start</th><th>End</th><th>Frequency</th><th>Status</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($advertisements as $ad): ?>
                        <tr>
                            <td>
                                <?php if (!empty($ad['image'])): ?>
                                    <img src="<?php echo $baseUrl . '/' . sanitize($ad['image']); ?>" style="width:60px;height:40px;object-fit:cover;border-radius:4px;">
                                <?php else: ?>
                                    <div class="bg-light d-flex align-items-center justify-content-center" style="width:60px;height:40px;border-radius:4px;"><i class="fas fa-image text-muted small"></i></div>
                                <?php endif; ?>
                            </td>
                            <td><strong><?php echo sanitize($ad['title'] ?? 'Untitled'); ?></strong></td>
                            <td><span class="badge bg-secondary"><?php echo ucfirst(str_replace('_', ' ', $ad['position'])); ?></span></td>
                            <td><?php echo $ad['start_date'] ? formatDate($ad['start_date']) : '-'; ?></td>
                            <td><?php echo $ad['end_date'] ? formatDate($ad['end_date']) : '-'; ?></td>
                            <td><?php echo ucfirst($ad['display_frequency'] ?? 'Always'); ?></td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-ad-status" type="checkbox" data-id="<?php echo $ad['id']; ?>" <?php echo $ad['is_active'] ? 'checked' : ''; ?>>
                                </div>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editAd(<?php echo $ad['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/advertisement_save.php" data-name="<?php echo sanitize($ad['title'] ?? 'Ad'); ?>" data-id="<?php echo $ad['id']; ?>"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="adModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="adForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="adAction" value="add">
                <input type="hidden" name="ad_id" id="adId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="adModalTitle">Add Advertisement</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</label>
                            <input type="text" class="form-control" name="title" id="adTitle">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Position <span class="text-danger">*</span></label>
                            <select class="form-select" name="position" id="adPosition" required>
                                <option value="top_banner">Top Banner</option>
                                <option value="hero_slider">Hero Slider</option>
                                <option value="section_banner">Section Banner</option>
                                <option value="popup">Popup</option>
                                <option value="bottom_sticky">Bottom Sticky</option>
                                <option value="category_banner">Category Banner</option>
                                <option value="checkout_banner">Checkout Banner</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="adDescription" rows="2"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Desktop Image</label>
                            <input type="file" class="form-control" name="image" accept="image/*" data-preview="#adImagePreview">
                            <img src="" id="adImagePreview" class="img-preview-lg mt-2" style="display:none;">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Mobile Image</label>
                            <input type="file" class="form-control" name="mobile_image" accept="image/*" data-preview="#adMobilePreview">
                            <img src="" id="adMobilePreview" class="img-preview-lg mt-2" style="display:none;">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Button Text</label>
                            <input type="text" class="form-control" name="button_text" id="adButtonText" placeholder="e.g., Order Now">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Button Link</label>
                            <input type="url" class="form-control" name="button_link" id="adButtonLink">
                        </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="adStartDate">
                        </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="adEndDate">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Frequency</label>
                            <select class="form-select" name="display_frequency" id="adFrequency">
                                <option value="always">Always</option>
                                <option value="once_per_session">Once per Session</option>
                                <option value="daily">Daily</option>
                                <option value="weekly">Weekly</option>
                            </select>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" name="is_active" id="adStatus">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </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>
function resetAdForm() {
    document.getElementById('adAction').value = 'add';
    document.getElementById('adId').value = '';
    document.getElementById('adTitle').value = '';
    document.getElementById('adPosition').value = 'top_banner';
    document.getElementById('adDescription').value = '';
    document.getElementById('adButtonText').value = '';
    document.getElementById('adButtonLink').value = '';
    document.getElementById('adStartDate').value = '';
    document.getElementById('adEndDate').value = '';
    document.getElementById('adFrequency').value = 'always';
    document.getElementById('adStatus').value = '1';
    document.getElementById('adImagePreview').style.display = 'none';
    document.getElementById('adMobilePreview').style.display = 'none';
    document.getElementById('adModalTitle').textContent = 'Add Advertisement';
}

function editAd(id) {
    fetch(BASE_URL + '/restaurant-admin/advertisement_save.php?action=get&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var a = data.ad;
            document.getElementById('adAction').value = 'edit';
            document.getElementById('adId').value = a.id;
            document.getElementById('adTitle').value = a.title || '';
            document.getElementById('adPosition').value = a.position;
            document.getElementById('adDescription').value = a.description || '';
            document.getElementById('adButtonText').value = a.button_text || '';
            document.getElementById('adButtonLink').value = a.button_link || '';
            document.getElementById('adStartDate').value = a.start_date || '';
            document.getElementById('adEndDate').value = a.end_date || '';
            document.getElementById('adFrequency').value = a.display_frequency || 'always';
            document.getElementById('adStatus').value = a.is_active;
            document.getElementById('adModalTitle').textContent = 'Edit Advertisement';
            if(a.image){document.getElementById('adImagePreview').src=BASE_URL+'/'+a.image;document.getElementById('adImagePreview').style.display='block';}
            if(a.mobile_image){document.getElementById('adMobilePreview').src=BASE_URL+'/'+a.mobile_image;document.getElementById('adMobilePreview').style.display='block';}
            new bootstrap.Modal(document.getElementById('adModal')).show();
        }
    });
}

document.getElementById('adForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('csrf_token', CSRF_TOKEN);
    fetch(BASE_URL + '/restaurant-admin/advertisement_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-ad-status').forEach(function(toggle) {
    toggle.addEventListener('change', function(e) {
        e.preventDefault();
        ajaxPost(BASE_URL + '/restaurant-admin/advertisement_save.php', 'action=toggle_status&id=' + this.dataset.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();
        if (confirm('Delete "' + (this.dataset.name || 'this ad') + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/advertisement_save.php', 'action=delete&id=' + this.dataset.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'; ?>
