<?php
/*****************
 *
 *  Data access
 *
 ******************/

/*****************
 *
 *  Property access
 *
 ******************/

/*
 * Get all properties for search page
 */
function rentpress_getAllProperties()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $properties = $wpdb->get_results("SELECT * FROM " . esc_sql($table_name));

    return $properties;
}

/*
 * Get nearby properties for single property page
 */
function rentpress_getNearbyProperties($city, $limit = null, $excluded_property_code = null)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $limit = !empty($limit) ? "LIMIT $limit" : "";
    $excludeString = "";
    if (!empty($excluded_property_code)) {
        $excludeString = "AND NOT `property_code` = '$excluded_property_code'";
    }

    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE `property_city` = '$city' $excludeString ORDER BY `property_available_units` DESC $limit");

    return $properties;
}

/*
 * Get neighborhood properties for single property page
 */
function rentpress_getNeighborhoodProperties($neighborhood, $limit = null, $excluded_property_code = null)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $limit = !empty($limit) ? "LIMIT $limit" : "";
    $excludeString = "";
    if (!empty($excluded_property_code)) {
        $excludeString = "AND NOT `property_code` = '$excluded_property_code'";
    }

    $sql_neighborhood_str = "FIND_IN_SET('$neighborhood',`property_neighborhood_post_names`)
                             OR `property_neighborhood_post_name` LIKE '%$neighborhood%'
                             OR FIND_IN_SET('$neighborhood',`property_neighborhood_post_ids`)
                            ";

    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE $sql_neighborhood_str $excludeString ORDER BY `property_available_units` DESC $limit");

    return $properties;
}

/*
 * Get properties for many neighborhoods
 */
function rentpress_getNeighborhoodsProperties($neighborhoods, $limit = null, $excluded_property_code = null)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $limit = !empty($limit) ? "LIMIT $limit" : "";
    $excludeString = "";
    if (!empty($excluded_property_code)) {
        $excludeString = "AND NOT `property_code` = '$excluded_property_code'";
    }

    $sql_neighborhood_str = "";
    foreach ($neighborhoods as $key => $neighborhood) {
        $neighborhood = trim($neighborhood);
        if (str_contains($neighborhood, "'")) {
            $neighborhood = str_replace("'", "\'", $neighborhood);
        }
        $sql_neighborhood_str .= "`property_neighborhood_post_names` LIKE '%$neighborhood%'
        OR FIND_IN_SET('$neighborhood',`property_neighborhood_post_ids`)";
        if (count($neighborhoods)!=($key+1)) {
            $sql_neighborhood_str .= " OR ";
        }
    }

    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE $sql_neighborhood_str $excludeString ORDER BY `property_available_units` DESC $limit");

    return $properties;
}

function rentpress_getNeighborhoodData() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';
    $meta_table_name = $wpdb->prefix . 'postmeta';
    $IDsAndCodes = [];

    $neighborhood_posts = get_posts([
        'post_type' => 'rentpress_hood',
        'post_status' => 'publish',
        'numberposts' => -1,
    ]);
    $propertyCodesForNeighborhoods = $wpdb->get_results("SELECT post_id, meta_value FROM $meta_table_name WHERE `meta_key` = 'rentpress_custom_field_neighborhood_property_codes'");

    foreach ($propertyCodesForNeighborhoods as $neighborhood) {
        $IDsAndCodes[$neighborhood->post_id] = $neighborhood->meta_value;
    }

    foreach ($neighborhood_posts as $key => $neighborhood) {
        $codes = isset($IDsAndCodes[$neighborhood->ID]) ? $IDsAndCodes[$neighborhood->ID] : "";
        if ($codes) {
            $neighborhood_posts[$key]->neighborhood_properties = explode(',', $codes);
        }
    }

    return $neighborhood_posts;
}

/*
 * Get all properties for taxonomy page
 */
