=== Listeo SMS Notifications & OTP Verification ===
Contributors: purethemes
Donate link: https://themeforest.net/user/purethemes
Tags: listeo, sms, twilio, whatsapp, web push, notifications, otp
Requires at least: 6.0
Tested up to: 6.9
Requires PHP: 7.4
Stable tag: 2.0
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html

SMS (Twilio), WhatsApp and Web Push notifications for Listeo bookings and listings, with per-user preferences, delivery log and phone OTP verification.

== Description ==

Listeo SMS Notifications & OTP Verification is an add-on for the Listeo directory theme. It sends text and push notifications for the booking and listing events that Listeo Core already fires, and adds phone number verification to registration and login.

**Channels**

* **SMS via Twilio** for around 20 Listeo events: new reservation (regular and instant), waiting for approval, approved, paid, cash payment confirmed, free booking confirmed, waiting for payment, canceled (user and owner), upcoming booking, review reminder, new review for the owner, listing submitted (user and admin), listing published, listing expiring soon and listing expired. Every event has its own on/off switch and editable message template with placeholders.
* **WhatsApp** through Twilio or the Meta WhatsApp Cloud API, with separate WhatsApp message templates.
* **Web Push** browser notifications for logged-in users. Self-hosted delivery (VAPID) is built in and needs no extra libraries; OneSignal can be used instead. Users subscribe from their notification preferences.

**Booking reminders**

Turn on Scheduled Booking Reminders and add a suggested time (day before or hour before), or choose a number of minutes, hours or days before the booking. Select SMS, WhatsApp and/or Web Push for each reminder and edit its messages in the same card. Save Settings applies every reminder change at once. Changing a time keeps its messages and notification preferences.

Reminders apply to confirmed, paid and approved bookings. The scheduler checks once per minute through WP-Cron, so actual delivery depends on your site's cron execution. It never intentionally sends before the selected time. After a delayed run it catches up only the most recent reminder due on each channel, and skips bookings that have already started. Scheduled reminders replace the older Upcoming booking notification on the channels used by active reminder rules; email notifications are unaffected.

**Per-user preferences**

Site-wide defaults decide which channels each event may use. Users can override them for their own account via the `[listeo_notification_preferences]` shortcode or the Notifications box shown in Listeo's My Account page.

Preferences appear for enabled channels even while provider setup is incomplete. Self-hosted Web Push device controls become available after VAPID keys are configured; until then the panel explains that push is unavailable and gives administrators a setup link.

The "Receive SMS notifications" switch in Notifications pauses all SMS without clearing individual choices. It replaces the older "Turn off SMS Notifications" control in Profile Details when the multi-channel engine and SMS channel are enabled. Existing opt-outs are preserved. Use Save preferences to apply both the master switch and detailed choices; phone verification codes are unaffected.

