<?php

defined( 'ABSPATH' ) or exit;

function pwlpar_log( $message, $type = 'info' ) {
    $log = new WC_Logger();

    switch ( $type ) {
        case 'debug':
            $log->debug( $message, array( 'source' => 'pw-loyalty-points-and-rewards-for-woocommerce' ) );
        break;

        case 'error':
            $log->error( $message, array( 'source' => 'pw-loyalty-points-and-rewards-for-woocommerce' ) );
        break;

        default:
            $log->info( $message, array( 'source' => 'pw-loyalty-points-and-rewards-for-woocommerce' ) );
        break;
    }
}

function pwlpar_get_template( $template_name, $args = array() ) {
    wc_get_template( $template_name, $args, '', PWLPAR_PLUGIN_DIR . '/templates/' );
}

function pwlpar_get_template_html( $template_name, $args = array() ) {
    ob_start();
    pwlpar_get_template( $template_name, $args );
    return ob_get_clean();
}

// Pass in the database column name (or alias) and the value. If the value is an array,
// it will split it up and find IN. Optionally pass $not to negate the query.
function pwlpar_get_sql_where( $column, $value, $not = false ) {
    global $wpdb;

    if ( is_array( $value ) ) {
        if ( !empty( $value ) ) {
            $placeholders = implode( ', ', array_fill( 0, count( $value ), '%s' ) );

            //
            // $placeholders will be a string of %s, %s, %s... tokens that $wpdb->prepare will escape.
            //
            // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            if ( $not ) {
                return $wpdb->prepare( " AND " . esc_sql( $column ) . " NOT IN ($placeholders)", $value );
            } else {
                return $wpdb->prepare( " AND " . esc_sql( $column ) . " IN ($placeholders)", $value );
            }
            // phpcs:enable
        }

    } else if ( $value != 'any' ) {
        if ( $not ) {
            return $wpdb->prepare( " AND " . esc_sql( $column ) . " != %s", $value );
        } else {
            return $wpdb->prepare( " AND " . esc_sql( $column ) . " = %s", $value );
        }
    }

    return '';
}

function pwlpar_format_string( $string ) {
    if ( empty( $member ) ) {
        $member = pwlpar_get_member( get_current_user_id() );
    }

    $placeholders = array(
        '{program_name}'            => 'pwlpar_program_name',
        '{rewards_home_link}'       => 'pwlpar_get_home_url',
        '{rewards_join_link}'       => 'pwlpar_join_url',
        '{cart_points}'             => function() { return pwlpar_format_points( pwlpar_calculate_earned_cart_points() ); },
    );

    foreach ( $placeholders as $placeholder => $function ) {
        if ( !empty( $string ) && strpos( $string, $placeholder ) ) {
            if ( is_callable( $function ) ) {
                $value = call_user_func( $function );
                $string = str_replace( $placeholder, $value, $string );
            }
        }
    }

    return $string;
}

function pwlpar_format_price( $price ) {
    $original_price = $price;

    $price = (float) $price;
    $result = number_format_i18n( $price, wc_get_price_decimals(), wc_get_price_decimal_separator(), wc_get_price_thousand_separator() );

    return apply_filters( 'pwlpar_format_price', $result, $original_price );
}

function pwlpar_format_points( $points ) {
    $original_points = $points;

    if ( is_numeric( $points ) ) {
        $points = number_format_i18n( $points, 0, '', wc_get_price_thousand_separator() );
    } else {
        $points = $original_points;
    }

    return apply_filters( 'pwlpar_format_points', $points, $original_points );
}

function pwlpar_format_points_with_label( $points ) {
    /* translators: %s: number of points */
    return sprintf( _n( '%s point', '%s points', $points, 'pw-loyalty-points-and-rewards-for-woocommerce' ), pwlpar_format_points( $points ) );
}

function pwlpar_relative_url( $url ) {
    return plugins_url( $url, PWLPAR_PLUGIN_FILE );
}

function pwlpar_get_gmt_from_date( $date, $format = 'Y-m-d H:i:s' ) {
    if ( empty( $date ) || '0000-00-00 00:00:00' == $date ) {
        return null;
    }

    return get_gmt_from_date( $date, $format );
}

function pwlpar_get_date_from_gmt( $date, $format = 'Y-m-d H:i:s' ) {
    if ( empty( $date ) || '0000-00-00 00:00:00' == $date ) {
        return null;
    }

    return get_date_from_gmt( $date, $format );
}

function pwlpar_format_date( $date, $format = '' ) {
    if ( ! $format ) {
        $format = wc_date_format();
    }

    return pwlpar_get_date_from_gmt( $date, $format );
}

function pwlpar_format_datetime( $date, $format = '' ) {
    if ( $format == 'mysql' ) {
        $format = 'Y-m-d H:i:s';
    }

    if ( ! $format ) {
        $format = wc_date_format() . ' ' . wc_time_format();
    }

    return pwlpar_get_date_from_gmt( $date, $format );
}

function pwlpar_dollars_to_points( $amount, $user_id = false ) {
    $points = 0;
    $original_amount = $amount;

    if ( !empty( $amount ) ) {
        $points = pwlpar_reward_points() * pwlpar_get_rounded_amount( $amount );
    }

    return apply_filters( 'pwlpar_dollars_to_points', $points, $original_amount, $user_id );
}

function pwlpar_get_rounded_amount( $amount ) {
    $amount = (float) $amount;
    $value = (float) pwlpar_reward_value();

    $rounded_amount = $amount;
    switch ( pwlpar_rounding_method() ) {
        case 'floor':
            $rounded_amount = floor( $amount / $value );
        break;

        case 'ceil':
            $rounded_amount = ceil( $amount / $value );
        break;

        default:
            $rounded_amount = round( $amount / $value );
        break;
    }

    return apply_filters( 'pwlpar_get_rounded_amount', $rounded_amount, $amount );
}