function rentpress_getAllPropertiesForTaxonomies($terms)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';
    $sql_term_str = "WHERE `property_terms` ";
    $terms_count = count($terms);

    if ($terms_count > 1) {
        for ($i = 0; $i < $terms_count; $i++) {
            $term = $terms[$i];
            $sql_term_str .= "REGEXP '\"$term\"'";
            if ($i != $terms_count - 1) {
                $sql_term_str .= " AND `property_terms` ";
            }
        }
    } else {
        $term = $terms[0];
        $sql_term_str .= "REGEXP '\"$term\"'";
    }

    $properties = $wpdb->get_results("SELECT * FROM $table_name $sql_term_str");

    return $properties;
}

/*
 * Get city properties with taxonomy
 */
function rentpress_getCityPropertiesWithTaxonomies($city, $terms, $limit = null, $excluded_property_code = null)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $limit = !empty($limit) ? "LIMIT $limit" : "";
    $excludeString = "";
    if (!empty($excluded_property_code)) {
        $excludeString = "AND NOT `property_code` = '$excluded_property_code'";
    }

    $sql_term_str = "AND `property_terms` ";
    $terms_count = $terms ? count($terms) : 0;

    if ($terms_count > 1) {
        for ($i = 0; $i < $terms_count; $i++) {
            $term = $terms[$i];
            $sql_term_str .= "REGEXP '\"$term\"'";
            if ($i != $terms_count - 1) {
                $sql_term_str .= " AND `property_terms` ";
            }
        }
    } elseif ($terms_count == 1) {
        $term = $terms[0];
        $sql_term_str .= "REGEXP '\"$term\"'";
    } else {
        $sql_term_str = '';
    }

    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE `property_city` = '$city' $sql_term_str $excludeString ORDER BY `property_available_units` DESC $limit");

    return $properties;
}

/*
 * Get neighborhood properties with taxonomy
 */
function rentpress_getNeighborhoodPropertiesWithTaxonomies($neighborhood, $terms, $limit = null, $excluded_property_code = null)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $limit = !empty($limit) ? "LIMIT $limit" : "";
    $excludeString = "";
    if (!empty($excluded_property_code)) {
        $excludeString = "AND NOT `property_code` = '$excluded_property_code'";
    }

    $sql_term_str = "`property_terms` ";
    $terms_count = count($terms);

    if ($terms_count > 1) {
        for ($i = 0; $i < $terms_count; $i++) {
            $term = $terms[$i];
            $sql_term_str .= "REGEXP '\"$term\"'";
            if ($i != $terms_count - 1) {
                $sql_term_str .= " AND `property_terms` ";
            }
        }
    } else {
        $term = $terms[0];
        $sql_term_str .= "REGEXP '\"$term\"'";
    }

    $sql_neighborhood_str = "(`property_neighborhood_post_name` = '$neighborhood' OR `property_primary_neighborhood_post_id` = '$neighborhood')";

    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE $sql_neighborhood_str AND $sql_term_str $excludeString ORDER BY `property_available_units` DESC $limit");

    return $properties;
}

/*
 * Get all properties for a featured page by property code or post id
 */
function rentpress_getAllPropertiesWithCodesOrIDs($properties_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $sql_code_str = "WHERE ";

    $codes_count = count($properties_info);

    if ($codes_count > 1) {
        for ($i = 0; $i < $codes_count; $i++) {
            $code = $properties_info[$i];
            $sql_code_str .= "(`property_code` = '$code' OR `property_post_id` = '$code')";
            if ($i != $codes_count - 1) {
                $sql_code_str .= " OR ";
            }
        }
    } else {
        $code = $properties_info[0];
        $sql_code_str .= "(`property_code` = '$code' OR `property_post_id` = '$code')";
    }

    $properties = $wpdb->get_results("SELECT * FROM $table_name $sql_code_str");

    return $properties;
}

/*
 * Get property by property code or post id
 */
function rentpress_getAllPropertyWithCodeOrID($property_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';
    $properties = $wpdb->get_results("SELECT * FROM $table_name WHERE (`property_code` = '$property_info' OR `property_post_id` = '$property_info')");

    return $properties;
}

/*
 * Get all properties and the related data based on property post id or propert code
 */
