<?php
if (!defined('ABSPATH')) exit;

global $annuncio;
include_once ABSPATH . 'wp-admin/includes/plugin.php';

function annfu_start_session()
{
    if (!session_id()) {
        session_start();
    }
}

function annfu_end_session()
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_destroy();
    }
}

function aioseo_filter_facebook_tags($facebookMeta)
{
    if (is_singular()) {
        $facebookMeta['og:title'] = '';
        $facebookMeta['og:image'] = '';
    }
    return $facebookMeta;
}

function aioseo_filter_canonical_url($url)
{
    if (is_singular()) {
        return '';
    }
    return $url;
}

function aioseo_filter_twitter_title($twitterMeta)
{
    if (is_singular()) {
        $twitterMeta['twitter:title'] = '';
        $twitterMeta['twitter:card'] = '';
    }
    return $twitterMeta;
}

function aioseo_filter_conflicting_shortcodes($conflictingShortcodes)
{
    $conflictingShortcodes = array_merge($conflictingShortcodes, [
        'annfu_annunci' => '[ANNFU_ANNUNCI]',
        'annfu_annuncio' => '[ANNFU_ANNUNCIO]',
        'annfu_diretta' => '[ANNFU_DIRETTA]',
    ]);

    return $conflictingShortcodes;
}

function aioseo_change_wordpress_seo_title()
{
    return true;
}

function annfu_remove_seo()
{
    if (is_page(ANNFU_PAGE_ANNUNCIO)) {

        if (defined('WPSEO_VERSION')) { // Yoast SEO
            global $wpseo_front;
            if (defined($wpseo_front)) {
                remove_action('wp_head', [$wpseo_front, 'head'], 1);
            } else {
                if (class_exists(Yoast\WP\SEO\Integrations\Front_End_Integration::class)) {
                    $front_end = YoastSEO()->classes->get(Yoast\WP\SEO\Integrations\Front_End_Integration::class);
                    remove_action('wpseo_head', [$front_end, 'present_head'], -9999);
                } else {
                    $wp_thing = WPSEO_Frontend::get_instance();
                    remove_action('wp_head', [$wp_thing, 'head'], 1);
                }
            }
        }
        if (defined('AIOSEO_VERSION')) { // All-In-One SEO
            global $aiosp;
            remove_action('wp_head', [$aiosp, 'wp_head']);
        }

        if (is_plugin_active('seo-by-rank-math/rank-math.php')) { // Rank Math SEO
            // Rimuovi solo i meta tag di Rank Math, non i filtri sul contenuto
            remove_all_actions('rank_math/head');
            remove_all_filters('rank_math/frontend/title');
            remove_all_filters('rank_math/frontend/description');
            // NON rimuoviamo the_content perché potrebbe bloccare l'esecuzione degli shortcode
        }

        if (is_plugin_active('autodescription/autodescription.php')) { // The SEO Framework
            remove_all_filters('pre_get_document_title', false);
            add_filter('pre_get_document_title', 'annfu_title', 10, 2);
        }
    }
}

function annfu_title($title)
{
    global $wp_query, $annuncio;
    $vars = $wp_query->query_vars;

    if (is_page([ANNFU_PAGE_ANNUNCIO, ANNFU_PAGE_DIRETTA]) && isset($vars['slug'])) {

        if (is_null($annuncio)) {
            $http_host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
            $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
            $referer = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://" . $http_host . $request_uri;
            $response = wp_remote_get(ANNFU_SITE_API . "/v2/annunci/" . $vars['slug']."?".time(), [
                'sslverify' => false,
                'timeout' => ANNFU_REMOTE_TIMEOUT,
                'headers' => ['of' => get_option('annfu_onoranza_funebre_id'), 'ref' => $referer]
            ]);
            $annuncio = json_decode(wp_remote_retrieve_body($response), true);
            if (is_null($annuncio)) {
                $wp_query->set_404();
                status_header(404);
            }
        }

        $annuncioData = $annuncio['data'];

        if (is_page(ANNFU_PAGE_ANNUNCIO)) {
            $title = (isset($annuncioData) && isset($annuncioData['nominativo']) ? $annuncioData['nominativo'] . ' - Necrologio e condoglianze su ' : '') . get_bloginfo('name');
        } elseif (is_page(ANNFU_PAGE_DIRETTA)) {
            $title = 'Diretta del funerale di ' . $annuncioData['nominativo'];
        }
    }

    return $title;
}

