<?php
/**
 * warego functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package warego
 */

if ( ! defined( '_S_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( '_S_VERSION', 5.80 );
}
include ('functions/compiled_menus.php');
include('custom-post-type/services.php');
include('custom-post-type/pricing.php');
include('custom-post-type/testimonials.php');
include('custom-post-type/faqs.php');
include('custom-post-type/industries-section.php');
include('custom-post-type/inventory-section.php');
include('custom-post-type/banner-logos.php');
include('custom-post-type/integrations.php');
// include('custom-post-type/resource.php');
include('functions/enqueue-dequeue.php');
include('functions/head.php');
include('functions/safe-image-attributes.php');

function is_valid_image_array($image) {
    if (is_array($image) && count($image) && isset($image['url']) && isset($image['alt'])) {
        return true;
    }

    return false;
}

function register_my_menu() {
    register_nav_menu('footer-menu', __('Footer Menu'));
}
add_action('init', 'register_my_menu');


function footer_register_my_menu() {
    register_nav_menu('primary-menu', __('Primary Menu'));
}
add_action('init', 'footer_register_my_menu');

require_once get_template_directory() . '/inc/class-wp-bootstrap-navwalker.php';

function theme_setup() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo', array(
        'height'      => 100,
        'width'       => 300,
        'flex-height' => true,
        'flex-width'  => true,
    ));
}
add_action('after_setup_theme', 'theme_setup');

if( function_exists('acf_add_options_page') ) {
    acf_add_options_page(array(
        'page_title'    => 'Theme Footer Settings',
        'menu_title'    => 'Footer Settings',
        'menu_slug'     => 'footer-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false
    ));
}

function mytheme_widgets_init() {
    register_sidebar(array(
        'name'          => 'Footer Widget Area',
        'id'            => 'footer-widget',
        'before_widget' => '<div class="footer-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3>',
        'after_title'   => '</h3>',
    ));
}
add_action('widgets_init', 'mytheme_widgets_init');



function subscribe_newsletter_ajax() {
    if (isset($_POST['email']) && is_email($_POST['email'])) {
        $email = sanitize_email($_POST['email']);
        
        // Assuming you are using the Newsletter plugin
        if (function_exists('newsletter_subscribe')) {
            newsletter_subscribe(array('email' => $email));
            echo '<p>Thank you for subscribing!</p>';
        } else {
            echo '<p>Subscription failed. Please try again later.</p>';
        }
    } else {
        echo '<p>Invalid email address.</p>';
    }
    wp_die(); // this is required to terminate immediately and return a response
}
add_action('wp_ajax_subscribe_newsletter', 'subscribe_newsletter_ajax');
add_action('wp_ajax_nopriv_subscribe_newsletter', 'subscribe_newsletter_ajax');



// nav menu icon
add_filter('wp_nav_menu_objects', 'navigation_wp_nav_menu_objects', 10, 2);

function navigation_wp_nav_menu_objects( $nav__items, $args ) {
    
    // loop
    foreach( $nav__items as &$nav__item ) {
        
        // vars
        $nav__icon = get_field('navigation__icon', $nav__item);
        $nav__icon_image = get_field('navigation_icon_image', $nav__item);
        
        // append icon
        if( $nav__icon ) {
            $nav__item->title = $nav__icon . ' ' . $nav__item->title;
        }
		if ( $nav__icon_image ) {

    $img_url = $nav__icon_image['url'];

    $img = '<img src="' . esc_url($img_url) . '" alt="menu icon" class="nav-icon" width="30" height="30" />';

    $nav__item->title = $img . ' ' . $nav__item->title;
}
        
    }
    
    
    // return
    return $nav__items;
    
}

// Redirects
// add_action( 'wp', function() {
//     if (is_page('industries')) wp_redirect(site_url());
// } );