function rentpress_getAllPropertyDataWithCodeOrPostID($property_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_properties';

    $property = $wpdb->get_row("SELECT * FROM $table_name WHERE (`property_code` = '$property_info' OR `property_post_id` = '$property_info')");

    if (!empty($property)) {
        $property->floorplans = rentpress_getAllFloorplansByParentPropertyCode($property->property_code);
        $units = rentpress_getAllAvailableUnitsByParentPropertyCode($property->property_code);

        if (!empty($property->floorplans)) {
            foreach ($property->floorplans as $fp) {
                $fp->units = array();
                if (!empty($units)) {
                    foreach ($units as $unit_key => $unit) {
                        if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                            array_push($fp->units, $unit);
                            unset($units[$unit_key]);
                        }
                    }
                }
            }
        }
    }

    return $property;

    // TODO: @Charles figure out how to do the complicated join in order to cut the calls
    // $data_set = $wpdb->get_results(
    //     "SELECT *
    //     FROM $property_table p
    //     INNER JOIN $floorplan_table f
    //         ON p.property_code = f.floorplan_parent_property_code
    //     INNER JOIN $unit_table u
    //         ON f.floorplan_parent_property_code = u.unit_parent_property_code
    //     WHERE (`property_code` = '$property_info' OR `property_post_id` = '$property_info')" );

}

/*****************
 *
 *  Floorplan access
 *
 ******************/

/*
 * Get all floorplans for search page
 */
function rentpress_getAllFloorplansAndUnits()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name");
    $units = rentpress_getAllAvailableUnits();

    foreach ($floorplans as $fp) {
        $fp->units = array();
        foreach ($units as $unit_key => $unit) {
            if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                array_push($fp->units, $unit);
                unset($units[$unit_key]);
            }
        }
    }

    return $floorplans;
}

/*
 * Get all floorplans for a property
 */
function rentpress_getAllFloorplansByParentPropertyCode($property_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name WHERE `floorplan_parent_property_code` = '$property_code'");

    return $floorplans;
}

/*
 * Get floorplan data row from code or post id
 */
function rentpress_getFloorplanDataWithCodeOrPostID($floorplan_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    return $wpdb->get_row("SELECT * FROM $table_name WHERE (`floorplan_code` = '$floorplan_info' OR `floorplan_post_id` = '$floorplan_info')");
}

/*
 * Get floorplans and units from floorplan codes or post ids
 */
function rentpress_getFloorplansAndUnitsWithCodesOrPostIDs($floorplans_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    $fp_codes_sql = '';
    foreach ($floorplans_info as $fp) {
        $fp_codes_sql .= "(`floorplan_code` = '$fp' OR `floorplan_post_id` = '$fp') OR ";
    }
    $fp_codes_sql = substr($fp_codes_sql, 0, -3);

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name WHERE $fp_codes_sql");
    $units = rentpress_getAllAvailableUnits();

    foreach ($floorplans as $fp) {
        $fp->units = array();
        foreach ($units as $unit_key => $unit) {
            if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                array_push($fp->units, $unit);
                unset($units[$unit_key]);
            }
        }
    }

    return $floorplans;
}

/*
 * Get floorplans and units from parent property codes or post ids
 */
function rentpress_getFloorplansAndUnitsWithParentPropertyCodesOrPostIDs($floorplans_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    $fp_codes_sql = '';
    foreach ($floorplans_info as $fp) {
        $fp_codes_sql .= "(`floorplan_parent_property_code` = '$fp' OR `floorplan_parent_property_post_id` = '$fp') OR ";
    }
    $fp_codes_sql = substr($fp_codes_sql, 0, -3);

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name WHERE $fp_codes_sql");
    $units = rentpress_getAllAvailableUnits();

    foreach ($floorplans as $fp) {
        $fp->units = array();
        foreach ($units as $unit_key => $unit) {
            if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                array_push($fp->units, $unit);
                unset($units[$unit_key]);
            }
        }
    }

    return $floorplans;
}

