<?php
$path = preg_replace( '/wp-content.*$/', '', __DIR__ );
require_once( str_replace("wp-content/plugins/inflatableoffice/website_filter.php", "wp-load.php", $_SERVER['SCRIPT_FILENAME']) );
//require_once( "C:/WWW/wp-bugs/wp-load.php" );
//require_once( __DIR__."/../../wp-load.php" );

$args = array( 'orderby'=>'name','order'=>'ASC', 'posts_per_page' => -1,'post_type' => 'page');
$style =
$loop = new WP_Query( $args );
$flag_feature_count=0;
$posts = Array();
$titles = Array();
$i=0;
while ( $loop->have_posts() ) : $loop->the_post();
    $title = get_the_title();
    $posts[] = Array(
        'order'=>$i,
        'id'=>get_the_id(),
        'content'=>get_the_content(),
        'permalink'=>get_permalink(),
        'title'=>$title,
    );
    $titles[] = trim(html_entity_decode($title));
    $i++;
endwhile;

//use inventory page to set order
$io_inventory_page_id = get_option("io_inventory_page_id");
if($io_inventory_page_id>0) {
    $inv_content = get_the_content(null,FALSE,$io_inventory_page_id);
    $inv_array = explode('[sc :io_all_cat ',$inv_content);
    $i=0;
    foreach ($inv_array as $cat) {
        $name_start = strpos($cat, 'rental_name="');
        $name = '';
        $key = FALSE;
        if($name_start!==FALSE) {
            $name_start += 13;
            $name_end = strpos($cat, '"', $name_start);
            $name = str_replace("''",'"',substr($cat, $name_start, $name_end - $name_start));
            $key = array_search(trim($name), $titles);
        }
        if($key!==FALSE){
            $posts[$key]['order']=$i;
        }
        $i++;
    }
}
$posts_ordered = array_orderby($posts, 'order', SORT_ASC, 'title', SORT_ASC);

$post_ids = "";
$post_id_rental_id_rel_array = Array();
$search_points = array();
$filter_size_values = array("io_filter_length_lower", "io_filter_length_upper",
    "io_filter_width_lower","io_filter_width_upper",
    "io_filter_height_lower", "io_filter_height_upper",
    "io_filter_area_lower", "io_filter_area_upper");
$filter_size_search_criteria = array();
$filter_area = FALSE;
foreach($_REQUEST as $data_name => $data_pair) {
    if(in_array($data_name, $filter_size_values)){
        switch(explode("_", $data_name)[2]){
            case "length":
                if(strpos($data_name, "lower")) {
                    $filter_size_search_criteria["length"]["lower"] = $data_pair;
                    break;
                }
                if(strpos($data_name, "upper")){
                    $filter_size_search_criteria["length"]["upper"] = $data_pair;
                    break;
                }
                break;
            case "width":
                if(strpos($data_name, "lower")) {
                    $filter_size_search_criteria["width"]["lower"] = $data_pair;
                    break;
                }
                if(strpos($data_name, "upper")){
                    $filter_size_search_criteria["width"]["upper"] = $data_pair;
                    break;
                }
                break;
            case "height":
                if(strpos($data_name, "lower")) {
                    $filter_size_search_criteria["height"]["lower"] = $data_pair;
                    break;
                }
                if(strpos($data_name, "upper")){
                    $filter_size_search_criteria["height"]["upper"] = $data_pair;
                    break;
                }
                break;
            case "area":
                $filter_area = TRUE;
                if(strpos($data_name, "lower")) {
                    $filter_size_search_criteria["area"]["lower"] = $data_pair;
                    break;
                }
                if(strpos($data_name, "upper")){
                    $filter_size_search_criteria["area"]["upper"] = $data_pair;
                    break;
                }
                break;
        }
    }
    if (strpos($data_pair, 'customfield-') === FALSE) continue;
    $data_name = explode("_", $data_pair)[0];
    $data_value = explode("_", $data_pair)[1];
    $data_value = urldecode($data_value);
    $data_value = preg_quote($data_value, "/");
    $search_point = strtolower(str_replace(" ", "_", $data_name)) . '="' . $data_value . '"';
    $search_point = "/".$data_name.'="([^"]*'.$data_value.'[^"]*)"/';
    $search_points[$data_name][] = $search_point;
}

