<?php

include_once(get_template_directory() . '/helpers/SecuredContent.php');
include_once(get_template_directory() . '/helpers/WooHelper.php');

add_action( 'gform_after_submission_1', 'post_to_salesforce_and_five9', 10, 2 );
function post_to_salesforce_and_five9( $entry, $form ) {
    post_to_salesforce( $entry, $form );
    postFiveNine( $entry, $form );
}

function post_to_salesforce( $entry, $form ) {
    $salesforceEnvironment = get_option('select-environment');
    $Campaign_ID = $_SESSION["SESScampaignid"];
    if ($salesforceEnvironment == 'full') {
        $sfdc_oid = '00DDh0000009Umu';
        $webtolead_url = 'https://test.salesforce.com/servlet/servlet.WebToLead';
    } else {
        $sfdc_oid = '00D1I000000mJ0Q';
        $webtolead_url = 'https://webto.salesforce.com/servlet/servlet.WebToLead';
    }

    $cleanPOST = array(
        'first_name' => rgar( $entry, '1.3' ),
        'last_name' => rgar( $entry, '1.6' ),
        'phone' => rgar( $entry, '3' ),
        'email' => rgar( $entry, '4' ),
        'lead_source' => 'Web',
        'oid' => $sfdc_oid,
        'Campaign_ID' => $Campaign_ID,
        'member_status' => 'Web response',
        'Inquiring_for__c' => rgar( $entry, '5' ),
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $webtolead_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
    }

    curl_close($ch);
}

// Function to send data to Five9
function postFiveNine( $entry, $form ) {
    $Campaign_ID = '701130000026vNy';
    $F9list = "Web Form Submissions H";
    $F9domain = "connect america";
    $permalink = getenv('HTTP_REFERER');
    $title = get_permalink(url_to_postid($permalink));
    date_default_timezone_set('America/New_York');
    $F9Date = date("Y-m-d") . "-" . date("H:i");
    $newphone = preg_replace('/^1|\D/', '', rgar($entry, '3'));

    $cleanPOST = array(
        'first_name' => sanitize_text_field(rgar($entry, '1.3')),
        'last_name' => sanitize_text_field(rgar($entry, '1.6')),
        'number1' => $newphone,
        'F9domain' => $F9domain,
        'F9list' => $F9list,
        'salesforce_id' => $Campaign_ID,
        'Device_6' => $title,
        'WebDialer_Key' => $F9Date,
        'F9key' => WebDialer_Key,
        'F9CallASAP' => true
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.five9.com/web2campaign/AddToList");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
    }

    curl_close($ch);
}

session_start();

# Imports all Composer packages
require __DIR__ . '/vendor/autoload.php';

use ofc\Site;

# Declare a new Site object
$site = new Site();

# Allow the Site object to be accessed in other files
function site()
{
    global $site;
    return $site;
}

/**
 * Register Custom Navigation Walker
 */
add_action('after_setup_theme', function () {
    require_once get_template_directory() . '/bootstrap_5_wp_nav_menu_walker.php';
});

register_nav_menu('consumer-menu', 'Consumer menu');
register_nav_menu('business-menu', 'Buisness menu');
register_nav_menu('col-one-consumer-menu', 'Col 1 Consumer Menu');
register_nav_menu('col-two-consumer-menu', 'Col 2 Consumer Menu');
register_nav_menu('col-three-consumer-menu', 'Col 3 Consumer Menu');
register_nav_menu('col-four-consumer-menu', 'Col 4 Consumer Menu');
register_nav_menu('col-one-business-menu', 'Col 1 Business Menu');
register_nav_menu('col-two-business-menu', 'Col 2 Business Menu');
register_nav_menu('col-three-business-menu', 'Col 3 Business Menu');
register_nav_menu('col-four-business-menu', 'Col 4 Business Menu');

/**
 * Adds selected style sheet option as a class on body element
 */
add_filter('body_class', function ($class) {
    $style_sheet = get_field('style_sheet');
    // default to consumer brand if we don't have the ACF option for the current page
    if (!$style_sheet) {
        $style_sheet = "consumer-brand";
    }
    $class[] = $style_sheet;
    return $class;
});

/**
 * Creates a custom excerpt from an ACF post object
 */
function custom_excerpt($str, $length = 70, $append = '...')
{
    $pieces = explode(' ', strip_tags($str));
    $excerpt = implode(' ', array_slice($pieces, 0, $length));
    if (count($pieces) > $length) {
        $excerpt .= $append;
    }
    return $excerpt;
}

/**
 * Replaces post excerpt truncate and sets as a link
 */
function wpdocs_excerpt_more( $more ) {
    if ( ! is_single() ) {
        $more = sprintf( '<a class="read-more" href="%1$s">%2$s</a>',
            get_permalink( get_the_ID() ),
            __( ' Read more >>', 'textdomain' )
        );
    }
    return $more;
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );

/**
 * Function: get_phone
 * Retrieves and formats a phone number from either session or database.
 *
 * @return string Formatted phone number (e.g., 123-456-7890) or an error message if invalid.
 */