/*
 * Get floorplans, units and parent property data from parent property codes or post ids
 */
function rentpress_getAllFloorplansDataWithParentPropertyCodesOrPostIDs($floorplans_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';
    $prop_table = $wpdb->prefix . 'rentpress_properties';

    $fp_codes_sql = '';
    foreach ($floorplans_info as $fp) {
        $fp_codes_sql .= "(`floorplan_parent_property_code` = '$fp' OR `floorplan_parent_property_post_id` = '$fp') OR ";
    }
    $fp_codes_sql = substr($fp_codes_sql, 0, -3);

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name AS fp INNER JOIN $prop_table as prop ON fp.floorplan_parent_property_code = prop.property_code WHERE $fp_codes_sql");
    $units = rentpress_getAllAvailableUnits();

    foreach ($floorplans as $fp) {
        $fp->units = array();
        foreach ($units as $unit_key => $unit) {
            if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                array_push($fp->units, $unit);
                unset($units[$unit_key]);
            }
        }
    }

    return $floorplans;
}

/*
 * Get floorplans, units and parent property data from parent property codes or post ids
 * and with floor plan unit type mapping
 */
function rentpress_getAllFloorplansDataWithParentPropertyCodesOrPostIDsWithTypeMap($floorplans_info, $unitMap)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';
    $prop_table = $wpdb->prefix . 'rentpress_properties';

    $fp_codes_sql = '';
    foreach ($floorplans_info as $fp) {
        $fp_codes_sql .= "(`floorplan_parent_property_code` = '$fp' OR `floorplan_parent_property_post_id` = '$fp') OR ";
    }
    $fp_codes_sql = substr($fp_codes_sql, 0, -3);

    $sql_map_str = $unitMap ? "AND `floorplan_unit_type_mapping` " : '';
    $unit_type_maps = count($unitMap);

    if ($unit_type_maps > 1) {
        for ($i = 0; $i < $unit_type_maps; $i++) {
            $map = $unitMap[$i];
            $sql_map_str .= "REGEXP '$map'";
            if ($i != $unit_type_maps - 1) {
                $sql_map_str .= " OR `floorplan_unit_type_mapping` ";
            }
        }
    } elseif ($unit_type_maps == 1) {
        $map = $unitMap[0];
        $sql_map_str .= "REGEXP '$map'";
    }

    $floorplans = $wpdb->get_results("SELECT * FROM $table_name AS fp INNER JOIN $prop_table as prop ON fp.floorplan_parent_property_code = prop.property_code WHERE $fp_codes_sql $sql_map_str");
    $units = rentpress_getAllAvailableUnits();

    foreach ($floorplans as $fp) {
        $fp->units = array();
        foreach ($units as $unit_key => $unit) {
            if ($unit->unit_parent_floorplan_code == $fp->floorplan_code) {
                array_push($fp->units, $unit);
                unset($units[$unit_key]);
            }
        }
    }

    return $floorplans;
}

/*
 * Get floorplan, parent property, and available unit data from floorplan code or post id
 */
function rentpress_getAllFloorplanDataWithCodeOrPostID($floorplan_info)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';
    $prop_table = $wpdb->prefix . 'rentpress_properties';

    $floorplan = $wpdb->get_row("SELECT * FROM $table_name AS fp INNER JOIN $prop_table as prop ON fp.floorplan_parent_property_code = prop.property_code WHERE (fp.floorplan_code = '$floorplan_info' OR fp.floorplan_post_id = '$floorplan_info')");

    if (!empty($floorplan)) {
        $floorplan->units = rentpress_getAllAvailableUnitsByFloorplanByCode($floorplan->floorplan_code);
    }

    return $floorplan;
}

/*
 * Get similar floorplans from floorplan object or post_id/floorplan_code
 */