if(!empty($filter_size_search_criteria)){
    $regex_parser = new RegexRangeNumberGenerator();
    $length_regex = "";
    $size_search_point = '/dimensions="';
    if(isset($filter_size_search_criteria['length'])){
        $lower = $filter_size_search_criteria['length']['lower'];
        $upper = $filter_size_search_criteria['length']['upper'];
        if($lower != $upper){
            $length_regex = $regex_parser->parse((int)$lower, (int)$upper);
        }else{
            $length_regex = "(".$lower.")";
        }
        $size_search_point .= $length_regex;
    }
    $width_regex = "";
    if(isset($filter_size_search_criteria['width'])){
        $lower = $filter_size_search_criteria['width']['lower'];
        $upper = $filter_size_search_criteria['width']['upper'];
        if($lower != $upper){
            $width_regex = $regex_parser->parse((int)$lower, (int)$upper);
        }else{
            $width_regex = "(".$lower.")";
        }
        $size_search_point .= "(?:\s*[xX]\s*)".$width_regex;
    }
    $height_regex = "";
    if(isset($filter_size_search_criteria['height'])){
        $lower = $filter_size_search_criteria['height']['lower'];
        $upper = $filter_size_search_criteria['height']['upper'];
        if($lower != $upper){
            $height_regex = $regex_parser->parse((int)$lower, (int)$upper);
        }else{
            $height_regex = "(".$lower.")";
        }
        $size_search_point .= "(?:\s*[xX]\s*)".$height_regex;
    }
    if($filter_area){
        $size_search_point .= "(\d*)(?:\s*[xX]\s*)(\d*)";
    }
    $search_points["dimensions"][] = $size_search_point.'/';
}
foreach($posts_ordered as $post){
    $content = $post['content'];
    $view_product_text = "View Product";

    $content_arr = Array();
    preg_match_all("/\[[^\]]*\]/", $content, $content_arr);
    $content_arr = $content_arr[0];
    if($_REQUEST['io_filter_search_type'] == "exclusive" || !isset($_REQUEST['io_filter_search_type'])) {
        $all_match = TRUE;
        foreach ($content_arr as $item_key => $item_html) {
            $item_html = str_replace("''", '"', $item_html);
            $rental_id = extract_rental_id($item_html);
            if (is_numeric($rental_id)) $post_id_rental_id_rel_array[$post['id']] = $rental_id;
            if (substr($item_html, 0, 4) == "[sc ") $item_html = substr($item_html, 4, -1);
            if (substr($item_html, 0, 11) == ":io_rental ") {
                foreach ($search_points as $search_group => $search_group_points) {
                    $group_match = TRUE;
                    foreach($search_group_points as $search_point) {
                        if (strpos($search_point, "dimensions") !== false) {
                            if ($filter_area) {
                                $length_width_found = array();
                                $area_search_res = preg_match($search_point, $item_html, $length_width_found);
                                if (!$area_search_res) {
                                    $group_match = FALSE;
                                    break;
                                } else {
                                    $found_area = $length_width_found[1] * $length_width_found[2];
                                    if (!($found_area >= $filter_size_search_criteria['area']['lower'] && $found_area <= $filter_size_search_criteria['area']['upper'])) {
                                        $group_match = FALSE;
                                        break;
                                    }
                                }
                            } else {
                                if (!preg_match($search_point, $item_html)) {
                                    $group_match = FALSE;
                                    break;
                                }
                            }
                        } else if (!preg_match($search_point, $item_html) && !preg_match(substr_replace($search_point, "-accessories", strpos($search_point, "="), 0), $item_html)) {
                            $group_match = FALSE;
                            break;
                        }
                    }
                    if(!$group_match){
                        $all_match = FALSE;
                        break;
                    }
                }

                if ($all_match) {
                    if (!$_REQUEST['category'] || $_REQUEST['category'] == "undefined" || $_REQUEST['category'] == "Items") {
                        $post_ids .= $post['id'] . ',';
                    }
                    else if ($_REQUEST['category'])
                    {
                        if (preg_match('/all_categories="([^"]*)"/', $item_html, $matches))
                        {
                            $allCats = explode(',', $matches[1]);
                            if (in_array($_REQUEST['category'], $allCats))
                            {
                                $post_ids .= $post['id'] . ',';
                            }
                        }
                    }
                }
            }
        }
    }else{
        $found = TRUE;
        foreach ($content_arr as $item_key => $item_html) {
            $item_html = str_replace("''", '"', $item_html);
            $rental_id = extract_rental_id($item_html);
            if (is_numeric($rental_id)) $post_id_rental_id_rel_array[$post['id']] = $rental_id;
            if (substr($item_html, 0, 4) == "[sc ") $item_html = substr($item_html, 4, -1);
            if (substr($item_html, 0, 11) == ":io_rental ") {
                foreach ($search_points as $search_group => $search_group_points) {
                    $group_match = FALSE;
                    foreach($search_group_points as $search_point) {
                        if (strpos($search_point, "dimensions") !== false) {
                            if ($filter_area) {
                                $length_width_found = array();
                                $area_search_res = preg_match($search_point, $item_html, $length_width_found);
                                if ($area_search_res) {
                                    $found_area = $length_width_found[1] * $length_width_found[2];
                                    if (($found_area >= $filter_size_search_criteria['area']['lower'] && $found_area <= $filter_size_search_criteria['area']['upper'])) {
                                        $group_match = TRUE;
                                        break;
                                    }
                                }
                            } else {
                                if (preg_match($search_point, $item_html)) {
                                    $group_match = TRUE;
                                    break;
                                }
                            }
                        } else if (preg_match($search_point, $item_html) || preg_match(substr_replace($search_point, "-accessories", strpos($search_point, "="), 0), $item_html)) {
                            $group_match = TRUE;
                            break;
                        }
                    }
                    if(!$group_match){
                        $found = FALSE;
                        break;
                    }
                }

                if ($found) {
                    if (!$_REQUEST['category'] || $_REQUEST['category'] == "undefined" || $_REQUEST['category'] == "Items") {
                        $post_ids .= $post['id'] . ',';
                    }
                    else if ($_REQUEST['category'])
                    {
                        if (preg_match('/all_categories="([^"]*)"/', $item_html, $matches))
                        {
                            $allCats = explode(',', $matches[1]);
                            if (in_array($_REQUEST['category'], $allCats))
                            {
                                $post_ids .= $post['id'] . ',';
                            }
                        }
                    }
                }
            }
        }
    }
}

