<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest') {
    header('Content-Type: application/json; charset=utf-8');
    $auth = new Auth();
    if (!$auth->check() || !$auth->isSuperAdmin()) { jsonResponse(false, 'Unauthorized', [], 401); }

    $csrf = new CSRF();
    if (!$csrf->verify($_POST['csrf_token'] ?? '')) { jsonResponse(false, 'Invalid CSRF token.'); }

    $db = Database::getInstance();
    $action = $_POST['action'] ?? '';

    if ($action === 'mark_read') {
        $enqId = (int) ($_POST['id'] ?? 0);
        if ($enqId > 0) {
            $db->update('enquiries', ['status' => 'read'], 'id = ?', [$enqId]);
            jsonResponse(true, 'Enquiry marked as read.');
        }
        jsonResponse(false, 'Invalid enquiry.');
    }

    if ($action === 'delete') {
        $enqId = (int) ($_POST['id'] ?? 0);
        if ($enqId > 0) {
            $db->delete('enquiries', 'id = ?', [$enqId]);
            jsonResponse(true, 'Enquiry deleted.');
        }
        jsonResponse(false, 'Invalid enquiry.');
    }

    jsonResponse(false, 'Invalid action.');
}

$pageTitle = 'Enquiries';
require_once __DIR__ . '/includes/header.php';
$db = Database::getInstance();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <form class="d-flex gap-2" method="GET">
        <select name="status" class="form-select form-select-sm" style="width:130px;">
            <option value="">All Status</option>
            <option value="new" <?php echo ($_GET['status'] ?? '') === 'new' ? 'selected' : ''; ?>>New</option>
            <option value="read" <?php echo ($_GET['status'] ?? '') === 'read' ? 'selected' : ''; ?>>Read</option>
            <option value="replied" <?php echo ($_GET['status'] ?? '') === 'replied' ? 'selected' : ''; ?>>Replied</option>
        </select>
        <input type="text" name="search" class="form-control form-control-sm" placeholder="Search..." value="<?php echo sanitize($_GET['search'] ?? ''); ?>" style="width:180px;">
        <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-search"></i></button>
    </form>
</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>ID</th><th>Name</th><th>Restaurant</th><th>Phone</th><th>Email</th><th>City</th><th>Plan</th><th>Status</th><th>Date</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT * FROM enquiries WHERE 1=1";
                    $params = [];
                    if (!empty($_GET['status'])) {
                        $sql .= " AND status = ?";
                        $params[] = $_GET['status'];
                    }
                    if (!empty($_GET['search'])) {
                        $s = "%" . $_GET['search'] . "%";
                        $sql .= " AND (name LIKE ? OR restaurant_name LIKE ? OR email LIKE ? OR phone LIKE ?)";
                        $params[] = $s;
                        $params[] = $s;
                        $params[] = $s;
                        $params[] = $s;
                    }
                    $sql .= " ORDER BY created_at DESC";
                    $enquiries = $db->query($sql, $params)->fetchAll();
                    ?>
                    <?php foreach ($enquiries as $enq): ?>
                    <tr>
                        <td><?php echo $enq['id']; ?></td>
                        <td><strong><?php echo sanitize($enq['name']); ?></strong></td>
                        <td><?php echo sanitize($enq['restaurant_name'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($enq['phone'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($enq['email'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($enq['city'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($enq['preferred_plan'] ?? 'N/A'); ?></td>
                        <td>
                            <?php
                            $eClass = ['new'=>'primary','read'=>'info','replied'=>'success'];
                            ?>
                            <span class="badge bg-<?php echo $eClass[$enq['status']] ?? 'secondary'; ?>"><?php echo ucfirst($enq['status']); ?></span>
                        </td>
                        <td><?php echo timeAgo($enq['created_at']); ?></td>
                        <td>
                            <button class="btn btn-sm btn-outline-info btn-action view-enquiry-btn"
                                data-id="<?php echo $enq['id']; ?>"
                                data-name="<?php echo sanitize($enq['name']); ?>"
                                data-restaurant="<?php echo sanitize($enq['restaurant_name'] ?? ''); ?>"
                                data-phone="<?php echo sanitize($enq['phone'] ?? ''); ?>"
                                data-email="<?php echo sanitize($enq['email'] ?? ''); ?>"
                                data-city="<?php echo sanitize($enq['city'] ?? ''); ?>"
                                data-plan="<?php echo sanitize($enq['preferred_plan'] ?? ''); ?>"
                                data-message="<?php echo sanitize($enq['message'] ?? ''); ?>"
                                data-status="<?php echo $enq['status']; ?>"
                                data-date="<?php echo formatDateTime($enq['created_at']); ?>"
                                title="View"><i class="fas fa-eye"></i></button>
                            <button class="btn btn-sm btn-outline-success btn-action mark-read-btn" data-id="<?php echo $enq['id']; ?>" title="Mark Read"><i class="fas fa-check"></i></button>
                            <button class="btn btn-sm btn-outline-danger btn-action delete-enq-btn" data-id="<?php echo $enq['id']; ?>" title="Delete"><i class="fas fa-trash"></i></button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="enquiryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enquiry Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row g-2 mb-3">
                    <div class="col-6"><strong>Name:</strong> <span id="eqName"></span></div>
                    <div class="col-6"><strong>Date:</strong> <span id="eqDate"></span></div>
                    <div class="col-6"><strong>Restaurant:</strong> <span id="eqRestaurant"></span></div>
                    <div class="col-6"><strong>City:</strong> <span id="eqCity"></span></div>
                    <div class="col-6"><strong>Phone:</strong> <span id="eqPhone"></span></div>
                    <div class="col-6"><strong>Email:</strong> <span id="eqEmail"></span></div>
                    <div class="col-6"><strong>Plan:</strong> <span id="eqPlan"></span></div>
                    <div class="col-6"><strong>Status:</strong> <span id="eqStatus"></span></div>
                </div>
                <div>
                    <strong>Message:</strong>
                    <p class="border p-3 bg-light rounded mt-1" id="eqMessage"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.view-enquiry-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        document.getElementById('eqName').textContent = this.dataset.name;
        document.getElementById('eqRestaurant').textContent = this.dataset.restaurant || 'N/A';
        document.getElementById('eqPhone').textContent = this.dataset.phone || 'N/A';
        document.getElementById('eqEmail').textContent = this.dataset.email || 'N/A';
        document.getElementById('eqCity').textContent = this.dataset.city || 'N/A';
        document.getElementById('eqPlan').textContent = this.dataset.plan || 'N/A';
        document.getElementById('eqMessage').textContent = this.dataset.message || 'No message';
        document.getElementById('eqDate').textContent = this.dataset.date;
        document.getElementById('eqStatus').textContent = this.dataset.status;
        new bootstrap.Modal(document.getElementById('enquiryModal')).show();
        if (this.dataset.status === 'new') {
            var self = this;
            ajaxPost(BASE_URL + '/admin/enquiries.php', 'action=mark_read&id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function() {});
        }
    });
});

document.querySelectorAll('.mark-read-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        ajaxPost(BASE_URL + '/admin/enquiries.php', 'action=mark_read&id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) {
                showAlert('success', data.message);
                setTimeout(function() { location.reload(); }, 1000);
            }
        });
    });
});

document.querySelectorAll('.delete-enq-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var id = this.dataset.id;
        if (confirm('Delete this enquiry?')) {
            ajaxPost(BASE_URL + '/admin/enquiries.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'; ?>