function get_phone() {
    // Local helper function as an anonymous function
    $format_phone = function ($num) {
        $num = preg_replace("/[^0-9]/", "", $num);
        if (strlen($num) < 10) {
            return "Invalid Number";
        }
        return substr($num, 0, 3) . "-" . substr($num, 3, 3) . "-" . substr($num, 6);
    };

    $num = $_SESSION['SESScampaignphone'] ?? get_option('cta_tel', true);
    return $format_phone($num);
}

add_shortcode('op', 'get_phone');

add_filter('gform_field_value_SESSpromoid', 'populate_SESSpromoid');
function populate_SESSpromoid($value) {
    if (isset($_SESSION["SESSpromoid"])) {
        return $_SESSION["SESSpromoid"];
    } else {
        return '';
    };
};

add_filter('gform_field_value_SESScoupon_code', 'populate_SESScoupon_code');
function populate_SESScoupon_code($value) {
    if (isset($_SESSION["SESScoupon_code"])) {
        return $_SESSION["SESScoupon_code"];
    } else {
        return '';
    };
};

add_filter('gform_field_value_SESSpromotion_description', 'populate_SESSpromotion_description');
function populate_SESSpromotion_description($value) {
    if (isset($_SESSION["SESSpromotion_description"])) {
        return $_SESSION["SESSpromotion_description"];
    } else {
        return '';
    };
};


/**
 * Rewrite WordPress URLs to Include /blog/ in Post Permalink Structure
 *
 * @author   Golden Oak Web Design <info@goldenoakwebdesign.com>
 * @license  https://www.gnu.org/licenses/gpl-2.0.html GPLv2+
 */
function blog_generate_rewrite_rules($wp_rewrite)
{
    $new_rules = array(
      '(([^/]+/)*blog)/page/?([0-9]{1,})/?$' => 'index.php?pagename=$matches[1]&paged=$matches[3]',
      'blog/([^/]+)/?$' => 'index.php?post_type=post&name=$matches[1]',
      'blog/[^/]+/attachment/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
      'blog/[^/]+/attachment/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
      'blog/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
      'blog/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
      'blog/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',
      'blog/[^/]+/attachment/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
      'blog/[^/]+/embed/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
      'blog/([^/]+)/embed/?$' => 'index.php?post_type=post&name=$matches[1]&embed=true',
      'blog/[^/]+/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
      'blog/([^/]+)/trackback/?$' => 'index.php?post_type=post&name=$matches[1]&tb=1',
      'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
      'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
      'blog/page/([0-9]{1,})/?$' => 'index.php?post_type=post&paged=$matches[1]',
      'blog/[^/]+/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
      'blog/([^/]+)/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
      'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&cpage=$matches[2]',
      'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?post_type=post&name=$matches[1]&page=$matches[2]',
      'blog/[^/]+/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
      'blog/[^/]+/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
      'blog/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
      'blog/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
      'blog/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

add_action('generate_rewrite_rules', 'blog_generate_rewrite_rules');

function update_post_link($post_link, $id = 0)
{
    $post = get_post($id);
    if (is_object($post) && $post->post_type == 'post') {
        return home_url('/blog/' . $post->post_name . '/');
    }
    return $post_link;
}

add_filter('post_link', 'update_post_link', 1, 3);

function skip_redirect($skip_redirect, $post_id, $post)
{
    if ($post->post_type === 'post') {
        $skip_redirect = true;
    }
    return $skip_redirect;
}
 
add_filter('wpseo_premium_post_redirect_slug_change', 'skip_redirect', 10, 3);

// Google Tag Manager
add_action('wp_head', 'gtm_output', 2);
add_action('wp_footer', 'gtm_datalayer_init', 10);
add_action('body_top', 'gtm_noscript_output');

function gtm_output()
{
    ?><!-- Google Tag Manager -->
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-MJH5WQQ');</script>
    <!-- End Google Tag Manager --><?php
}

function gtm_noscript_output()
{
    ?><!-- Google Tag Manager (noscript) -->
    <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MJH5WQQ"
    height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <!-- End Google Tag Manager (noscript) --><?php
}

function gtm_datalayer_init()
{
    ?><script>window.dataLayer = window.dataLayer || [];</script><?php
}

add_filter('mce_buttons', function ($buttons) {
    return array_merge(['styleselect'], $buttons);
});

// Attach callback to 'tiny_mce_before_init'
add_filter('tiny_mce_before_init', function ($init_array) {
    $init_array['style_formats'] = wp_json_encode([
        [
            'title' => 'CTA Primary',
            'selector' => 'a',
            'classes' => ['button--primary'],
        ],
        [
            'title' => 'CTA Secondary',
            'selector' => 'a',
            'classes' => ['btn', 'btn-secondary'],
        ],
        [
            'title' => 'CTA Tertiary',
            'selector' => 'a',
            'classes' => ['btn', 'btn-outline-primary'],
        ],
    ]);
    // die(var_dump($init_array));
    return $init_array;
});