// Need to pass in rental ids of all items on page already, then if the above code results in empty set of ids (no other filters)
// need to assign rental ids to all rental ids passed in if the availability and price filters are being used.
if($_REQUEST['io_filter_availability'] || ($_REQUEST['io_filter_price_min'] && $_REQUEST['io_filter_price_max'])){
    /*
        Not included for now:
             &street=
             &city=
             &state=
             &zip=
    */
    $rental_ids_str = "";
    if(empty($post_ids) && !empty($_REQUEST["page_rental_ids"])){
        $rental_ids_str = $_REQUEST["page_rental_ids"];
    }else if(!empty($post_ids)){
        foreach(explode(",", $post_ids) as $post_id){
            $rental_ids_str .= $post_id_rental_id_rel_array[$post_id].",";
        }
    }

    if(!empty($rental_ids_str)){
        // Make sure if we are just looking for price and date and time are not set any time
        if( (!$_REQUEST['io_filter_availability'] && ($_REQUEST['io_filter_price_min'] && $_REQUEST['io_filter_price_max']) ) && (!$_REQUEST["start_date"] || $_REQUEST["start_time"])){
            $_REQUEST["start_date"] = date('m/d/Y', time());
            $_REQUEST["start_time"] = date('h:i a', time());
        }
        //$url = "http://localhost/io/bugs/quotes/check_availability_v2.php?&name=".urlencode($_REQUEST["name"])."&startdate=".urlencode($_REQUEST["start_date"])."&starttime=".urlencode($_REQUEST["start_time"])."&duration=".$_REQUEST["duration"]."&single_cart=0&usecushion=1&include_price=1&showlocations=0&rental_ids=".str_replace(",", "|",$rental_ids_str)."&cart_rental_names=&cart_rental_ids=&return_id=1&delivery_method=&temp=1";
        $url = "https://rental.software/quotes/check_availability_v2.php?&name=".urlencode($_REQUEST["name"])."&startdate=".urlencode($_REQUEST["start_date"])."&starttime=".urlencode($_REQUEST["start_time"])."&duration=".$_REQUEST["duration"]."&single_cart=0&usecushion=1&include_price=1&showlocations=0&rental_ids=".str_replace(",", "|",$rental_ids_str)."&cart_rental_names=&cart_rental_ids=&return_id=1&delivery_method=&temp=1";
        $check_avail_result = file_get_contents($url);
    }

    if($check_avail_result){
        $check_avail_result_obj = json_decode($check_avail_result);
        $temp_post_ids_str = "";
        foreach(explode(",", $rental_ids_str) as $rid){
            $item_avail = $check_avail_result_obj->$rid;
            $item_price = floatval($check_avail_result_obj->price->$rid);
            $post_id = array_search($rid, $post_id_rental_id_rel_array);
            if($_REQUEST['io_filter_availability'] && ($_REQUEST['io_filter_price_min'] && $_REQUEST['io_filter_price_max'])){
                // We are checking both availability and price of items.
                if($item_avail > 0 && ( ($_REQUEST['io_filter_price_min'] <= $item_price) && ($item_price <= $_REQUEST['io_filter_price_max']) )){
                    $temp_post_ids_str .= $post_id.",";
                }

            }else if($_REQUEST['io_filter_availability'] && (!$_REQUEST['io_filter_price_min'] || !$_REQUEST['io_filter_price_max'])){
                // We are checking availability of items only.
                if($item_avail > 0){
                    $temp_post_ids_str .= $post_id.",";
                }

            }else if(!$_REQUEST['io_filter_availability'] && ($_REQUEST['io_filter_price_min'] && $_REQUEST['io_filter_price_max'])){
                // We are checking price of items only.
                if(($_REQUEST['io_filter_price_min'] <= $item_price) && ($item_price <= $_REQUEST['io_filter_price_max'])){
                    $temp_post_ids_str .= $post_id.",";
                }
            }
        }
        $post_ids = $temp_post_ids_str;
    }

}