function annfu_head()
{
    global $wp_query, $annuncio;
    $vars = $wp_query->query_vars;

    if (get_option('annfu_search_console') != '') {
        echo '<meta name="google-site-verification" content="' . esc_attr(get_option('annfu_search_console')) . '"/>';
    }

    wp_enqueue_style('af-pwa', ANNFU_PLUGIN_URL . 'css/pwa.css', false, ANNFU_VERSION, 'all');
    wp_enqueue_script('af-cookie', ANNFU_PLUGIN_URL . 'js/js.cookie.js', ['jquery'], ANNFU_VERSION, true);

    if (is_page([ANNFU_PAGE_ANNUNCIO, ANNFU_PAGE_ANNUNCI, ANNFU_PAGE_DIRETTA]) || is_front_page() || is_active_widget(false, false, 'annfu_widget', true)) {
        wp_enqueue_script('af-alpinejs', ANNFU_PLUGIN_URL . 'js/alpine.min.js', [], '3.14.1', true);
        wp_enqueue_script('af-select2', ANNFU_PLUGIN_URL . 'js/select2.min.js', ['jquery'], ANNFU_VERSION, true);
        if (get_option('annfu_bootstrap', 4) == 4) {
            wp_enqueue_script('af-bootstrap', ANNFU_PLUGIN_URL . 'js/bootstrap4-annfu.min.js', ['jquery'], ANNFU_VERSION, true);
        } elseif (get_option('annfu_bootstrap') == 3) {
            wp_enqueue_script('af-bootstrap', ANNFU_PLUGIN_URL . 'js/bootstrap3-annfu.min.js', ['jquery'], ANNFU_VERSION, true);
        }
        wp_enqueue_script('jquery-ui-datepicker');
        wp_enqueue_script('af-dropzone', ANNFU_PLUGIN_URL . 'js/dropzone.min.js', ['jquery'], ANNFU_VERSION, true);
        wp_enqueue_script('af-slick', ANNFU_PLUGIN_URL . 'js/slick.min.js', ['jquery'], ANNFU_VERSION, false);
        wp_enqueue_script('af-colorbox', ANNFU_PLUGIN_URL . 'js/jquery.colorbox.min.js', ['jquery'], ANNFU_VERSION, false);
        wp_enqueue_script('af', ANNFU_PLUGIN_URL . 'js/annuncifunebri.js', [], ANNFU_VERSION, true);
        wp_enqueue_script('af-fiori', ANNFU_PLUGIN_URL . 'js/annuncifunebriFiori.js', [], ANNFU_VERSION, true);
        wp_enqueue_script('af-ricordi-floreali', ANNFU_PLUGIN_URL . 'js/annuncifunebriRicordiFloreali.js', [], ANNFU_VERSION, true);
        wp_enqueue_script('af-fotocordogli', ANNFU_PLUGIN_URL . 'js/annuncifunebriFotoCordogli.js', [], ANNFU_VERSION, true);
        wp_enqueue_script('af-analytics', ANNFU_PLUGIN_URL . 'js/analytics.js', [], ANNFU_VERSION, true);

        wp_enqueue_style('af-font-awesome', ANNFU_PLUGIN_URL . 'css/fa6-all.min.css', false, ANNFU_VERSION, 'all');
        wp_enqueue_style('af-font-awesome-compatibility', ANNFU_PLUGIN_URL . 'css/v5-font-face.min.css', false, ANNFU_VERSION, 'all');
        wp_enqueue_style('af-jquery-ui', ANNFU_PLUGIN_URL . 'css/jquery-ui.min.css', false, ANNFU_VERSION, 'all');
        if (get_option('annfu_bootstrap', 4) == 4) {
            wp_enqueue_style('af-bootstrap4', ANNFU_PLUGIN_URL . 'css/bootstrap4-annfu.min.css', false, ANNFU_VERSION, 'all');
        } elseif (get_option('annfu_bootstrap') == 3) {
            wp_enqueue_style('af-bootstrap3', ANNFU_PLUGIN_URL . 'css/bootstrap3-annfu.min.css', false, ANNFU_VERSION, 'all');
        }
        wp_enqueue_style('af-select2', ANNFU_PLUGIN_URL . 'css/select2.min.css', false, ANNFU_VERSION, 'all');
        wp_enqueue_style('af-dropzone', ANNFU_PLUGIN_URL . 'css/dropzone.min.css', false, ANNFU_VERSION, 'all');
        wp_enqueue_style('af-slick', ANNFU_PLUGIN_URL . 'css/slick.min.css', [], ANNFU_VERSION, 'all');
        wp_enqueue_style('af-colorbox', ANNFU_PLUGIN_URL . 'css/colorbox.min.css', [], ANNFU_VERSION, 'all');
        wp_enqueue_style('af', ANNFU_PLUGIN_URL . 'css/style.css', false, ANNFU_VERSION . wp_date( 'YmdHi' ), 'all');

        $template = get_annfu_template();
        if (file_exists(ANNFU_PLUGIN_PATH . 'css/style-' . $template . '.css')) {
            wp_enqueue_style('af-custom', ANNFU_PLUGIN_URL . 'css/style-' . $template . '.css', false, ANNFU_VERSION, 'all');
        }

        echo '<meta name="af-version" content="' . esc_attr(ANNFU_VERSION) . '"/>';
    }

    if (is_page(ANNFU_PAGE_DIRETTA)) {
        wp_enqueue_script('annuncifunebri-streaming', ANNFU_PLUGIN_URL . 'js/clappr.min.js', [], ANNFU_VERSION, true);
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Password verification for streaming access
        if (isset($_POST['password'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Password verification for streaming access
            $password = sanitize_text_field( wp_unslash( $_POST['password'] ) );
            $value = annfu_encrypt(hash('sha256', $password));
            setcookie('annuncifunebri_streaming', $value, time() + 3 * HOUR_IN_SECONDS, '/');
            $_COOKIE['annuncifunebri_streaming'] = $value;
        }
    }

    if (is_page(ANNFU_PAGE_ANNUNCI)) {
        annfu_delete_annunci_cookies();
        annfu_add_annunci_cookies();
        $page = isset($vars['pg']) && is_numeric($vars['pg']) ? $vars['pg'] : 1;
        $value = annfu_encrypt($page);
        if (!headers_sent()) {
            setcookie('annuncifunebri_page', $value, time() + MONTH_IN_SECONDS, '/');
        }
        $_COOKIE['annuncifunebri_page'] = $value;
    }

    if (isset($vars['comune']) && isset($vars['slug'])) {

        if (is_null($annuncio)) {
            $http_host = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
            $request_uri = isset($_SERVER['REQUEST_URI']) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
            $referer = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://" . $http_host . $request_uri;
            $response = wp_remote_get(ANNFU_SITE_API . "/v2/annunci/" . $vars['slug']."?".time(), [
                'sslverify' => false,
                'timeout' => ANNFU_REMOTE_TIMEOUT,
                'headers' => ['of' => get_option('annfu_onoranza_funebre_id'), 'ref' => $referer]
            ]);
            $annuncio = json_decode(wp_remote_retrieve_body($response), true);
            if (is_null($annuncio)) {
                $wp_query->set_404();
                status_header(404);
            }
        }

        if (array_key_exists('metaData', $annuncio)) {
            $metaData = $annuncio['metaData'];
            $annuncioData = $annuncio['data'];
        } else {
            $annuncioData = $annuncio;
        }

        $cordoglioId = isset($_COOKIE['cordoglio_id']) ? sanitize_text_field( wp_unslash( $_COOKIE['cordoglio_id'] ) ) : null;
        if ($cordoglioId && array_key_exists('cordogli_approvati', $annuncio['data']) && in_array($cordoglioId, $annuncio['data']['cordogli_approvati'])) {
            setcookie("cordoglio_id", "", time() - 3600 * 24, '/');
            unset($_COOKIE['cordoglio_id']);
        }


        $title = (isset($annuncioData) && isset($annuncioData['nominativo']) ? $annuncioData['nominativo'] . ' - Necrologio e condoglianze su ' : '') . get_bloginfo('name');
        $description = $annuncioData['testo'] != '' ? substr( wp_strip_all_tags( $annuncioData['testo'] ), 0, 120 ) . "..." : "";
        echo '<title>' . esc_html($title) . '</title>' . "\n";
        echo '<link rel="canonical" href="' . esc_url(get_permalink() . $vars['comune'] . '/' . $vars['slug'] . '/') . '" />' . "\n";
        echo '<meta name="description" content="' . esc_attr($description) . '" />' . "\n";
        echo '<meta name="keywords" content="' . esc_attr(str_replace('"', '\'', $annuncioData['nominativo']) . ', ' . $annuncioData['onoranzaFunebre']['ragioneSociale'] . ', annuncio, annunci, funebri, onoranza, funebre, conforto, cordoglio, partecipazione, defunto, morto') . '" />';
        echo '<meta property="og:site_name" content="' . esc_attr(get_site_url()) . '"/>';
        if ($annuncioData['onoranzaFunebre']['slug'] == 'fratelliferrario') {
            echo '<meta property="og:title" content="' . esc_attr(str_replace('"', '\'', $annuncioData['nominativo']) . ' - Invia le tue Condoglianze Online') . '"/>';
        } else if ($annuncioData['onoranzaFunebre']['slug'] == 'casasrl') {
            echo '<meta property="og:title" content="' . esc_attr(str_replace('"', '\'', $annuncioData['nominativo']) . ' - Casa funeraria Caliendo - Celestial') . '"/>';
        } else {
            echo '<meta property="og:title" content="' . esc_attr($title) . '"/>';
        }
        echo '<meta property="og:type" content="profile" />';
        echo '<meta property="og:description" content="' . esc_attr($description . $annuncioData['onoranzaFunebre']['ragioneSociale']) . '" />';
        echo '<meta property="og:url" content="' . esc_attr(esc_url(get_permalink() . $vars['comune'] . '/' . $vars['slug'] . '/')) . '"/>';
        if (!is_null($annuncioData['facebookFoto'])) {
            echo '<meta property="og:image" content="' . esc_attr(esc_url(annfu_fix_url($annuncioData['facebookFoto']))) . '"/>';
        } elseif (get_option('annfu_epigrafe_facebook', 0) && $annuncioData['onoranzaFunebre']['showEpigrafeAnteprima'] && filter_var($annuncioData['fileEpigrafe'], FILTER_VALIDATE_URL) && substr($annuncioData['fileEpigrafe'], -4) != '.pdf') {
            echo '<meta property="og:image" content="' . esc_attr(esc_url(annfu_fix_url($annuncioData['fileEpigrafe']))) . '"/>';
            echo '<meta property="og:image:width" content="' . esc_attr($annuncioData['fileEpigrafeWidth']) . '" />';
            echo '<meta property="og:image:height" content="' . esc_attr($annuncioData['fileEpigrafeHeight']) . '" />';
        } elseif (!is_null($annuncioData['foto'])) {
            echo '<meta property="og:image" content="' . esc_attr(esc_url(annfu_fix_url($annuncioData['foto']))) . '"/>';
            echo '<meta property="og:image:width" content="300" />';
            echo '<meta property="og:image:height" content="360" />';
        }
        echo '<meta property="og:first_name" content="' . esc_attr(str_replace('"', '\'', $annuncioData['nome'])) . '"/>';
        echo '<meta property="og:last_name" content="' . esc_attr(str_replace('"', '\'', $annuncioData['cognome'])) . '"/>';
        echo '<meta property="fb:app_id" content="966242223397117"/>';

        $schema = [
    '@context' => 'http://schema.org',
    '@type' => 'Article',
    'headline' => $annuncioData['nominativo'],
    'author' => [
        '@type' => 'Organization',
        'name' => $annuncioData['onoranzaFunebre']['ragioneSociale'],
        'url' => get_site_url(),
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => $annuncioData['onoranzaFunebre']['via'],
            'addressLocality' => $annuncioData['onoranzaFunebre']['comune'],
            'postalCode' => $annuncioData['onoranzaFunebre']['cap'],
            'addressCountry' => 'ITA',
        ],
        'contactPoint' => [
            [
                '@type' => 'ContactPoint',
                'telephone' => '+39 ' . $annuncioData['onoranzaFunebre']['telefono1'],
                'contactType' => 'customer service',
                'contactOption' => 'H24',
                'email' => $annuncioData['onoranzaFunebre']['mail'],
            ],
        ],
        'logo' => [
            '@type' => 'ImageObject',
            'url' => $annuncioData['onoranzaFunebre']['logo'],
        ],
    ],
    'url' => get_permalink() . $vars['comune'] . '/' . $vars['slug'],
    'mainEntityOfPage' => get_permalink() . $vars['comune'] . '/' . $vars['slug'],
    'image' => annfu_fix_url($annuncioData['foto']),
    'genre' => 'necrologie',
    'description' => $annuncioData['apertura'] != "" ? wp_strip_all_tags( str_replace( array( "\u{2019}", "\u{201C}", "\u{201D}", "\\" ), array( "'", "\"", "\"", "/" ), $annuncioData['apertura'] ) ) : "",
    'articleBody' => $annuncioData['testo'] != "" ? wp_strip_all_tags( str_replace( array( "\u{2019}", "\u{201C}", "\u{201D}", "\\" ), array( "'", "\"", "\"", "/" ), $annuncioData['testo'] ) ) : "",
    'datePublished' => date_i18n('c', strtotime($annuncioData['data'])),
    'dateModified' => date_i18n('c', strtotime($annuncioData['updatedAt'])),
    'publisher' => [
        '@type' => 'Organization',
        'name' => $annuncioData['onoranzaFunebre']['ragioneSociale'],
        'url' => get_site_url(),
        'address' => [
            '@type' => 'PostalAddress',
            'streetAddress' => $annuncioData['onoranzaFunebre']['via'],
            'addressLocality' => $annuncioData['onoranzaFunebre']['comune'],
            'postalCode' => $annuncioData['onoranzaFunebre']['cap'],
            'addressCountry' => 'ITA',
        ],
        'contactPoint' => [
            [
                '@type' => 'ContactPoint',
                'telephone' => '+39 ' . $annuncioData['onoranzaFunebre']['telefono1'],
                'contactType' => 'customer service',
                'contactOption' => 'H24',
                'email' => $annuncioData['onoranzaFunebre']['mail'],
            ],
        ],
        'logo' => [
            '@type' => 'ImageObject',
            'url' => $annuncioData['onoranzaFunebre']['logo'],
        ],
    ],
];
echo '<script type="application/ld+json">' . wp_json_encode($schema) . '</script>';
        if (isset($annuncioData['onoranzaFunebre']['openReplay']) && $annuncioData['onoranzaFunebre']['openReplay'] == 1) {
            include('_open-replay.php');
        }
    }
}

function annfu_add_annunci_cookies()
{
    global $wp_query;
    $vars = $wp_query->query_vars;
    $variables = annfu_query_variables();
    foreach ($variables as $var) {
        if (isset($vars[$var]) && $vars[$var] != "") {
            if ($var == "dal" || $var == "al") {
                list($gg, $mm, $aa) = explode("/", $vars[$var]);
                $value = annfu_encrypt($aa . "-" . $mm . "-" . $gg);
                setcookie('annuncifunebri_' . $var . '_en', $value, time() + MONTH_IN_SECONDS, '/');
                $_COOKIE['annuncifunebri_' . $var . '_en'] = $value;
            }
            $value = annfu_encrypt($vars[$var]);
            setcookie('annuncifunebri_' . $var, $value, time() + MONTH_IN_SECONDS, '/');
            $_COOKIE['annuncifunebri_' . $var] = $value;
        }
    }
}

function annfu_delete_annunci_cookies()
{
    $variables = annfu_query_variables();
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Search/filter parameters, not a form action
    $text = isset($_GET['text']) ? sanitize_text_field( wp_unslash( $_GET['text'] ) ) : '';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Search/filter parameters, not a form action
    if (isset($_GET['reset']) || (isset($_GET['text']) && $text == '')) {
        setcookie('annuncifunebri_page', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_page']);
        setcookie('annuncifunebri_dal_en', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_dal_en']);
        setcookie('annuncifunebri_al_en', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_al_en']);
        foreach ($variables as $var) {
            setcookie('annuncifunebri_' . $var, '', time() - 3600, '/');
            unset($_COOKIE['annuncifunebri_' . $var]);
        }
        return; // Esci dopo il reset completo
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Search/filter parameters, not a form action
    $avanzata = isset($_GET['avanzata']) ? sanitize_text_field( wp_unslash( $_GET['avanzata'] ) ) : '';

    // Se stiamo solo navigando tra le pagine (nessun parametro di ricerca), non cancellare i cookies
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Search/filter parameters, not a form action
    $has_search_params = isset($_GET['text']) || isset($_GET['nome']) || isset($_GET['cognome']) ||
                         isset($_GET['dal']) || isset($_GET['al']) || isset($_GET['paese']) ||
                         isset($_GET['avanzata']) || isset($_GET['regione']) || isset($_GET['provincia']);

    if (!$has_search_params) {
        // Solo paginazione, mantieni tutti i cookies di ricerca
        return;
    }

    if ($avanzata == '1') {
        setcookie('annuncifunebri_text', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_text']);
        setcookie('annuncifunebri_regione', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_regione']);
        setcookie('annuncifunebri_provincia', '', time() - 3600, '/');
        unset($_COOKIE['annuncifunebri_provincia']);
    } elseif ($avanzata == '0') {
        foreach ($variables as $var) {
            if ($var != 'text') {
                setcookie('annuncifunebri_' . $var, '', time() - 3600, '/');
                unset($_COOKIE['annuncifunebri_' . $var]);
            }
        }
    } else {
        foreach ($variables as $var) {
            if ($var != 'regione' && $var != 'provincia') {
                if (!headers_sent()) {
                    setcookie('annuncifunebri_' . $var, '', time() - 3600, '/');
                }
                unset($_COOKIE['annuncifunebri_' . $var]);
            }
        }
    }
}

function annfu_header()
{
    if (get_option('annfu_abilita_notifiche_pwa', 0) == 1) {
        include('_download_pwa.php');
    }
}

function annfu_footer()
{
    if (get_option('annfu_abilita_notifiche_pwa', 0) == 1) {
        include('_allow_notifications.php');
    }
}

function annfu_query_variables()
{
    return ['text', 'regione', 'provincia', 'onoranza_funebre_id', 'nome', 'cognome', 'paese', 'dal', 'al'];
}

function annfu_query_annunci()
{
    global $wp_query;
    $vars = $wp_query->query_vars;
    $variables = annfu_query_variables();

    $limit = get_option('annfu_max_per_page', ANNFU_MAX_PER_PAGE);
    $page = isset($vars['pg']) && is_numeric($vars['pg']) ? $vars['pg'] : 1;

    $query = '?onoranza_funebre_id=' . get_option('annfu_onoranza_funebre_id');
    foreach ($variables as $var) {
        // Usa || invece di && per leggere dal cookie anche se il parametro non è nell'URL
        if (isset($vars[$var]) || isset($_COOKIE['annuncifunebri_' . $var])) {
            if ($var == "dal" || $var == "al") {
                // Usa il valore dall'URL se presente e non vuoto
                if (isset($vars[$var]) && $vars[$var] != '') {
                    $query .= '&' . $var . '=' . annfu_get_date_parameter($var);
                } elseif (isset($_COOKIE['annuncifunebri_' . $var . '_en'])) {
                    // Altrimenti usa il cookie
                    $cookie_en_key = 'annuncifunebri_' . $var . '_en';
                    $cookie_en_value = isset($_COOKIE[ $cookie_en_key ]) ? sanitize_text_field( wp_unslash( $_COOKIE[ $cookie_en_key ] ) ) : '';
                    $query .= '&' . $var . '=' . htmlspecialchars( annfu_decrypt( $cookie_en_value ) );
                }
            } else {
                $cookie_key = 'annuncifunebri_' . $var;
                if (isset($_COOKIE[$cookie_key])) {
                    $cookie_value = sanitize_text_field( wp_unslash( $_COOKIE[$cookie_key] ) );
                    // Usa il valore dall'URL se presente e non vuoto, altrimenti dal cookie
                    $url_value = isset($vars[$var]) && $vars[$var] != '' ? $vars[$var] : null;
                    $value = $url_value !== null ? $url_value : annfu_decrypt( $cookie_value );
                    $query .= '&' . $var . '=' . urlencode( htmlspecialchars( $value ) );
                } elseif (isset($vars[$var]) && $vars[$var] != '') {
                    $query .= '&' . $var . '=' . urlencode( htmlspecialchars( $vars[$var] ) );
                }
            }
        }
    }
    $query .= $limit != ANNFU_MAX_PER_PAGE ? "&limit=" . $limit : "";
    $query .= $page != 1 ? "&page=" . $page : "";

    return $query;
}


function annfu_annunci_shortcode()
{
    if (get_option('annfu_onoranza_funebre_id') != '') {
        ob_start();
        include('annunci.php'); // Cambiato da include_once a include per supportare chiamate multiple
        $content = ob_get_clean();

        return $content;
    } else {
        return 'Plugin Annunci Funebri non configurato';
    }
}

function annfu_annunci_register_shortcode()
{
    add_shortcode('ANNFU_ANNUNCI', 'annfu_annunci_shortcode');
}

function annfu_ultimi_annunci_shortcode()
{
    if (get_option('annfu_onoranza_funebre_id') != '') {
        ob_start();
        include('ultimi-annunci.php'); // Cambiato da include_once a include per supportare chiamate multiple
        $content = ob_get_clean();

        return $content;
    } else {
        return 'Plugin Annunci Funebri non configurato';
    }
}

function annfu_ultimi_annunci_register_shortcode()
{
    add_shortcode('ANNFU_ULTIMI_ANNUNCI', 'annfu_ultimi_annunci_shortcode');
}

function annfu_annuncio_shortcode()
{
    if (get_option('annfu_onoranza_funebre_id') != '') {
        ob_start();
        include('annuncio.php'); // Cambiato da include_once a include per supportare chiamate multiple
        $content = ob_get_clean();

        return $content;
    } else {
        return 'Plugin Annunci Funebri non configurato';
    }
}

function annfu_annuncio_register_shortcode()
{
    add_shortcode('ANNFU_ANNUNCIO', 'annfu_annuncio_shortcode');
}

function annfu_diretta_shortcode()
{
    if (get_option('annfu_onoranza_funebre_id') != '') {
        ob_start();
        include('diretta.php'); // Cambiato da include_once a include per supportare chiamate multiple
        $content = ob_get_clean();

        return $content;
    } else {
        return 'Plugin Annunci Funebri non configurato';
    }
}

function annfu_diretta_register_shortcode()
{
    add_shortcode('ANNFU_DIRETTA', 'annfu_diretta_shortcode');
}

// aggiungo le variabili che mi servono nella riscrittura degli URL
function annfu_add_query_vars($aVars)
{
    $aVars[] = "text";
    $aVars[] = "slug";
    $aVars[] = "regione";
    $aVars[] = "provincia";
    $aVars[] = "regione_id";
    $aVars[] = "provincia_id";
    $aVars[] = "comune";
    $aVars[] = "nome";
    $aVars[] = "cognome";
    $aVars[] = "paese";
    $aVars[] = "dal";
    $aVars[] = "al";
    $aVars[] = "pg";

    return $aVars;
}

// riscrivo gli URL come mi serve
function annfu_rewrite_rules()
{
    add_rewrite_rule(ANNFU_PAGE_DIRETTA . '/([^/]+)$', 'index.php?pagename=' . ANNFU_PAGE_DIRETTA . '&slug=$matches[1]', 'top');
    add_rewrite_rule(ANNFU_PAGE_ANNUNCIO . '/([^/]+)/([^/]+)$', 'index.php?pagename=' . ANNFU_PAGE_ANNUNCIO . '&comune=$matches[1]&slug=$matches[2]', 'top');
    add_rewrite_rule(ANNFU_PAGE_ANNUNCI . '/(\d+)/?$', 'index.php?pagename=' . ANNFU_PAGE_ANNUNCI . '&pg=$matches[1]', 'top');
    add_rewrite_rule(ANNFU_PAGE_ANNUNCI . '/([^/]+)/?$', 'index.php?pagename=' . ANNFU_PAGE_ANNUNCI . '&regione=$matches[1]', 'top');
    add_rewrite_rule(ANNFU_PAGE_ANNUNCI . '/([^/]+)/([^/]+)/?$', 'index.php?pagename=' . ANNFU_PAGE_ANNUNCI . '&regione=$matches[1]&provincia=$matches[2]', 'top');
    add_rewrite_rule(ANNFU_PAGE_ANNUNCI . '/([^/]+)/([^/]+)/(\d+)/?$', 'index.php?pagename=' . ANNFU_PAGE_ANNUNCI . '&regione=$matches[1]&provincia=$matches[2]&pg=$matches[3]', 'top');
    add_rewrite_rule(ANNFU_PAGE_AF_VERSION, 'index.php?af-version=' . ANNFU_VERSION, 'top');
    flush_rewrite_rules();
}

function annfu_add_endpoints()
{
    if (is_page([ANNFU_PAGE_ANNUNCIO, ANNFU_PAGE_ANNUNCI, ANNFU_PAGE_DIRETTA])) {
        header("Cache-Control: no-cache");
    }

    add_rewrite_endpoint(ANNFU_PAGE_ANNUNCIO, EP_PAGES);
}

function annfu_rewrite_tag()
{
    add_rewrite_tag('%pagename%', '([^&]+)');
    add_rewrite_tag('%regione%', '([^&]+)');
    add_rewrite_tag('%provincia%', '([^&]+)');
    add_rewrite_tag('%comune%', '([^&]+)');
    add_rewrite_tag('%slug%', '([^&]+)');
    add_rewrite_tag('%annuncio%', '([^&]+)');
}

function annfu_text_url($link, $text, $blank = null)
{
    $htmlLink = $text;
    if (filter_var($link, FILTER_VALIDATE_URL)) {
        $htmlLink = "<a href=\"" . esc_url($link) . "\" " . (!is_null($blank) ? "target=\"_blank\"" : "") . ">{$text}</a>";
    }

    return $htmlLink;
}

function annfu_script_defer($tag, $handle)
{
    return 'af-alpinejs' !== $handle ? $tag : str_replace(' src', ' defer src', $tag);
}

function get_annfu_version()
{
    register_rest_route('annfu', '/version', [
        'methods' => 'GET',
        'callback' => 'annfu_version',
        'permission_callback' => '__return_true',
    ]);
}

function annfu_version()
{
    return ['version' => ANNFU_VERSION];
}

function get_annfu_template()
{
    $template = get_option('annfu_template', 'default');

    return $template == '' ? 'default' : $template;
}

// menu
function annfu_menu()
{
    // Menu principale che punta alle impostazioni
    add_menu_page(
        __('Annunci Funebri', 'annuncifunebri-onoranza'),
        __('Annunci Funebri', 'annuncifunebri-onoranza'),
        'edit_others_pages',
        'af-plugin',
        'annfu_admin',
        ANNFU_IMG . 'af.png'
    );

    // Il primo submenu viene aggiunto automaticamente da WordPress con lo stesso nome del menu principale.
    // Lo rinominiamo in "Impostazioni" usando remove + add
    remove_submenu_page('af-plugin', 'af-plugin');

    // Aggiungi Impostazioni come primo submenu
    add_submenu_page(
        'af-plugin',
        __('Impostazioni', 'annuncifunebri-onoranza'),
        __('Impostazioni', 'annuncifunebri-onoranza'),
        'edit_others_pages',
        'af-plugin',
        'annfu_admin'
    );
}

// Hook per riordinare i submenu dopo che tutti i plugin hanno registrato i loro
function annfu_fix_menu_order() {
    global $submenu;

    // Verifica che il menu esista
    if (!isset($submenu['af-plugin'])) {
        return;
    }

    // Riordina i submenu per avere l'ordine corretto
    $items = $submenu['af-plugin'];
    $ordered = [];

    // 1. Prima: Impostazioni (af-plugin)
    foreach ($items as $item) {
        if ($item[2] === 'af-plugin') {
            $ordered[] = $item;
            break;
        }
    }

    // 2. Secondo: Template Personalizzati
    foreach ($items as $item) {
        if (strpos($item[2], 'post_type=annfu_el_template') !== false) {
            $ordered[] = $item;
            break;
        }
    }

    // 3. Resto degli item
    foreach ($items as $item) {
        if ($item[2] !== 'af-plugin' && strpos($item[2], 'post_type=annfu_el_template') === false) {
            $ordered[] = $item;
        }
    }

    $submenu['af-plugin'] = $ordered;
}
add_action('admin_menu', 'annfu_fix_menu_order', 999);

// script e css
function annfu_admin_scripts($hook)
{
    if ('toplevel_page_af-plugin' != $hook) {
        return;
    }
    wp_enqueue_script('af-ace', ANNFU_PLUGIN_URL . 'js/ace/ace.js', ['jquery'], ANNFU_VERSION, true);
    wp_enqueue_script('af-bootstrap4', ANNFU_PLUGIN_URL . 'js/bootstrap4-annfu.min.js', ['jquery'], ANNFU_VERSION, true);
    wp_enqueue_script('af-cp', ANNFU_PLUGIN_URL . 'js/bootstrap-colorpicker.min.js', ['jquery'], ANNFU_VERSION, true);
    wp_enqueue_script('af', ANNFU_PLUGIN_URL . 'js/annuncifunebriAdmin.js', ['jquery'], ANNFU_VERSION, true);
    wp_enqueue_style('af-bootstrap4', ANNFU_PLUGIN_URL . 'css/bootstrap4-annfu.min.css', [], ANNFU_VERSION, 'all');
    wp_enqueue_style('af', ANNFU_PLUGIN_URL . 'css/style.css', [], ANNFU_VERSION, 'all');
    wp_enqueue_style('af-font-awesome-admin', ANNFU_PLUGIN_URL . 'css/fa6-all.min.css', [], ANNFU_VERSION, 'all');
    wp_enqueue_style('af-cp', ANNFU_PLUGIN_URL . 'css/bootstrap-colorpicker.min.css', false, '1.0', 'all');
}

function annfu_get_testi_aggiuntivi()
{
    return [
        'cima_annuncio' => 'Testo visibile in cima all\'annuncio',
        'fondo_annuncio' => 'Testo visibile in fondo all\'annuncio',
        'fondo_form_cordogli' => 'Testo visibile in fondo alla form di inserimento cordogli',
        'invito_download_pwa_android' => 'Testo del pulsante per il download della PWA (solo Android)',
        'invito_download_pwa_ios' => 'Testo di invito al download della PWA (solo iOS)'
    ];
}

// pagina di amministrazione
function annfu_admin()
{
    require_once('backoffice.php');
}

//salvataggio del form
function annfu_register_settings()
{
    // Impostazioni testuali con sanitizzazione
    register_setting('af-settings', 'annfu_onoranza_funebre_id', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    register_setting('af-settings', 'annfu_page_annunci', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    register_setting('af-settings', 'annfu_page_annuncio', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    register_setting('af-settings', 'annfu_page_diretta', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));

    // Impostazioni numeriche
    register_setting('af-settings', 'annfu_max_per_page', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_foto_w_annuncio', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_foto_h_annuncio', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_pages', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_ultimi_annunci', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_ultimi_annunci_per_slide', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_bootstrap', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    register_setting('af-settings', 'annfu_template', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));

    // URL con validazione
    register_setting('af-settings', 'annfu_link_fiori', array(
        'type' => 'string',
        'sanitize_callback' => 'esc_url_raw',
    ));

    // Checkbox (booleani)
    register_setting('af-settings', 'annfu_lightbox', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_breadcrumbs', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_search_console', array(
        'type' => 'string',
        'sanitize_callback' => 'sanitize_text_field',
    ));
    register_setting('af-settings', 'annfu_poweredby', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_abilita_notifiche_pwa', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_notifiche_pwa_fixed', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_epigrafe_facebook', array(
        'type' => 'boolean',
        'sanitize_callback' => 'absint',
    ));

    // HTML consentito (privacy personalizzata)
    register_setting('af-settings', 'annfu_custom_privacy', array(
        'type' => 'string',
        'sanitize_callback' => 'wp_kses_post',
    ));

    // CSS personalizzato - sanitizzazione specifica
    register_setting('af-settings', 'annfu_css', array(
        'type' => 'string',
        'sanitize_callback' => 'annfu_sanitize_css',
    ));
    register_setting('af-settings', 'annfu_css_pwa', array(
        'type' => 'string',
        'sanitize_callback' => 'annfu_sanitize_css',
    ));

    // Template Elementor (ID numerici)
    register_setting('af-settings', 'annfu_template_elementor_annunci', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_template_elementor_annuncio', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));
    register_setting('af-settings', 'annfu_template_elementor_diretta', array(
        'type' => 'integer',
        'sanitize_callback' => 'absint',
    ));

    // Opzioni colori
    $afOptionColors = annfu_get_options();
    foreach ($afOptionColors as $k => $v) {
        register_setting('af-settings', $k, array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_hex_color',
        ));
    }

    // Testi aggiuntivi
    $testi = annfu_get_testi_aggiuntivi();
    foreach ($testi as $k => $v) {
        register_setting('af-settings', 'annfu_' . $k, array(
            'type' => 'string',
            'sanitize_callback' => 'wp_kses_post',
        ));
    }
}

/**
 * Auto-seleziona il template personalizzato in base all'ID dell'impresa
 * Intercetta il valore del template prima del salvataggio
 *
 * @param mixed $value Valore del template che sta per essere salvato
 * @param mixed $old_value Valore precedente
 * @return string Template corretto da salvare
 */
function annfu_auto_select_template($value, $old_value)
{
    // Verifica se siamo in un salvataggio del form admin e se l'ID impresa è cambiato
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress settings API
    if (!isset($_POST['annfu_onoranza_funebre_id'])) {
        return $value;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified by WordPress settings API
    $onoranzaId = sanitize_text_field(wp_unslash($_POST['annfu_onoranza_funebre_id']));
    $oldOnoranzaId = get_option('annfu_onoranza_funebre_id', '');

    // Se l'ID impresa non è cambiato, non fare nulla
    if ($onoranzaId === $oldOnoranzaId) {
        return $value;
    }

    // Prende il primo ID se ce ne sono più di uno separati da virgola
    $ids = array_map('trim', explode(',', $onoranzaId));
    $primoId = $ids[0];

    // Verifica se esiste un template personalizzato per questo ID
    if ($primoId && file_exists(ANNFU_PLUGIN_PATH . 'templates/' . $primoId . '/_annuncio.php')) {
        return $primoId;
    } elseif (array_intersect($ids, array_map('strval', ANNFU_GRUPPO_CONCORDIA)) && file_exists(ANNFU_PLUGIN_PATH . 'templates/concordia/_annuncio.php')) {
        return 'concordia';
    } elseif (array_intersect($ids, array_map('strval', ANNFU_PFA)) && file_exists(ANNFU_PLUGIN_PATH . 'templates/pfa/_annuncio.php')) {
        return 'pfa';
    }

    return 'default';
}
add_filter('pre_update_option_annfu_template', 'annfu_auto_select_template', 10, 2);

/**
 * Sanitizza il CSS personalizzato rimuovendo codice potenzialmente pericoloso
 *
 * @param string $css Il CSS da sanitizzare
 * @return string CSS sanitizzato
 */
function annfu_sanitize_css($css)
{
    if (empty($css)) {
        return '';
    }

    // Rimuove tag HTML
    $css = wp_strip_all_tags($css);

    // Rimuove javascript: e expression()
    $css = preg_replace('/javascript\s*:/i', '', $css);
    $css = preg_replace('/expression\s*\(/i', '', $css);
    $css = preg_replace('/behavior\s*:/i', '', $css);
    $css = preg_replace('/-moz-binding\s*:/i', '', $css);

    // Rimuove @import per prevenire caricamento di risorse esterne malevole
    $css = preg_replace('/@import/i', '', $css);

    return $css;
}

function annfu_get_options()
{
    return [
        //annunci - ricerca ///////////////////////////////////////////////////////////////////////////
        'id_bg_annfu_annunci_filter' => [
            'css' => '#annfu_annunci_filter .front, #annfu_annunci_filter .back',
            'property' => 'background-color',
            'default' => '#fafafa',
            'description' => 'Sfondo box'],
        'id_annfu_annunci_filter' => [
            'css' => '#annfu_annunci_filter .front, #annfu_annunci_filter .back',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore box'],
        'class_bg_annfu_filter_submit' => [
            'css' => '.annfu_filter_submit',
            'property' => 'background-color',
            'default' => '#dcdcdc',
            'description' => 'Sfondo pulsante'],
        'class_annfu_filter_submit' => [
            'css' => '.annfu_filter_submit',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore pulsante'],
        //annunci - elenco ////////////////////////////////////////////////////////////////////////////
        'id_border_annfu_annunci' => [
            'css' => '.annfu_annunci',
            'property' => 'border-color',
            'default' => '#f2f2f2',
            'description' => 'Bordo contenitore annunci'],
        'id_bg_annfu_annunci' => [
            'css' => '.annfu_annunci',
            'property' => 'background-color',
            'default' => '#fafafa',
            'description' => 'Sfondo contenitore annunci'],
        'class_border_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper',
            'property' => 'border-color',
            'default' => '#dcdcdc',
            'description' => 'Bordo annuncio'],
        'class_bg_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper',
            'property' => 'background-color',
            'default' => '#ffffff',
            'description' => 'Sfondo annuncio'],
        'class_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore testo annuncio'],
        'class_annfu_annunci_nominativo' => [
            'css' => 'h2.annfu_annunci_nominativo a',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore titolo annuncio'],
        'class_border_hover_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper:hover',
            'property' => 'border-color',
            'default' => '#4f5064',
            'description' => 'Bordo annuncio (hover)'],
        'class_bg_hover_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper:hover',
            'property' => 'background-color',
            'default' => '#4f5064',
            'description' => 'Sfondo annuncio (hover)'],
        'class_hover_annfu_annunci_wrapper' => [
            'css' => '.annfu_annunci_wrapper:hover',
            'property' => 'color',
            'default' => '#ffffff',
            'description' => 'Colore testo annuncio (hover)'],
        'class_hover_annfu_annunci_nominativo' => [
            'css' => '.annfu_annunci_wrapper:hover h2.annfu_annunci_nominativo a',
            'property' => 'color',
            'default' => '#ffffff',
            'description' => 'Colore titolo annuncio (hover)'],
        'class_bg_hover_annfu_add_cordoglio' => [
            'css' => '.annfu_annunci_wrapper:hover h2.annfu_add_cordoglio',
            'property' => 'background-color',
            'default' => '#ffffff',
            'description' => 'Sfondo aggiungi cordoglio'],
        'class_hover_annfu_add_cordoglio' => [
            'css' => '.annfu_annunci_wrapper:hover h2.annfu_add_cordoglio',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore aggiungi cordoglio'],
        //annuncio //////////////////////////////////////////////////////////////////////////////////
        'class_border_annfu_annuncio_wrapper' => [
            'css' => '.annfu_annuncio_wrapper',
            'property' => 'border-color',
            'default' => '#d2d2d2',
            'description' => 'Bordo annuncio'],
        'class_annfu_annuncio_wrapper' => [
            'css' => '.annfu_annuncio_wrapper',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore testo annuncio'],
        'class_h2_annfu_annuncio_wrapper' => [
            'css' => '.annfu_annuncio_wrapper h2',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore testo nominativo'],
        //annuncio - form cordoglio /////////////////////////////////////////////////////////////////
        'class_annfu_form_cordoglio_wrapper' => [
            'css' => '.annfu_form_cordoglio_wrapper',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore form cordoglio'],
        'class_h2_annfu_form_cordoglio_wrapper' => [
            'css' => '.annfu_form_cordoglio_wrapper h2',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore titolo form cordoglio'],
        'class_bg_annfu_invio' => [
            'css' => '.annfu_invio',
            'property' => 'background-color',
            'default' => '#dcdcdc',
            'description' => 'Sfondo pulsante'],
        'class_annfu_invio' => [
            'css' => '.annfu_invio',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore pulsante'],
        'class_bg_hover_annfu_invio' => [
            'css' => '.annfu_invio:hover',
            'property' => 'background-color',
            'default' => '#ffffff',
            'description' => 'Sfondo pulsante (hover)'],
        'class_hover_annfu_invio' => [
            'css' => '.annfu_invio:hover',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore pulsante (hover)'],
        //annuncio - cordogli ///////////////////////////////////////////////////////////////////////
        'class_annfu_cordoglio_intestazione' => [
            'css' => '.annfu_cordoglio_intestazione strong',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore nominativo cordoglio'],
        'class_annfu_data_cordoglio' => [
            'css' => '.annfu_data_cordoglio',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore data cordoglio'],
        'class_border_annfu_cordoglio_intestazione' => [
            'css' => '.annfu_cordoglio_intestazione',
            'property' => 'border-bottom-color',
            'default' => '#d2d2d2',
            'description' => 'Bordo cordoglio'],
        'class_annfu_cordoglio_testo' => [
            'css' => '.annfu_cordoglio_testo',
            'property' => 'color',
            'default' => '#000000',
            'description' => 'Colore testo cordoglio'],
    ];
}

function annfu_get_options_values()
{
    $values = [];
    $afOptions = annfu_get_options();
    foreach ($afOptions as $k => $v) {
        $values[$k] = !get_option($k) ? $v['default'] : get_option($k);
    }

    return $values;
}

function annfu_reset_options()
{
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('Non hai i permessi per eseguire questa azione.', 'annuncifunebri-onoranza'));
    }

    check_admin_referer('annfu_reset_options_action', '_wpnonce');

    if (isset($_GET['_reset']) && $_GET['_reset'] == '1') {
        $afOptions = annfu_get_options();
        if (is_array($afOptions)) {
            foreach ($afOptions as $k => $v) {
                delete_option($k);
            }
        }

        set_transient('annfu_reset_success', true, 30);
    }

    wp_safe_redirect( admin_url( 'admin.php?page=af-plugin&reset=success' ) );
    exit;
}

function annfu_fix_url($url)
{
    if (substr($url, 0, 2) == "//") {
        $url = "https:" . $url;
    }
    return $url;
}

function annfu_create_sitemap()
{
    $response = wp_remote_get(ANNFU_SITE_API . '/v2/annunci?limit=50&onoranza_funebre_id=' . get_option('annfu_onoranza_funebre_id'), ['sslverify' => false, 'timeout' => ANNFU_REMOTE_TIMEOUT]);
    $r = json_decode(wp_remote_retrieve_body($response), true);

    $sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\" xmlns:image=\"http://www.google.com/schemas/sitemap-image/1.1\">\n";
    $sitemap .= "<url><loc>" . esc_url(get_site_url()) . "</loc><changefreq>Daily</changefreq><priority>1.0</priority></url>\n";
    $sitemap .= "<url><loc>" . esc_url(get_site_url() . '/' . ANNFU_PAGE_ANNUNCI . "/") . "</loc><changefreq>Daily</changefreq><priority>1.0</priority></url>\n";
    if (isset($r['data'])) {
        foreach ($r['data'] as $annuncio) {
            $link = esc_url(get_site_url() . '/' . ANNFU_PAGE_ANNUNCIO . '/' . $annuncio['comune']['slug'] . '/' . $annuncio['slug'] . '/');
            $sitemap .= "<url>" .
                "<loc>" . $link . "</loc>" .
                "<lastmod>" . wp_date( "Y-m-d\TH:i:sP", strtotime( $annuncio['updatedAt'] ) ) . "</lastmod>" .
                "<image:image>".
                "<image:loc>" . esc_url($annuncio['foto']) . "</image:loc>" .
                "<image:title>Necrologio di " . esc_html($annuncio['nomeVisualizzato']) . "</image:title>" .
                "</image:image>" .
                "<changefreq>Weekly</changefreq>" .
                "<priority>0.5</priority>" .
                "</url>\n";
        }
    }
    $sitemap .= "</urlset>";

    global $wp_filesystem;
    if ( empty( $wp_filesystem ) ) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();
    }
    $wp_filesystem->put_contents( ABSPATH . 'sitemap_AF.xml', $sitemap, FS_CHMOD_FILE );
}

function annfu_cron_schedules($schedules)
{
    if (!isset($schedules["sitemapAF"])) {
        $schedules["sitemapAF"] = [
            'interval' => 24 * 60 * 60,
            'display' => __('Once every day', 'annuncifunebri-onoranza'),];
    }

    return $schedules;
}

function annfu_add_sitemap_to_robots($output, $public)
{
    if ($public) {
        $sitemap_url = get_site_url() . '/sitemap_AF.xml';
        $output .= "\nSitemap: " . $sitemap_url . "\n";
    }
    return $output;
}

function annfu_cron()
{
    wp_schedule_event(time(), 'sitemapAF', 'annfu_create_sitemap');
}

function annfu_plugin_activation()
{
    $testo = "*Attivato* plugin AF (" . ANNFU_VERSION . ") su " . get_site_url() . " (" . get_bloginfo('name') . " - ver." . get_bloginfo('version') . " " . get_bloginfo('admin_email') . ") #ID: " . get_option('annfu_onoranza_funebre_id', 'N/D');

    wp_remote_post(ANNFU_SITE_API . '/v2/wp-log', ['body' => ['testo' => $testo]]);
}

function annfu_plugin_deactivation()
{
    $testo = "*Disattivato* plugin AF (" . ANNFU_VERSION . ") su " . get_site_url() . " (" . get_bloginfo('name') . ") #ID: " . get_option('annfu_onoranza_funebre_id', 'N/D');

    wp_remote_post(ANNFU_SITE_API . '/v2/wp-log', ['body' => ['testo' => $testo]]);
}

function annfu_upgrade_completed($upgrader_object, $options)
{
    if ($options['action'] == 'update' && $options['type'] == 'plugin' && isset($options['plugins'])) {
        foreach ($options['plugins'] as $plugin) {
            if (strpos($plugin, 'annuncifunebri-onoranza')) {
                $testo = "*Aggiornato* plugin AF (" . ANNFU_VERSION . ") su " . get_site_url() . " (" . get_bloginfo('name') . " - ver." . get_bloginfo('version') . " " . get_bloginfo('admin_email') . ") #ID: " . get_option('annfu_onoranza_funebre_id', 'N/D');
                wp_remote_post(ANNFU_SITE_API . '/v2/wp-log', ['body' => ['testo' => $testo]]);
            }
        }
    }
}

function annfu_encryption_params()
{
    // AES-256-CBC richiede IV di 16 byte e chiave di 32 byte
    $ciphering = "AES-256-CBC";

    // Usa chiavi separate per il nuovo cipher per evitare conflitti con vecchi valori
    $encryptionIv = get_option('annfu_encryptioniv_aes');
    if (!$encryptionIv) {
        $encryptionIv = substr(hash('sha256', microtime() . wp_salt()), 0, 16);
        add_option('annfu_encryptioniv_aes', $encryptionIv);
    }
    $encryptionKey = get_option('annfu_encryptionkey_aes');
    if (!$encryptionKey) {
        $encryptionKey = substr(hash('sha256', php_uname() . wp_salt()), 0, 32);
        add_option('annfu_encryptionkey_aes', $encryptionKey);
    }

    return [
        'ciphering' => $ciphering,
        'options' => 0,
        'encryption_iv' => $encryptionIv,
        'encryption_key' => $encryptionKey
    ];
}

function annfu_encrypt($value)
{
    $params = annfu_encryption_params();
    $encrypted = openssl_encrypt($value, $params['ciphering'], $params['encryption_key'], $params['options'], $params['encryption_iv']);
    return base64_encode($encrypted);
}

function annfu_decrypt($value)
{
    $params = annfu_encryption_params();
    return openssl_decrypt(base64_decode($value), $params['ciphering'], $params['encryption_key'], $params['options'], $params['encryption_iv']);
}

function annfu_get_date_parameter($value)
{
    list($d, $m, $y) = explode('%2F', $value);

    return $y . '-' . $m . '-' . $d;
}