function rentpress_getSimilarFloorplans($floorplan, $comparing = 'relevance', $number_of_floorplans = 3, $same_property = true) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_floorplans';

    // Ensure we have a floorplan object
    if (empty($floorplan->floorplan_code)) {
        $floorplan = rentpress_getFloorplanDataWithCodeOrPostID($floorplan);
        if (empty($floorplan->floorplan_code)) {
            return new WP_Error('invalid_floorplan', 'No floorplans match this floorplan_code or post_id');
        }
    }

    $same_floorplan_filter = $wpdb->prepare("`floorplan_code` != %s", $floorplan->floorplan_code);
    $same_property_filter = '';
    if ($same_property) {
        $same_property_filter = $wpdb->prepare("AND `floorplan_parent_property_code` = %s", $floorplan->floorplan_parent_property_code);
    }

    // Build absolute difference expressions
    $cost_order    = !empty($floorplan->floorplan_rent_type_selection_cost) ? "ABS(`floorplan_rent_type_selection_cost` - " . floatval($floorplan->floorplan_rent_type_selection_cost) . ") ASC" : '';
    $bedroom_order = !empty($floorplan->floorplan_bedrooms) ? "ABS(`floorplan_bedrooms` - " . intval($floorplan->floorplan_bedrooms) . ") ASC" : '';
    $sqft_order    = !empty($floorplan->floorplan_sqft_min) ? "ABS(`floorplan_sqft_min` - " . intval($floorplan->floorplan_sqft_min) . ") ASC" : '';

    // Helper for specials ordering: treat empty/null as high value to push them last
    $special_order = "CASE WHEN `floorplan_specials_message` IS NULL OR `floorplan_specials_message` = '' THEN 1 ELSE 0 END ASC";

    // Build ORDER BY clause based on comparing
    switch ($comparing) {
        case 'price':
            $order_by = $cost_order ?: '`floorplan_post_title` ASC';
            break;
        case 'bedrooms':
            $order_by = $bedroom_order ?: '`floorplan_units_available` DESC';
            break;
        case 'sqft':
            $order_by = $sqft_order ?: '`floorplan_units_available` DESC';
            break;
        case 'special':
            $order_parts = [$special_order];
            if ($bedroom_order) $order_parts[] = $bedroom_order;
            if ($cost_order) $order_parts[] = $cost_order;
            $order_by = implode(', ', $order_parts);
            break;
        case 'availability':
            $order_by = '`floorplan_units_available` DESC';
            break;
        case 'relevance':
        default:
            $order_parts = [];
            if ($bedroom_order) $order_parts[] = $bedroom_order;
            $order_parts[] = $special_order;
            $order_parts[] = '`floorplan_units_available` DESC';
            if ($cost_order) $order_parts[] = $cost_order;
            $order_by = implode(', ', $order_parts);
            break;
    }

    // Prepare and execute query
    $sql = "SELECT *
            FROM $table_name
            WHERE $same_floorplan_filter
            $same_property_filter
            ORDER BY $order_by
            LIMIT %d";

    // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- identifiers and expressions are safely escaped
    $similar_floorplans = $wpdb->get_results($wpdb->prepare($sql, $number_of_floorplans));

    return $similar_floorplans ?: [];
}

/*****************
 *
 *  Unit access
 *
 ******************/

/*
 * Get all units for search page
 */
function rentpress_getAllUnits()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name");

    return $units;
}

/*
 * Get all manual units for resync
 */
function rentpress_getAllManualUnits()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_is_feed` = '0' ORDER BY `unit_ready_date` DESC");

    return $units;
}

function rentpress_getAllManualUnitsForFloorplans($codes)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $floorplanCodes = "";
    $length = count($codes);
    foreach ($codes as $key => $code) {
        $floorplanCodes .= "`unit_parent_floorplan_code` = '$code'";
        if ($key != $length - 1) {
            $floorplanCodes .= " AND ";
        }
    }

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_is_feed` = '0' AND $floorplanCodes ORDER BY `unit_ready_date` DESC");

    return $units;
}

/*
 * Get all units codes
 */
function rentpress_getAllUnitCodes()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $unit_codes_array = array();
    $unit_codes = $wpdb->get_results("SELECT `unit_code` FROM $table_name");
    foreach ($unit_codes as $unit_code) {
        $unit_codes_array[] = $unit_code->unit_code;

    }

    return $unit_codes_array;
}

