<?php

/**
 * @Packge     : daltech
 * @Version    : 1.0
 * @Author     : daltech
 * @Author URI : https://themeforest.net/user/validthemes/portfolio
 *
 */


// Blocking direct access
if (!defined('ABSPATH')) {
    exit;
}

function daltech_core_essential_scripts()
{
    wp_enqueue_script('daltech-ajax', DALTECH_PLUGDIRURI . 'assets/js/daltech.ajax.js', array('jquery'), '1.0', true);
    wp_localize_script(
        'daltech-ajax',
        'daltechajax',
        array(
            'action_url' => admin_url('admin-ajax.php'),
            'nonce'         => wp_create_nonce('daltech-nonce'),
        )
    );
}

add_action('wp_enqueue_scripts', 'daltech_core_essential_scripts');


// daltech Section subscribe ajax callback function
add_action('wp_ajax_daltech_subscribe_ajax', 'daltech_subscribe_ajax');
add_action('wp_ajax_nopriv_daltech_subscribe_ajax', 'daltech_subscribe_ajax');

function daltech_subscribe_ajax()
{
    $apiKey = daltech_opt('daltech_subscribe_apikey');
    $listid = daltech_opt('daltech_subscribe_listid');
    if (!wp_verify_nonce($_POST['security'], 'daltech-nonce')) {
        echo '<div class="alert alert-danger mt-2" role="alert">' . esc_html__('You are not allowed.', 'daltech') . '</div>';
    } else {
        if (!empty($apiKey) && !empty($listid)) {
            $MailChimp = new DrewM\MailChimp\MailChimp($apiKey);

            $result = $MailChimp->post("lists/{$listid}/members", [
                'email_address'    => esc_attr($_POST['sectsubscribe_email']),
                'status'           => 'subscribed',
            ]);
            if ($MailChimp->success()) {
                if ($result['status'] == 'subscribed') {
                    echo '<div class="alert alert-success mt-2" role="alert">' . esc_html__('Thank you, you have been added to our mailing list.', 'daltech') . '</div>';
                }
            } elseif ($result['status'] == '400') {
                echo '<div class="alert alert-danger mt-2" role="alert">' . esc_html__('This Email address is already exists.', 'daltech') . '</div>';
            } else {
                echo '<div class="alert alert-danger mt-2" role="alert">' . esc_html__('Sorry something went wrong.', 'daltech') . '</div>';
            }
        } else {
            echo '<div class="alert alert-danger mt-2" role="alert">' . esc_html__('Apikey Or Listid Missing.', 'daltech') . '</div>';
        }
    }

    wp_die();
}