<?php
/*
Plugin Name: Bookly - LOCALiQ - Caching Buster
Description: Bookly - LOCALiQ - Caching Buster Plugin – This plugin must be activated to successfully use Bookly with our themes on Pantheon.
Version: 0.2
Author: Gannett / Pantheon
Author URI: https://localiq.com
License: GPLv3
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/*
 * Set $regex_path_patterns accordingly.
 *
 * We don't set this variable for you, so you must define it
 * yourself per your specific use case before the following conditional.
 *
 * For example, to exclude pages in the /news/ and /about/ path from cache, set:
 *
 *   $regex_path_patterns = array(
 *     '#^/news/?#',
 *     '#^/about/?#',
 *   );
 */

$regex_path_patterns = array(
    '#^/book/?#',
    '#^/booking/?#',
    '#^/schedule/?#',
    '#^/reserve/?#',
    '#^/consult/?#',
    '#^/appointments/?#',
    '#^/booking-success/?#',
    '#^/booking-denied/?#',
    '#^/cancelled-appointment/?#',
    '#^/booking-thanks/?#',
    '#^/booking-about/?#',
    '#^/booking-confirmation/?#',
    '#^/rejected-appointment/?#',
    '#^/rejection-denied/?#',
    '#^/staff-login/?#',
    '#^/client-login/?#',

);

// Loop through the patterns.
foreach ($regex_path_patterns as $regex_path_pattern) {
    if (preg_match($regex_path_pattern, $_SERVER['REQUEST_URI'])) {
        add_action( 'send_headers', 'add_header_nocache', 15 );

        // No need to continue the loop once there's a match.
        break;
    }
}
function add_header_nocache() {
    header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
}


/* For WP REST API specific paths, we use a different approach by using the rest_post_dispatch filter */

// wp-json paths or any custom endpoints 
$regex_json_path_patterns = array(
    '#^/wp-json/wp/v2?#',
    '#^/wp-json/?#'
);

foreach ($regex_json_path_patterns as $regex_json_path_pattern) {
    if (preg_match($regex_json_path_pattern, $_SERVER['REQUEST_URI'])) {
        // re-use the rest_post_dispatch filter in the Pantheon page cache plugin
        add_filter( 'rest_post_dispatch', 'filter_rest_post_dispatch_send_cache_control', 12, 2 );

        // Re-define the send_header value with any custom Cache-Control header
        function filter_rest_post_dispatch_send_cache_control( $response, $server ) {
            $server->send_header( 'Cache-Control', 'no-cache, must-revalidate, max-age=0' );
            return $response;
        }
        break;
    }
}