<?php

/**
 * save preview image
 */
function ncpc_free_save_canvas_image($image, $file_name, $upload_dir = '')
{
    $upload_dirs = $upload_dir ? $upload_dir : NCPC_IMAGE_PATH;
    wp_mkdir_p($upload_dirs);
    $upload_dir = $upload_dirs . DIRECTORY_SEPARATOR;
    $file1 = base64_decode(explode(',', $image)[1]);
    $file_name1 = $upload_dir . $file_name . ".png";
    file_put_contents($file_name1, $file1);
}

/**
 * add or edit product to cart
 */
function ncpc_free_add_custom_design_to_cart_ajax()
{
    if (wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'ncpc_add_to_cart_after_custom')) {
        if (isset($_POST['data']['variation_id'])) {
            $redirectToCheckOut = isset($_POST['data']['redirectToCheckOut']) ? $_POST['data']['redirectToCheckOut'] : false;
            $displayRecapsOnCheckout = isset($_POST['data']['displayRecapsOnCheckout']) ? $_POST['data']['displayRecapsOnCheckout'] : false;
            $main_variation_id = intval($_POST['data']['variation_id']);
            $quantity = isset($_POST['data']['quantity']) ? intval($_POST['data']['quantity']) : 1;
            $cart_item_key = isset($_POST['data']['cart_item_key']) ? sanitize_key($_POST['data']['cart_item_key']) : false;
            $preview_img = isset($_POST['data']['previewImg']) ? $_POST['data']['previewImg'] : '';
            $svgData = isset($_POST['data']['svgData']) ? $_POST['data']['svgData'] : '';
            //$svgData = isset($_POST['data']['ncpc_svg_data']) ? $_POST['data']['ncpc_svg_data'] : [];
            $recaps = isset($_POST['data']['recaps']) ? map_deep($_POST['data']['recaps'], 'sanitize_text_field') : [];
            $message = '';

            /* if ( session_status() !== 2 ) {
                session_start();
            }

            $_SESSION['ncpc_calculated_totals'] = false; */

            $newly_added_cart_item_key = false;
            $file_name = uniqid('ncpc-');
            ncpc_free_save_canvas_image($preview_img, $file_name);
            $preview_img = NCPC_IMAGE_URL . '/' . $file_name . '.png';
            if ($cart_item_key) {
                WC()->cart->cart_contents[$cart_item_key]['ncpc_recaps'] = $recaps;
                WC()->cart->cart_contents[$cart_item_key]['ncpc_preview_img'] = $preview_img;
                WC()->cart->calculate_totals();
                wp_send_json(array(
                    'success' => true
                ));
            } else {
                $newly_added_cart_item_key = ncpc_free_add_designs_to_cart($main_variation_id, $recaps, $displayRecapsOnCheckout, $preview_img, $quantity);

                if ($newly_added_cart_item_key) {
                    $message = __('Product successfully added to cart.', "neon-channel-product-customizer-free");
                    wp_send_json(array(
                        'success' => true,
                        'cart_item_key' => $newly_added_cart_item_key,
                        'message' => $message,
                        'url' => $redirectToCheckOut ? wc_get_checkout_url() : wc_get_cart_url(),
                        'form_fields' => $recaps,

                    ));
                } else {
                    $message = __('A problem occured while adding the product to the cart. Please try again.', "neon-channel-product-customizer-free");
                    wp_send_json(array(
                        'success' => false,
                        'message' => $message,

                    ));
                }

            }
        } else {
            wp_send_json(array('message' => 'ID produit manquant.'));
        }
    }
}

/**
 *  add product to cart
 */
function ncpc_free_add_designs_to_cart(int $product_id, array $recaps, bool $displayRecapsOnCheckout, string $preview_img, int $quantity)
{
    $newly_added_cart_item_key = false;
    $product = wc_get_product($product_id);
    $parent_id = $product->get_parent_id();
    if ($parent_id == 0) {
        $newly_added_cart_item_key = WC()->cart->add_to_cart(
            $product_id,
            $quantity,
            0,
            array(),
            array(
                'ncpc_recaps' => $recaps,
                'ncpc_displayRecapsOnCheckout' => $displayRecapsOnCheckout,
                'ncpc_preview_img' => $preview_img
            )
        );
    } else {
        $variation = $product->get_variation_attributes();
        $newly_added_cart_item_key = WC()->cart->add_to_cart(
            $product_id,
            $quantity,
            0,
            $variation,
            array(
                'ncpc_recaps' => $recaps,
                'ncpc_displayRecapsOnCheckout' => $displayRecapsOnCheckout,
                'ncpc_preview_img' => $preview_img,
            )
        );
    }

    /* if ( isset( $_SESSION['npd_key'] ) ) {
                 $variations = get_transient( $_SESSION['npd_key'] );
             }

             foreach ( $variation as $key => $value ) {
                 if ( isset( $variations[ $key ] ) && '' === $value ) {
                     $variation[ $key ] = $variations[ $key ];
                 }
             }

             if ( isset( $_SESSION['combinaison'][ $variation_name ] ) ) {
                 $variation = $_SESSION['combinaison'][ $variation_name ];
             } */

    if (method_exists(WC()->cart, 'maybe_set_cart_cookies')) {
        WC()->cart->maybe_set_cart_cookies();
    }
    return $newly_added_cart_item_key;
}