echo do_shortcode('[widget widget_name="IO_Featured" item_ids="'.$post_ids.'" show_price="'.$_REQUEST['show_price'].'" view_product_hover="'.$_REQUEST['view_product_hover'].'" add_to_cart="'.$_REQUEST['add_to_cart'].'" width="'.$_REQUEST['width'].'" io_id="'.rand(1000, 100000).'"]');

function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
        }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}

function extract_rental_id($item_html){
    $loc = strpos($item_html,"rental_id=")+strlen("rental_id=");
    if($loc && $loc<strlen($item_html)){
        $loc_end = strpos($item_html,'"',$loc+1);
        $rental_id = substr($item_html, $loc+1, $loc_end-$loc-1);
    }
    if(is_numeric($rental_id)) return $rental_id;
}

// Class found at https://stackoverflow.com/a/57446672
// php version of https://github.com/erwinyusrizal/RegexNumericRangeGenerator
// We use the parse function of this class to generate a regex number range for the purposes of filtering by size.
class RegexRangeNumberGenerator {

    static function parse($min, $max, $MatchWholeWord = FALSE, $MatchWholeLine = FALSE, $MatchLeadingZero = FALSE) {
        if (!is_int($min) || !is_int($max) || $min > $max || $min < 0 || $max < 0) {
            return FALSE;
        }
        if ($min == $max) {
            return self::parseIntoPattern($min, $MatchWholeWord, $MatchWholeLine, $MatchLeadingZero);
        }
        $s = [];
        $x = self::parseStartRange($min, $max);
        foreach ($x as $o) {
            $s[] = self::parseEndRange($o[0], $o[1]);
        }
        $n = self::reformatArray($s);
        $h = self::parseIntoRegex($n);
        return self::parseIntoPattern($h, $MatchWholeWord, $MatchWholeLine, $MatchLeadingZero);
    }

