<?php
$pageTitle = 'Testimonials';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
$testimonials = $db->query("SELECT * FROM testimonials ORDER BY sort_order ASC, created_at DESC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h6 class="mb-0">Manage Testimonials</h6>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#testimonialModal" onclick="resetTestForm()"><i class="fas fa-plus me-1"></i>Add Testimonial</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>Restaurant</th><th>Role</th><th>Rating</th><th>Content</th><th>Active</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($testimonials as $t): ?>
                    <tr>
                        <td><?php echo $t['sort_order']; ?></td>
                        <td><strong><?php echo sanitize($t['name']); ?></strong></td>
                        <td><?php echo sanitize($t['restaurant_name'] ?? ''); ?></td>
                        <td><?php echo sanitize($t['role'] ?? ''); ?></td>
                        <td><?php for ($i = 0; $i < $t['rating']; $i++) { echo '<i class="fas fa-star text-warning" style="font-size:12px;"></i>'; } ?></td>
                        <td><?php echo sanitize(truncate($t['content'], 80)); ?></td>
                        <td><span class="badge bg-<?php echo $t['is_active'] ? 'success' : 'secondary'; ?>"><?php echo $t['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary btn-action edit-test-btn" data-id="<?php echo $t['id']; ?>" title="Edit"><i class="fas fa-edit"></i></button>
                            <button class="btn btn-sm btn-outline-danger btn-action delete-test-btn" data-id="<?php echo $t['id']; ?>" data-name="<?php echo sanitize($t['name']); ?>" title="Delete"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="testimonialModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="testModalTitle">Add Testimonial</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form id="testForm">
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="testimonial_id" id="test_id" value="">
                    <div class="row g-3">
                        <div class="col-md-4"><label class="form-label">Name <span class="text-danger">*</span></label><input type="text" class="form-control" name="name" id="test_name" required></div>
                        <div class="col-md-4"><label class="form-label">Restaurant</label><input type="text" class="form-control" name="restaurant_name" id="test_restaurant"></div>
                        <div class="col-md-4"><label class="form-label">Role</label><input type="text" class="form-control" name="role" id="test_role" placeholder="e.g. Owner"></div>
                        <div class="col-md-12"><label class="form-label">Content <span class="text-danger">*</span></label><textarea class="form-control" name="content" id="test_content" rows="3" required></textarea></div>
                        <div class="col-md-4"><label class="form-label">Image</label><input type="file" class="form-control" name="image" accept="image/*"></div>
                        <div class="col-md-2"><label class="form-label">Rating</label><select class="form-select" name="rating" id="test_rating"><?php for ($i = 5; $i >= 1; $i--): ?><option value="<?php echo $i; ?>"><?php echo $i; ?></option><?php endfor; ?></select></div>
                        <div class="col-md-2"><label class="form-label">Sort</label><input type="number" class="form-control" name="sort_order" id="test_sort" value="0"></div>
                        <div class="col-md-4"><div class="form-check mt-4"><input class="form-check-input" type="checkbox" name="is_active" id="test_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 testData = <?php echo json_encode($testimonials, JSON_HEX_TAG | JSON_HEX_AMP); ?>;

function resetTestForm() {
    document.getElementById('testModalTitle').textContent = 'Add Testimonial';
    document.getElementById('testForm').reset();
    document.getElementById('test_id').value = '';
}

document.querySelectorAll('.edit-test-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var t = testData.find(function(x) { return x.id == btn.dataset.id; });
        if (!t) return;
        document.getElementById('testModalTitle').textContent = 'Edit Testimonial';
        document.getElementById('test_id').value = t.id;
        document.getElementById('test_name').value = t.name;
        document.getElementById('test_restaurant').value = t.restaurant_name || '';
        document.getElementById('test_role').value = t.role || '';
        document.getElementById('test_content').value = t.content;
        document.getElementById('test_rating').value = t.rating;
        document.getElementById('test_sort').value = t.sort_order;
        document.getElementById('test_active').checked = t.is_active == 1;
        new bootstrap.Modal(document.getElementById('testimonialModal')).show();
    });
});

document.getElementById('testForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var fd = new FormData(this);
    fetch(BASE_URL + '/admin/testimonial_save.php', { method: 'POST', body: fd, processData: false, contentType: false })
    .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-test-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        if (confirm('Delete testimonial from "' + this.dataset.name + '"?')) {
            ajaxPost(BASE_URL + '/admin/testimonial_save.php', 'action=delete&testimonial_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'; ?>
