<?php
$path = preg_replace( '/wp-content.*$/', '', __DIR__ );
require_once( str_replace("wp-content/plugins/inflatableoffice/remove_orphan_pages.php", "wp-load.php", $_SERVER['SCRIPT_FILENAME']) );
$curl_handle = curl_init();

$post_data = "username=".$_REQUEST["username"]."&location=".$_REQUEST["location"]."&url=".$_REQUEST["url"];
//curl_setopt($curl_handle,CURLOPT_URL,'http://localhost/io/bugs/wp-plugin/orphan_page_search.php');
curl_setopt($curl_handle,CURLOPT_URL,'https://rental.software/wp-plugin/orphan_page_search.php');
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_handle, CURLOPT_TIMEOUT_MS, 1000);
curl_setopt($curl_handle, CURLOPT_POST,1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,true);
$correct_page_ids = json_decode(curl_exec($curl_handle));
if(!is_array($correct_page_ids) || empty($correct_page_ids)){
    exit;
}

if ( is_multisite() ) {
    // This is a multisite environment
    $domain = parse_url($_REQUEST["url"], PHP_URL_HOST );
    $path = parse_url($_REQUEST["url"], PHP_URL_PATH )."/";
    $details = get_blog_details( array(
        'domain' => $domain,
        'path'   => $path
    ) );
    if ( $details ) {
        switch_to_blog($details->blog_id);
    }
}

$args = array( 'orderby'=>'name','order'=>'ASC', 'posts_per_page' => -1,'post_type' => 'page');
$loop = new WP_Query( $args );
$orphan_pages = [];
while ( $loop->have_posts() ) : $loop->the_post();
    $id = strval(get_the_id());
    $content = get_the_content();
    if(str_contains($content, "[sc :io_")){
        if(!in_array($id, $correct_page_ids)){
            $orphan_pages[] = $id;
        }
    }
endwhile;
foreach($orphan_pages as $orphan){
    wp_trash_post($orphan);
}