/*
 * Get all units for property
 */
function rentpress_getAllUnitsByParentPropertyCode($property_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_parent_property_code` = '$property_code'");

    return $units;
}

/*
 * Get all units for floorplan
 */
function rentpress_getAllUnitsForFloorplan($floorplan_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_parent_floorplan_code` = '$floorplan_code'");

    return $units;
}

/*
 * Get all available units
 */
function rentpress_getAllAvailableUnits()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_available` = 1");

    return $units;
}

/*
 * Get all available units for a property
 */
function rentpress_getAllAvailableUnitsByParentPropertyCode($property_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_parent_property_code` = '$property_code' AND `unit_available` = 1");

    return $units;
}

/*
 * Get all available units for a floorplan
 */
function rentpress_getAllAvailableUnitsByFloorplanByCode($floorplan_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_units';

    $units = $wpdb->get_results("SELECT * FROM $table_name WHERE `unit_parent_floorplan_code` = '$floorplan_code' AND `unit_available` = 1");
    return $units;
}

/*
 * Get all unit and floorplan data by unit code
 */
function rentpress_getUnitAndFloorplanDataByUnitCode($unit_code)
{
    global $wpdb;
    $unit_table = $wpdb->prefix . 'rentpress_units';
    $fp_table = $wpdb->prefix . 'rentpress_floorplans';

    return $wpdb->get_row("SELECT * FROM $unit_table AS u INNER JOIN $fp_table as fp ON u.unit_parent_floorplan_code = fp.floorplan_code WHERE u.unit_code = '$unit_code'");
}

/*****************
 *
 *  Refresh access
 *
 ******************/

/*
 * Get all refresh data
 */
function rentpress_getRefreshData()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';

    $data = $wpdb->get_results("SELECT * FROM $table_name");

    return $data;
}

/*
 * Get all refresh data paginated
 */
function rentpress_getPaginatedRefreshData($offset = 0, $limit = 10)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';

    $data = $wpdb->get_results("SELECT * FROM $table_name ORDER BY `property_code` LIMIT $offset, $limit");

    return $data;
}

/*
 * Get all refresh data
 */
function rentpress_getRefreshPropertyCodes()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';

    $data = $wpdb->get_results("SELECT `property_code` FROM $table_name");

    $property_codes = array();
    foreach ($data as $property_code) {
        array_push($property_codes, $property_code->property_code);
    }

    return $property_codes;
}

/*
 * Get oldest refresh time
 */
function rentpress_getOldestRefreshTS()
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';

    $data = $wpdb->get_results("SELECT MIN(`last_refresh_time`) AS 'oldest_ts' FROM $table_name");

    return $data[0]->oldest_ts;
}

/*
 * Get refresh data for specific property
 */
function rentpress_getRefreshRow($property_code)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';

    $data = $wpdb->get_row("SELECT * FROM $table_name WHERE `property_code` = '$property_code'");

    return $data;
}

/*
 * Get refresh data for property list
 */
function rentpress_getRefreshRowsFromPropertyCodes($property_codes)
{
    global $wpdb;
    $table_name = $wpdb->prefix . 'rentpress_refresh';
    $sql_str = "WHERE ";
    $codes_count = count($property_codes);

    for ($i = 0; $i < $codes_count; $i++) {
        $property_code = $property_codes[$i];
        $sql_str .= "`property_code` = '$property_code'";
        if ($i + 1 < $codes_count) {
            $sql_str .= " OR ";
        }
    }

    $data = $wpdb->get_results("SELECT * FROM $table_name $sql_str");

    return $data;
}

/*****************
 *
 *  Data manipulation
 *
 ******************/

/*
 * Remove a db row for when posts get deleted
 */
function rentpress_deleteRowRowFromTableWithPostID($table_name, $column_name, $postID)
{
    global $wpdb;
    return $wpdb->delete(
        $wpdb->prefix . $table_name,
        [$column_name => $postID]
    );
}