function is_modal_link($link) {
    $attributes = '';

    if (
        is_string($link) &&
        (substr($link, 0, 1) == '#') &&
        str_contains($link, 'modal')
        ) {
        $attributes = 'data-bs-toggle="modal" data-bs-target="' . $link . '"';
    }

    return $attributes;
}

add_action("wp_ajax_submit_affiliate_form", "submit_affiliate_form_callback");
add_action("wp_ajax_nopriv_submit_affiliate_form", "submit_affiliate_form_callback");

function submit_affiliate_form_callback() {

    if (!isset($_POST['form_data'])) {
        wp_send_json_error("No form data received");
    }

    parse_str($_POST['form_data'], $form_data);

    $api_url = "https://affiliates.warego.co/api/affiliate/create-new";

    $response = wp_remote_post($api_url, [
        'body' => $form_data,
        'timeout' => 30,
        'headers' => [
            'Accept'        => 'application/json',
            'Authorization' => 'Bearer MddY2oO2r8lBqHRbPjl1zPUMugU312aP',
        ],
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error($response->get_error_message());
    }

    $body = wp_remote_retrieve_body($response);
    $decoded = json_decode($body, true);

    $recipients = [
		'junaid.mohsin@eplanetglobal.com',
		'junaid.mohsin@trangotech.com',
        'fahmed@eplanetglobal.com',
    ]; 

    $subject = "New Affiliate Submission";

    $message = "<h2>New Affiliate Form Submission</h2>";
    foreach ($form_data as $key => $value) {
        $message .= "<p><strong>" . esc_html(ucwords(str_replace('_', ' ', $key))) . ":</strong> " . esc_html($value) . "</p>";
    }

    $headers = [
        'Content-Type: text/html; charset=UTF-8',
        'From: Warego Affiliates <no-reply@yourdomain.com>'
    ];

    wp_mail($recipients, $subject, $message, $headers);

    if (json_last_error() === JSON_ERROR_NONE) {
        wp_send_json_success($decoded);
    } else {
        wp_send_json_success($body);
    }
}


if( function_exists('acf_add_options_page') ) {
    
    acf_add_options_page(array(
        'page_title'    => 'Schema Settings', 
        'menu_title'    => 'Schema',          
        'menu_slug'     => 'schema-settings', 
        'capability'    => 'edit_posts',      
        'redirect'      => false              
    ));

}

add_action('wpcf7_before_send_mail', function ($contact_form) {

    $submission = WPCF7_Submission::get_instance();
    if (!$submission) return;

    $data = $submission->get_posted_data();

    $payload = [
        'first_name'   => $data['firstname'] ?? '',
        'last_name'    => $data['lastname'] ?? '',
        'email'        => $data['email'] ?? '',
        'phone_number' => $data['mobilephone'] ?? '',
        'campaign_id'  => $data['campaign_id'] ?? '',
        'affiliate_id' => $data['affiliate_id'] ?? '',
    ];

    $response = wp_remote_post('https://affiliates.warego.co/campaign-lead', [
        'timeout' => 15,
        'headers' => [
            'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8',
        ],
        'body' => $payload,
    ]);

    if (is_wp_error($response)) {
        error_log('Affiliate API error: ' . $response->get_error_message());
        return;
    }

    $code = wp_remote_retrieve_response_code($response);
    if ($code < 200 || $code >= 300) {
        error_log('Affiliate API non-2xx: ' . $code . ' body=' . wp_remote_retrieve_body($response));
    }

}, 10, 1);

add_filter( 'wpcf7_form_tag', 'custom_query_string_to_cf7', 10, 2 );
function custom_query_string_to_cf7( $tag, $replace ) {
    if ( $tag['name'] != 'campaign_id' && $tag['name'] != 'affiliate_id' ) return $tag;
    
    $get_value = isset( $_GET[$tag['name']] ) ? esc_attr( $_GET[$tag['name']] ) : '';
    $tag['values'] = (array) $get_value;
    
    return $tag;
}
add_filter('wpcf7_autop_or_not', '__return_false');