/**
 *  includes ajax in plugin 
 */
add_action('wp_ajax_ncpc_add_custom_design_to_cart', 'ncpc_free_add_custom_design_to_cart_ajax');
add_action('wp_ajax_nopriv_ncpc_add_custom_design_to_cart', 'ncpc_free_add_custom_design_to_cart_ajax');


/**
 *  get custom products
 */
function ncpc_free_get_custom_products()
{
    $args = [
        'post_type' => 'product',
        'posts_per_page' => -1,
        'fields' => 'ids',
        'meta_query' => [
            [
                'key' => 'product-ncpc-metas',
                'value' => 'config-id";s:1:"0"',
                'compare' => 'NOT LIKE',
            ],
        ],
    ];

    $product_ids = get_posts($args);

    if (is_array($product_ids) && count($product_ids) > 0) {
        return $product_ids;
    } else {
        return [];
    }
}

function ncpc_free_dismiss_review_handler()
{

    if (!wp_verify_nonce($_POST['nonce'], 'ncpc_free_dismiss_nonce')) {
        wp_send_json_error('Safety error');
        return;
    }

    $dismiss_type = sanitize_text_field($_POST['dismiss_type']);
    $user_id = get_current_user_id();

    if ($dismiss_type === 'done') {

        update_user_meta($user_id, 'ncpc_free_review_done', true);
        wp_send_json_success('Review marked as completed');

    } elseif ($dismiss_type === 'later') {

        update_user_meta($user_id, 'ncpc_free_review_later', time() + (15 * DAY_IN_SECONDS));
        wp_send_json_success('Review postponed to a later date');

    } else {
        wp_send_json_error('Invalid dismissal type');
    }
}
add_action('wp_ajax_ncpc_free_dismiss_review', 'ncpc_free_dismiss_review_handler');
add_action('wp_ajax_nopriv_ncpc_free_dismiss_review', 'ncpc_free_dismiss_review_handler');
function ncpc_free_dismiss_promo_handler()
{
    if (!wp_verify_nonce($_POST['nonce'], 'ncpc_free_promo_nonce')) {
        wp_send_json_error('Security error');
        return;
    }

    $dismiss_type = sanitize_text_field($_POST['dismiss_type']);
    $user_id = get_current_user_id();

    if ($dismiss_type === 'done') {

        update_user_meta($user_id, 'ncpc_free_plugins_promo_dismissed', true);
        wp_send_json_success('Definitely hidden promotion');

    } elseif ($dismiss_type === 'later') {

        update_user_meta($user_id, 'ncpc_free_promo_later', time() + (15 * DAY_IN_SECONDS));
        wp_send_json_success('Promotion postponed');
    }
}
add_action('wp_ajax_ncpc_free_dismiss_promo', 'ncpc_free_dismiss_promo_handler');
add_action('wp_ajax_nopriv_ncpc_free_dismiss_promo', 'ncpc_free_dismiss_promo_handler');


function ncpc_free_track_plugin_click_handler()
{
    if (!wp_verify_nonce($_POST['nonce'], 'ncpc_free_promo_nonce')) {
        wp_send_json_error('Erreur de sécurité');
        return;
    }

    $plugin_slug = sanitize_text_field($_POST['plugin_slug']);

    // Sauvegarder les stats (optionnel)
    $stats = get_option('ncpc_free_plugin_clicks', []);
    if (!isset($stats[$plugin_slug])) {
        $stats[$plugin_slug] = 0;
    }
    $stats[$plugin_slug]++;
    update_option('ncpc_free_plugin_clicks', $stats);

    wp_send_json_success('Click enregistré');
}
add_action('wp_ajax_ncpc_free_track_plugin_click', 'ncpc_free_track_plugin_click_handler');
add_action('wp_ajax_nopriv_ncpc_free_track_plugin_click', 'ncpc_free_track_plugin_click_handler');

function handle_dismiss_pro_notice()
{

    if (!wp_verify_nonce($_POST['nonce'], 'ncpc_free_promo_nonce')) {
        wp_die('Erreur de sécurité');
    }

    $action = sanitize_text_field($_POST['dismiss_action']);
    $user_id = get_current_user_id();

    if ($action === 'done') {

        update_user_meta($user_id, 'ncpc_pro_notice_dismissed', true);

        delete_user_meta($user_id, 'ncpc_pro_notice_later');

    } elseif ($action === 'later') {

        update_user_meta($user_id, 'ncpc_pro_notice_later', time() + (15 * DAY_IN_SECONDS));

        delete_user_meta($user_id, 'ncpc_pro_notice_dismissed');
    }

    wp_die();
}
add_action('wp_ajax_ncpc_dismiss_pro_notice', 'handle_dismiss_pro_notice');