function pwlpar_get_history_url() {
    $url = pwlpar_get_my_account_home_url() . 'history';
    return apply_filters( 'pwlpar_history_url', $url );
}

function pwlpar_get_my_account_home_url() {
    $url = '';
    $endpoint = get_option( 'woocommerce_myaccount_pwlpar_endpoint', 'rewards' );
    if ( !empty( $endpoint ) ) {
        $url = wc_get_account_endpoint_url( 'rewards' );
    }

    $url = trailingslashit( $url );

    return apply_filters( 'pwlpar_get_my_account_home_url', $url );
}

function pwlpar_get_home_url() {
    global $wpdb;

    $url = '';
    $home_page = pwlpar_get_home_page();

    if ( !is_null( $home_page ) ) {
        $url = get_permalink( $home_page );
    }

    if ( empty( $url ) ) {
        $url = pwlpar_get_my_account_home_url();
    }

    if ( empty( $url ) ) {
        $url = pwlpar_get_url_by_shortcode( PWLPAR_HOME_SHORTCODE );
    }

    if ( empty( $url ) ) {
        $url = get_site_url();
    }

    return apply_filters( 'pwlpar_get_home_url', $url );
}

function pwlpar_get_join_url() {
    global $wpdb;

    $url = '';
    $join_page = pwlpar_get_join_page();

    if ( !is_null( $join_page ) ) {
        $url = get_permalink( $join_page );
    }

    if ( empty( $url ) ) {
        $url = pwlpar_get_url_by_shortcode( PWLPAR_JOIN_SHORTCODE );
    }

    if ( empty( $url ) ) {
        $url = get_site_url();
    }

    return apply_filters( 'pwlpar_get_join_url', $url );
}

function pwlpar_get_url_by_shortcode( $shortcode ) {
    global $wpdb;

    $url = '';

    $args = array(
        'post_type'      => 'page',
        'post_status'    => 'publish',
        's'             => '[' . $shortcode . ']', // Searches for the shortcode in content.
        'orderby'        => 'date',
        'order'          => 'DESC',
        'posts_per_page' => 1,
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
        $query->the_post();
        $url = get_permalink( get_the_ID() );
        wp_reset_postdata();
    }

    return $url;
}

function pwlpar_month_picker( $id, $name, $selected_month = '' ) {
    ?>
    <select id="<?php echo esc_attr( $id ); ?>" name="<?php echo esc_attr( $name ); ?>">
        <option value=""><?php esc_html_e( 'Select month', 'pw-loyalty-points-and-rewards-for-woocommerce' ); ?></option>
        <?php
            for ( $month = 1; $month <= 12; $month++ ) {
                $month_name = pwlpar_get_month_name( $month );
                $selected = selected( $month, $selected_month, false );

                ?>
                <option value='<?php echo esc_attr( $month ); ?>' <?php echo esc_attr( $selected ); ?>><?php echo esc_html( $month_name ); ?></option>
                <?php
            }
        ?>
    </select>
    <?php
}

function pwlpar_get_month_name( $month_number ) {
    $month_number = absint( $month_number );

    if ( empty( $month_number ) ) {
        return '';
    }

    $padded_month = str_pad( $month_number, 2, '0', STR_PAD_LEFT );
    return date_i18n( 'F', strtotime( '1980-' . $padded_month . '-01' ) );
}

function pwlpar_wc_account_creation_enabled() {
    $enabled = false;

    if ( get_option( 'woocommerce_enable_myaccount_registration' ) === 'yes' ) {
        $enabled = true;
    } else if ( WC()->checkout()->is_registration_enabled() ) {
        $enabled = true;
    }

    return apply_filters( 'pwlpar_wc_account_creation_enabled', $enabled );
}

function pwlpar_display_none( $a, $b ) {
    if ( empty( $b ) ) {
        return ( empty( $a ) == empty( $b ) ) ? 'display: none;' : '';
    }

    return ( $a == $b ) ? 'display: none;' : '';
}

function pwlpar_display_initial( $a, $b ) {
    if ( empty( $b ) ) {
        return ( empty( $a ) == empty( $b ) ) ? 'display: initial;' : '';
    }

    return ( $a == $b ) ? 'display: initial;' : '';
}

function pwlpar_get_inline_style() {
    // Add inline CSS for primary and secondary colors.
    $style = apply_filters( 'pwlpar_inline_css_colors', '
        :root {
            --pwlpar-primary-color: ' . pwlpar_primary_color() . ';
            --pwlpar-secondary-color: ' . pwlpar_secondary_color() . ';
            --pwlpar-background-color: ' . pwlpar_background_color() . ';
            --pwlpar-text-color: ' . pwlpar_text_color() . ';
        }
    ' );

    return apply_filters( 'pwlpar_inline_style', $style );
}

function pwlpar_flatten_and_sort_cart_items( $cart_items, $lowest_to_highest = true ) {
    if ( empty( $cart_items ) ) {
        return $cart_items;
    }

    usort( $cart_items, function ( $a, $b ) {
        return ( floatval( $a['line_total'] / $a['quantity'] ) < floatval( $b['line_total'] / $b['quantity'] ) ) ? -1 : 1;
    } );

    if ( $lowest_to_highest !== true ) {
        $cart_items = array_reverse( $cart_items );
    }

    $flat = array();
    foreach ( $cart_items as $cart_item ) {
        for ( $i = 0; $i < $cart_item['quantity']; $i++ ) {
            $flat[] = $cart_item;
        }
    }

    return $flat;
}
