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

$db = Database::getInstance();

$statusFilter = $_GET['status'] ?? '';
$planFilter = $_GET['plan'] ?? '';
$search = $_GET['search'] ?? '';

$plans = $db->query("SELECT id, name FROM subscription_plans ORDER BY sort_order ASC")->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <form class="d-flex gap-2" method="GET">
            <select name="status" class="form-select form-select-sm" style="width:150px;">
                <option value="">All Status</option>
                <option value="active" <?php echo $statusFilter === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="trial" <?php echo $statusFilter === 'trial' ? 'selected' : ''; ?>>Trial</option>
                <option value="suspended" <?php echo $statusFilter === 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                <option value="expired" <?php echo $statusFilter === 'expired' ? 'selected' : ''; ?>>Expired</option>
                <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
            </select>
            <select name="plan" class="form-select form-select-sm" style="width:150px;">
                <option value="">All Plans</option>
                <?php foreach ($plans as $p): ?>
                    <option value="<?php echo $p['id']; ?>" <?php echo $planFilter == $p['id'] ? 'selected' : ''; ?>><?php echo sanitize($p['name']); ?></option>
                <?php endforeach; ?>
            </select>
            <input type="text" name="search" class="form-control form-control-sm" placeholder="Search..." value="<?php echo sanitize($search); ?>" style="width:200px;">
            <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-search"></i></button>
            <a href="restaurants.php" class="btn btn-sm btn-outline-secondary">Reset</a>
        </form>
    </div>
    <a href="restaurant_add.php" class="btn btn-primary btn-sm"><i class="fas fa-plus me-1"></i>Add Restaurant</a>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable" id="restaurantsTable">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Owner</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Plan</th>
                        <th>Status</th>
                        <th>Mode</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $sql = "SELECT r.*, sp.name as plan_name, u.name as owner_name, u.email as owner_email
                            FROM restaurants r
                            LEFT JOIN subscription_plans sp ON r.plan_id = sp.id
                            LEFT JOIN users u ON u.restaurant_id = r.id AND u.role_id = 2
                            WHERE 1=1";
                    $params = [];

                    if (!empty($statusFilter)) {
                        $sql .= " AND r.status = ?";
                        $params[] = $statusFilter;
                    }
                    if (!empty($planFilter)) {
                        $sql .= " AND r.plan_id = ?";
                        $params[] = $planFilter;
                    }
                    if (!empty($search)) {
                        $sql .= " AND (r.name LIKE ? OR r.email LIKE ? OR r.phone LIKE ? OR r.code LIKE ?)";
                        $s = "%{$search}%";
                        $params[] = $s;
                        $params[] = $s;
                        $params[] = $s;
                        $params[] = $s;
                    }

                    $sql .= " ORDER BY r.created_at DESC";
                    $restaurants = $db->query($sql, $params)->fetchAll();
                    ?>
                    <?php foreach ($restaurants as $rest): ?>
                    <tr>
                        <td><?php echo $rest['id']; ?></td>
                        <td>
                            <a href="restaurant_view.php?id=<?php echo $rest['id']; ?>" class="fw-bold text-decoration-none">
                                <?php echo sanitize($rest['name']); ?>
                            </a>
                            <div class="text-muted" style="font-size:11px;"><?php echo sanitize($rest['code']); ?></div>
                        </td>
                        <td><?php echo sanitize($rest['owner_name'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($rest['email'] ?? 'N/A'); ?></td>
                        <td><?php echo sanitize($rest['phone'] ?? 'N/A'); ?></td>
                        <td><span class="badge bg-info"><?php echo sanitize($rest['plan_name'] ?? 'None'); ?></span></td>
                        <td>
                            <?php
                            $statusClass = ['active'=>'success','trial'=>'warning','suspended'=>'danger','expired'=>'secondary','cancelled'=>'dark'];
                            $cls = $statusClass[$rest['status']] ?? 'secondary';
                            ?>
                            <span class="badge bg-<?php echo $cls; ?>"><?php echo ucfirst(sanitize($rest['status'])); ?></span>
                        </td>
                        <td><?php echo $rest['operating_mode'] == 1 ? 'View Only' : 'Ordering'; ?></td>
                        <td><?php echo timeAgo($rest['created_at']); ?></td>
                        <td>
                            <div class="d-flex gap-1">
                                <a href="restaurant_view.php?id=<?php echo $rest['id']; ?>" class="btn btn-sm btn-outline-info btn-action" title="View"><i class="fas fa-eye"></i></a>
                                <a href="restaurant_edit.php?id=<?php echo $rest['id']; ?>" class="btn btn-sm btn-outline-primary btn-action" title="Edit"><i class="fas fa-edit"></i></a>
                                <?php if ($rest['status'] === 'active' || $rest['status'] === 'trial'): ?>
                                    <button type="button" class="btn btn-sm btn-outline-warning btn-action toggle-status-btn" data-id="<?php echo $rest['id']; ?>" data-action="toggle_status" title="Suspend"><i class="fas fa-ban"></i></button>
                                <?php else: ?>
                                    <button type="button" class="btn btn-sm btn-outline-success btn-action toggle-status-btn" data-id="<?php echo $rest['id']; ?>" data-action="toggle_status" title="Activate"><i class="fas fa-check"></i></button>
                                <?php endif; ?>
                                <button type="button" class="btn btn-sm btn-outline-danger btn-action delete-btn" data-id="<?php echo $rest['id']; ?>" data-name="<?php echo sanitize($rest['name']); ?>" title="Delete"><i class="fas fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
$(document).on('click', '.toggle-status-btn', function() {
    var id = $(this).data('id');
    if (confirm('Are you sure you want to toggle this restaurant\'s status?')) {
        ajaxPost(BASE_URL + '/admin/restaurant_action.php', 'action=toggle_status&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);
            }
        });
    }
});

$(document).on('click', '.delete-btn', function() {
    var id = $(this).data('id');
    var name = $(this).data('name');
    if (confirm('Are you sure you want to delete "' + name + '"? This action cannot be undone.')) {
        ajaxPost(BASE_URL + '/admin/restaurant_action.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'; ?>