    static private function parseIntoPattern($t, $MatchWholeWord = FALSE, $MatchWholeLine = FALSE, $MatchLeadingZero = FALSE) {
        $r = ((is_array($t)) ? implode("|", $t) : $t);
        return (($MatchWholeLine && $MatchLeadingZero) ? "^0*(" . $r . ")$" : (($MatchLeadingZero) ? "0*(" . $r . ")" : (($MatchWholeLine) ? "^(" . $r . ")$" : (($MatchWholeWord) ? "\\b(" . $r . ")\\b" : "(" . $r . ")"))));
    }

    static private function parseIntoRegex($t) {
        if (!is_array($t)) {
            throw new Exception("Argument needs to be an array!");
        }
        $r = [];
        for ($i = 0; $i < count($t); $i++) {
            $e = str_split($t[$i][0]);
            $n = str_split($t[$i][1]);
            $s = "";
            $o = 0;
            $h = "";
            for ($a = 0; $a < count($e); $a++) {
                if ($e[$a] === $n[$a]) {
                    $h .= $e[$a];
                } else {
                    if ((intval($e[$a]) + 1) === intval($n[$a])) {
                        $h .= "[" . $e[$a] . $n[$a] . "]";
                    } else {
                        if ($s === ($e[$a] . $n[$a])) {
                            $o++;
                        }
                        $s = $e[$a] . $n[$a];
                        if ($a == (count($e) - 1)) {
                            $h .= (($o > 0) ? "{" . ($o + 1) . "}" : "[" . $e[$a] . "-" . $n[$a] . "]");
                        } else {
                            if ($o === 0) {
                                $h .= "[" . $e[$a] . "-" . $n[$a] . "]";
                            }
                        }
                    }
                }
            }
            $r[] = $h;
        }
        return $r;
    }

    static private function reformatArray($t) {
        $arrReturn = [];
        for ($i = 0; $i < count($t); $i++) {
            $page = count($t[$i]) / 2;
            for ($a = 0; $a < $page; $a++) {
                $arrReturn[] = array_slice($t[$i], (2 * $a), 2);
            }
        }
        return $arrReturn;
    }

    static private function parseStartRange($t, $r) {
        if (strlen($t) === strlen($r)) {
            return [[$t, $r]];
        }
        $break = pow(10, strlen($t)) - 1;
        return array_merge([[$t, $break]], self::parseStartRange($break + 1, $r));
    }

    static private function parseEndRange($t, $r) {
        if (strlen($t) == 1) {
            return [$t, $r];
        }
        if (str_repeat("0", strlen($t)) === "0" . substr($t, 1)) {
            if (str_repeat("0", strlen($r)) == "9" . substr($r, 1)) {
                return [$t, $r];
            }
            if ((int) substr($t, 0, 1) < (int) substr($r, 0, 1)) {
                $e = intval(substr($r, 0, 1) . str_repeat("0", strlen($r) - 1)) - 1;
                return array_merge([$t, self::strBreakPoint($e)], self::parseEndRange(self::strBreakPoint($e + 1), $r));
            }
        }
        if (str_repeat("9", strlen($r)) === "9" . substr($r, 1) && (int) substr($t, 0, 1) < (int) substr($r, 0, 1)) {
            $e = intval(intval((int) substr($t, 0, 1) + 1) . "" . str_repeat("0", strlen($r) - 1)) - 1;
            return array_merge(self::parseEndRange($t, self::strBreakPoint($e)), [self::strBreakPoint($e + 1), $r]);
        }
        if ((int) substr($t, 0, 1) < (int) substr($r, 0, 1)) {
            $e = intval(intval((int) substr($t, 0, 1) + 1) . "" . str_repeat("0", strlen($r) - 1)) - 1;
            return array_merge(self::parseEndRange($t, self::strBreakPoint($e)), self::parseEndRange(self::strBreakPoint($e + 1), $r));
        }
        $a = (int) substr($t, 0, 1);
        $o = self::parseEndRange(substr($t, 1), substr($r, 1));
        $h = [];
        for ($u = 0; $u < count($o); $u++) {
            $h[] = ($a . $o[$u]);
        }
        return $h;
    }

    static private function strBreakPoint($t) {
        return str_pad($t, strlen(($t + 1)), "0", STR_PAD_LEFT);
    }
}

?>