Notification preferences use inline SVG icons. The WhatsApp mark is from Font Awesome Free 5.15.1 by Font Awesome (https://fontawesome.com), licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/); the bundled font glyph is transformed for inline SVG display.

**Delivery log**

Every message is recorded with its channel, event, recipient and result. The log can be filtered by channel and status and purged of entries older than a chosen number of days.

**Phone OTP verification**

A one-time code is sent by SMS during registration and login. The message text is editable.

**Other**

* Templates are WPML and Polylang aware: messages are rendered in the recipient's language when a translation exists.
* Debug Mode is a separate switch under **Notifications -> Logs & Debug**. It simulates messages on all channels without provider credentials. Message details go to `wp-content/debug.log` when WordPress debug logging is enabled.
* Settings live under **Listeo -> Settings -> Notifications**.

== Installation ==

1. Install and activate the Listeo theme and the Listeo Core plugin. This add-on does nothing without them.
2. Upload the `listeo-sms` folder to `/wp-content/plugins/` and activate the plugin through the Plugins menu.
3. Go to **Listeo -> Settings -> Notifications**.
4. Enter your Twilio Account SID, Auth Token and Twilio Sender.
5. Enable the events you want to send and adjust the message templates. Optionally configure WhatsApp, Web Push and Scheduled Booking Reminders in the same settings page.

== Frequently Asked Questions ==

= What can I enter in the "Twilio Sender" field? =

One of three values: a Twilio phone number in international E.164 format (for example `+12025551234`), an Alphanumeric Sender ID (for example `PetFlex`, max 11 characters, one-way SMS only, not available for US/Canada), or a Twilio Messaging Service SID starting with `MG`. A Messaging Service SID is sent as `messagingServiceSid`; anything else is used as the `from` sender.

= Messages are not being sent. What should I check? =

* Check Debug Mode under **Notifications -> Logs & Debug**. When enabled, it simulates sending. Message details are written to `wp-content/debug.log` when WordPress debug logging is enabled.
* The event is not enabled. Each event has its own switch in the Notifications tab, and for WhatsApp/Web Push the channel itself must be enabled too.
* The recipient's phone number is not in international E.164 format (`+` followed by country code and number). Numbers are normalized before sending, but a number without a country code cannot be delivered.
* For the "new listing submitted" admin SMS, the admin phone number must be set in the settings.

= Can I send SMS through a provider other than Twilio? =

Yes, with a small code snippet. Twilio is the built-in provider, but every message the plugin sends (all booking and listing notifications, the scheduled reminders and the login/registration OTP) goes through a single function, and that function offers the `listeo_sms_pre_send` filter. Return anything other than `null` from a callback and your own gateway takes over; Twilio is skipped and never called. Local providers with a plain HTTP API can be connected in a few lines.

Put the snippet in a small plugin of your own (or a `mu-plugins` file) so it survives plugin and theme updates:

`
add_filter( 'listeo_sms_pre_send', function ( $result, $to, $body ) {
	$response = wp_remote_post( 'https://gateway.example.com/api/send', array(
		'timeout' => 15,
		'body'    => array(
			'username' => 'my-user',
			'token'    => 'my-token',
			'to'       => ltrim( $to, '+' ), // $to arrives as +972501234567
			'message'  => $body,
		),
	) );

	if ( is_wp_error( $response ) ) {
		return $response; // failure, the reason lands in the delivery log
	}

	$code = wp_remote_retrieve_response_code( $response );

	return array(
		'sent'   => 200 === $code,
		'status' => $code,
		'error'  => wp_remote_retrieve_body( $response ),
	);
}, 10, 3 );
`

The number arrives already normalized: international input, and any national number that can be completed with the "Default country code" setting, is passed in E.164 format with a leading plus. A national number on a site with no default country code configured is passed through exactly as the user typed it, which is the same value Twilio would have received, so a gateway that insists on E.164 should check for the leading plus itself.

A callback may also simply return `true` or `false`, or a `WP_Error` whose message is stored with the delivery log entry. Returning an `id` records the provider's message id in the log, just like the Twilio SID. Returning anything else that is not one of those documented shapes (an HTTP response object, for example) is treated as a failed send, never as a silent success.

Debug Mode is evaluated before the filter, so it keeps simulating sends without contacting your gateway.

WhatsApp has the same seam, `listeo_notification_whatsapp_pre_send`, with the signature `( $result, $to, $body, $context )`. It runs before both the Twilio and the Meta Cloud API providers.

= How are national phone numbers handled? =

Use `+` or `00` before the country code for international numbers. Other numbers are treated as national when "Default country code" is configured, even if their first digits happen to match that country code. For example, national `481234567` with default `+48` becomes `+48481234567`. Without a default, WhatsApp rejects national numbers. The default-country conversion removes leading zeros; for countries that retain them internationally, enter the full international number with `+`.

= Can WhatsApp send unattended booking reminders? =

The built-in provider requests currently send free-form text. WhatsApp requires approved templates for business-initiated messages outside the 24-hour customer service window. Production template selection and variable mapping are still pending; the Meta payload filter can be used by a developer to supply an approved template. See https://www.twilio.com/docs/content/session-definitions .

= Does "sent" in the log confirm delivery to the phone? =

It means the provider accepted the request (or Debug Mode simulated it). The SMS log retains the Twilio message SID and errors reported during the request. Later delivery failures require provider status callbacks, which are not implemented yet.

= Can I turn off the WhatsApp / Web Push / reminders engine and keep only the original SMS behaviour? =

Yes. Add `define( 'LISTEO_NOTIFICATIONS_PLUS_DISABLED', true );` to `wp-config.php`. The plugin then falls back to the legacy SMS-only event hooks.

= Does uninstalling remove the plugin's data? =

Yes. Deleting the plugin from the Plugins screen drops the delivery log and push subscription tables, removes all plugin options (including the per-event templates) and the per-user notification preferences, and unschedules the reminder cron event. The legacy per-user `sms_notifications` opt-out flag and the "already sent" markers on listings are left in place.

== Changelog ==

= 2.0 =
* Developers can now send SMS through any provider instead of Twilio, using the new `listeo_sms_pre_send` filter. It covers every notification, the scheduled reminders and the phone OTP, because all of them share one send function. WhatsApp has the matching `listeo_notification_whatsapp_pre_send` filter. Twilio remains the default and nothing changes for sites that do not use the filters. See the FAQ for a ready-to-use example.

= 1.3.0 =
* Release hardening: blank WhatsApp credential overrides inherit SMS credentials correctly; international phone addressing no longer guesses a country from matching leading digits.
* SMS delivery logs retain the provider message SID and immediate error details; provider exceptions do not interrupt the remaining notification channels.
* Fallback delivery respects user preferences and avoids duplicate attempts; recipient language is restored even after an error.
* Multiline notification templates preserve plain-text line breaks.
* Disabled phone OTP cannot be used to request SMS; failed sends remove the stored verification code. The companion Listeo Core update strictly validates registration codes and consumes the code after successful AJAX registration.
* The multi-channel notification engine (WhatsApp, Web Push, scheduled booking reminders, per-user preferences, delivery log) is now part of the Notifications settings tab and always on. Existing SMS behaviour is unchanged.
* The phone OTP endpoint now verifies the security token and limits attempts per phone number and per IP address.
* Phone numbers are normalized to international E.164 format before sending.
* The admin phone number for the "new listing submitted" SMS can now be configured in the settings, and its message text can be edited.
* OTP verification works while Debug Mode is enabled.
* Push subscription storage hardened.
* The Notifications settings tab is split into sub-tabs: SMS Configurations, WhatsApp, Web Push, reminders, fallback, default preferences and Logs & Debug. SMS Configurations groups basic settings, OTP, provider credentials and listing/booking messages in one place. Enabling SMS reveals its event fields within that same tab. WhatsApp and Web Push settings and message templates only appear when that channel is enabled, provider fields follow the selected provider, and each message text is shown only when its event is switched on.
* Logs & Debug contains the global Debug Mode switch and a redesigned delivery history: full-width layout, labelled filters, readable event/channel/status names, expandable error/provider details, contextual empty states and a separate cleanup section. Pagination keeps the selected filters and active tab.
* SMS Configurations shows configuration, providers, listing notifications and booking/payment notifications as separate native sections on the same screen. The SMS switch controls the two event sections. This grouping uses the companion Listeo Core settings update.
* WhatsApp and Web Push message templates come pre-filled with a sensible default text for every event, which is also what gets sent when a template is left empty.
* The notification preferences in My Account use groups that start collapsed: "Your bookings", "Bookings on your listings" and "Your listings" (only the groups that apply to your account). Expand a group to choose individual notifications or toggle its entire channel. Controls use the same switches as the other profile settings, with a centered knob for partially selected groups. Channel columns stay aligned, controls support keyboard navigation, and the current-device push status remains visible above the groups.
* New "Send a test notification to my devices" button next to the VAPID keys checks Web Push end to end without creating a booking, and a "Send a WhatsApp test message" button (with a phone number field) does the same for WhatsApp.
* Disabling push on a device from the preference center now completes (it previously waited forever for the service worker).
* Plugin translations now load from the languages folder (text domain `listeo-sms`).
* Uninstalling the plugin removes its database tables and options.
* Version numbers (plugin header, constant and internal version) unified.

= 1.2 =
* Twilio sender now accepts a Messaging Service SID. If the "Twilio Sender" setting is an "MG..." Messaging Service SID it is sent via Twilio's messagingServiceSid parameter; phone numbers and Alphanumeric Sender IDs (e.g. "PetFlex") continue to be sent as the "from" sender. The setting label/description were updated to explain the three accepted value types.
