<?php
/**
 * Divi 5 Child Improved functions.
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Enqueue parent and child styles/scripts.
 */
function divi_5_child_improved_enqueue_assets() {
    $theme = wp_get_theme();
    $version = $theme ? $theme->get('Version') : '1.0.0';

    wp_enqueue_style(
        'divi-parent-style',
        get_template_directory_uri() . '/style.css',
        array(),
        defined('ET_CORE_VERSION') ? ET_CORE_VERSION : null
    );

    wp_enqueue_style(
        'divi-5-child-style',
        get_stylesheet_uri(),
        array('divi-parent-style'),
        $version
    );

    wp_enqueue_style(
        'divi-5-child-custom',
        get_stylesheet_directory_uri() . '/assets/css/custom.css',
        array('divi-5-child-style'),
        $version
    );

    wp_enqueue_script(
        'divi-5-child-custom-js',
        get_stylesheet_directory_uri() . '/assets/js/custom.js',
        array(),
        $version,
        true
    );
}
add_action('wp_enqueue_scripts', 'divi_5_child_improved_enqueue_assets', 20);

/**
 * Setup child theme translations.
 */
function divi_5_child_improved_setup() {
    load_child_theme_textdomain('divi-5-child-improved', get_stylesheet_directory() . '/languages');
}
add_action('after_setup_theme', 'divi_5_child_improved_setup');

/**
 * WooCommerce - sprememba napisa gumba "Dodaj v košarico" na izdelkih.
 *
 * Deluje za:
 * - single product WooCommerce gumb,
 * - shop/archive/product loop gumb,
 * - Divi WooCommerce modul fallback prek prevodov.
 */
function vd_je_napis_dodaj_v_kosarico($value) {

    if (!is_string($value) && !is_numeric($value)) {
        return false;
    }

    $value = trim((string) $value);

    if ('' === $value) {
        return false;
    }

    static $charset = null;

    if (null === $charset) {
        $charset = get_bloginfo('charset');
        $charset = $charset ? $charset : 'UTF-8';
    }

    $value = wp_strip_all_tags($value);
    $value = html_entity_decode($value, ENT_QUOTES, $charset);
    $value = trim(preg_replace('/\s+/', ' ', $value));

    if (function_exists('mb_strtolower')) {
        $value = mb_strtolower($value, $charset);
    } else {
        $value = strtolower($value);
    }

    $iskana_besedila = array(
        'add to cart',
        'add to basket',
        'dodaj v košarico',
        'dodaj v kosarico'
    );

    return in_array($value, $iskana_besedila, true);
}

function vd_spremeni_napis_dodaj_v_kosarico($text, $product = null) {

    if (is_admin() && !wp_doing_ajax()) {
        return $text;
    }

    if (vd_je_napis_dodaj_v_kosarico($text)) {
        return 'Dodaj na seznam';
    }

    return $text;
}
add_filter('woocommerce_product_single_add_to_cart_text', 'vd_spremeni_napis_dodaj_v_kosarico', 9999, 2);
add_filter('woocommerce_product_add_to_cart_text', 'vd_spremeni_napis_dodaj_v_kosarico', 9999, 2);

/**
 * WooCommerce/Divi - fallback za primere, ko modul besedilo izpiše prek prevodov.
 */
function vd_spremeni_napis_dodaj_v_kosarico_prevod($translation, $text, $domain) {

    if (is_admin() && !wp_doing_ajax()) {
        return $translation;
    }

    $dovoljene_domene = array(
        'woocommerce',
        'et_builder',
        'Divi',
        'divi-5-child-improved'
    );

    if (!in_array($domain, $dovoljene_domene, true)) {
        return $translation;
    }

    if (vd_je_napis_dodaj_v_kosarico($text) || vd_je_napis_dodaj_v_kosarico($translation)) {
        return 'Dodaj na seznam';
    }

    return $translation;
}
add_filter('gettext', 'vd_spremeni_napis_dodaj_v_kosarico_prevod', 9999, 3);

/**
 * WooCommerce - dodatni fallback za HTML gumba v loop/archive prikazih.
 */
function vd_spremeni_napis_dodaj_v_kosarico_html($html, $product = null, $args = array()) {

    if (!is_string($html) || '' === $html) {
        return $html;
    }

    $iskanje = array(
        'Add to cart',
        'Add to Cart',
        'ADD TO CART',
        'Add to basket',
        'Add to Basket',
        'Dodaj v košarico',
        'Dodaj v ko&#353;arico',
        'Dodaj v ko&scaron;arico',
        'Dodaj v kosarico'
    );

    return str_replace($iskanje, 'Dodaj na seznam', $html);
}
add_filter('woocommerce_loop_add_to_cart_link', 'vd_spremeni_napis_dodaj_v_kosarico_html', 9999, 3);

/**
 * WooCommerce - sprememba besedila gumba na blagajni.
 */
function vd_spremeni_gumb_narocilo() {
    return 'Naroči individualno ponudbo';
}
add_filter('woocommerce_order_button_text', 'vd_spremeni_gumb_narocilo', 9999);

/**
 * WooCommerce - sprememba besedila gumba "Nadaljuj na zaključek nakupa" v košarici.
 */
function vd_spremeni_gumb_nadaljuj_zakljucek_nakupa($translation, $text, $domain) {

    if (is_admin() && !wp_doing_ajax()) {
        return $translation;
    }

    $iskana_besedila = array(
        'Proceed to checkout',
        'Nadaljuj na zaključek nakupa',
        'Nadaljuj na zakljucek nakupa'
    );

    if (in_array($text, $iskana_besedila, true) || in_array($translation, $iskana_besedila, true)) {
        return 'Nadaljuj';
    }

    return $translation;
}
add_filter('gettext_woocommerce', 'vd_spremeni_gumb_nadaljuj_zakljucek_nakupa', 20, 3);

/**
 * WooCommerce - popravek barve in velikosti obvestila za napako kupona
 * v košarici in na blagajni, tudi pri shortcode [woocommerce_checkout].
 */
if (!function_exists('vd_woo_coupon_error_notice_css')) {
    function vd_woo_coupon_error_notice_css() {

        if (is_admin()) {
            return;
        }

        $css = '
/* WooCommerce - napaka kupona: barva in velikost */
body form.checkout_coupon,
body .checkout_coupon,
body form.woocommerce-form-coupon,
body .woocommerce-form-coupon,
body .coupon {
    --wc-red: #9bd650 !important;
}

body .coupon-error-notice,
body #coupon-error-notice,
body [id^="coupon-error-notice"],
body form.checkout_coupon .coupon-error-notice,
body form.checkout_coupon #coupon-error-notice,
body form.checkout_coupon [id^="coupon-error-notice"],
body .checkout_coupon .coupon-error-notice,
body .checkout_coupon #coupon-error-notice,
body .checkout_coupon [id^="coupon-error-notice"],
body form.woocommerce-form-coupon .coupon-error-notice,
body form.woocommerce-form-coupon #coupon-error-notice,
body form.woocommerce-form-coupon [id^="coupon-error-notice"],
body .woocommerce-form-coupon .coupon-error-notice,
body .woocommerce-form-coupon #coupon-error-notice,
body .woocommerce-form-coupon [id^="coupon-error-notice"],
body.woocommerce-checkout .coupon-error-notice,
body.woocommerce-checkout #coupon-error-notice,
body.woocommerce-checkout [id^="coupon-error-notice"],
body.woocommerce-cart .coupon-error-notice,
body.woocommerce-cart #coupon-error-notice,
body.woocommerce-cart [id^="coupon-error-notice"] {
    color: #9bd650 !important;
    font-size: 14px !important;
    line-height: 1.45 !important;
    font-weight: 500 !important;
    margin-top: 8px !important;
    margin-bottom: 0 !important;
    display: block !important;
    text-align: left !important;
}

body .coupon-error-notice *,
body #coupon-error-notice *,
body [id^="coupon-error-notice"] * {
    color: inherit !important;
    font-size: inherit !important;
    line-height: inherit !important;
}

body form.checkout_coupon .input-text.has-error,
body form.checkout_coupon input.has-error,
body .checkout_coupon .input-text.has-error,
body .checkout_coupon input.has-error,
body form.woocommerce-form-coupon .input-text.has-error,
body form.woocommerce-form-coupon input.has-error,
body .woocommerce-form-coupon .input-text.has-error,
body .woocommerce-form-coupon input.has-error,
body .coupon .input-text.has-error,
body .coupon input.has-error {
    border-color: #9bd650 !important;
    outline-color: #9bd650 !important;
    box-shadow: none !important;
}
';

        wp_register_style('vd-woo-coupon-error-notice-fix', false, array(), '1.0.0');
        wp_enqueue_style('vd-woo-coupon-error-notice-fix');
        wp_add_inline_style('vd-woo-coupon-error-notice-fix', $css);
    }

    add_action('wp_enqueue_scripts', 'vd_woo_coupon_error_notice_css', 9999);
}



/** Allow validated Divi portability JSON for site administrators. */
add_filter('upload_mimes', function ($mimes) {
    if (current_user_can('manage_options')) { $mimes['json'] = 'application/json'; }
    return $mimes;
});
add_filter('wp_check_filetype_and_ext', function ($result, $file, $filename) {
    if (!current_user_can('manage_options') || strtolower(pathinfo($filename, PATHINFO_EXTENSION)) !== 'json') { return $result; }
    $layout = json_decode(file_get_contents($file), true);
    if (is_array($layout) && isset($layout['context'], $layout['data']) && in_array($layout['context'], array('et_builder', 'et_builder_layouts'), true)) {
        $result['ext'] = 'json'; $result['type'] = 'application/json';
    }
    return $result;
}, 20, 3);


/** Temporary, administrator-only importer for the Breza Divi conversion. */
add_action('admin_menu', function () { add_management_page('Breza Divi uvoz', 'Breza Divi uvoz', 'manage_options', 'breza-divi-import', 'breza_divi_import_screen'); });
function breza_divi_import_screen() {
 if (!current_user_can('manage_options')) { return; }
 echo '<div class="wrap"><h1>Breza Divi uvoz</h1>';
 if (isset($_POST['breza_import'])) {
  check_admin_referer('breza_divi_import');
  $file = isset($_FILES['breza_file']['tmp_name']) ? $_FILES['breza_file']['tmp_name'] : '';
  $pages = $file && is_uploaded_file($file) ? json_decode(file_get_contents($file), true) : null;
  $allowed = array('domov','o-podjetju','ekipa','zgodovina','certifikati','zagan-les','les-za-terase-fasade','blog','kontakt','politika-zasebnosti','trajnostno-ogrevanje-z-lesnimi-sekanci-okolju-prijazna-pot-do-toplote');
  $valid = is_array($pages) && count($pages) <= count($allowed);
  foreach ((array) $pages as $p) { if (!is_array($p) || !isset($p['slug'], $p['title'], $p['content']) || !in_array($p['slug'], $allowed, true) || strpos($p['content'], '<!-- wp:divi/section ') === false) { $valid = false; } }
  if (!$valid) { echo '<div class="notice notice-error"><p>Neveljavna datoteka postavitev.</p></div>'; }
  else {
   echo '<div class="notice notice-success"><p>Posodobljene strani:</p><ul>';
   foreach ($pages as $p) {
    $type = isset($p['type']) && $p['type'] === 'post' ? 'post' : 'page';
    $old = get_page_by_path($p['slug'], OBJECT, $type);
    if ($old) { wp_save_post_revision($old->ID); }
    $post = array('post_title'=>$p['title'], 'post_name'=>$p['slug'], 'post_content'=>$p['content'], 'post_type'=>$type, 'post_status'=>$old ? $old->post_status : 'draft', 'comment_status'=>'closed', 'ping_status'=>'closed');
    if ($type === 'post') { $post['post_date']='2024-02-05 07:36:42'; $post['post_date_gmt']='2024-02-05 06:36:42'; }
                if ($old) { $post['ID'] = $old->ID; }
    $id = wp_insert_post(wp_slash($post), true);
    if (is_wp_error($id)) { echo '<li>'.esc_html($id->get_error_message()).'</li>'; continue; }
    foreach (array('_et_pb_use_builder'=>'on','_et_pb_built_for_post_type'=>$type,'_et_pb_page_layout'=>'et_full_width_page','_wp_page_template'=>'page-template-blank.php','_yoast_wpseo_title'=>$p['seo_title'],'_yoast_wpseo_metadesc'=>$p['description'],'_breza_divi_migrated'=>'1') as $key=>$value) { update_post_meta($id, $key, $value); }
    update_post_meta($id, '_et_pb_use_divi_5', 'on');
                update_post_meta($id, '_et_pb_show_page_creation', 'off');
                delete_post_meta($id, '_yoast_wpseo_meta-robots-noindex');
    echo '<li>'.esc_html($p['title']).' — ID '.intval($id).'</li>';
   }
   echo '</ul></div>';
  }
 }
 echo '<p>Posodobi samo 11 navedenih slovenskih postavitev. Obstoječi status objave ostane ohranjen.</p><form method="post" enctype="multipart/form-data">';
 wp_nonce_field('breza_divi_import');
 echo '<p><label for="breza_file">Datoteka postavitev JSON</label> <input id="breza_file" name="breza_file" type="file" accept=".json" required></p>';
 submit_button('Posodobi postavitve', 'primary', 'breza_import');
 echo '</form></div>';
}

/* Temporary save diagnostics, visible only to administrators, no request content. */
add_filter('rest_post_dispatch', function($response, $server, $request) {
 if ($request->get_route() !== '/divi/v1/sync-to-server' || !current_user_can('manage_options')) return $response;
 $data = $response->get_data();
 $info = array('method'=>$request->get_method(), 'route_exists'=>isset($server->get_routes()['/divi/v1/sync-to-server']), 'params'=>array_keys($request->get_params()), 'divi5'=>get_post_meta(310004, '_et_pb_use_divi_5', true), 'status'=>$response->get_status(), 'keys'=>is_array($data)?array_keys($data):gettype($data));
 foreach (array('code','message','success','error','save_verification','post_status') as $key) if (isset($data[$key])) $info[$key]=$data[$key];
 set_transient('breza_save_diagnostic', $info, 600);
 return $response;
}, 999, 3);
add_action('admin_notices', function() {
 if (current_user_can('manage_options') && ($info=get_transient('breza_save_diagnostic'))) echo '<div class="notice notice-info"><p>Breza save diagnostic: <code>'.esc_html(wp_json_encode($info)).'</code></p></div>';
});

add_action('wp_footer', function(){ if(!current_user_can('manage_options') || !isset($_GET['et_fb']))return; echo '<script>(function(){const original=window.fetch; window.fetch=function(input,options){const url=typeof input==="string"?input:input.url;const tracked=url&&url.includes("sync-to-server");if(tracked)console.info("BREZA_SAVE_REQUEST",JSON.stringify({url:url,method:options&&options.method,size:options&&typeof options.body==="string"?options.body.length:null}));return original.apply(this,arguments).then(function(response){if(tracked)console.info("BREZA_SAVE_RESPONSE",JSON.stringify({url:response.url,status:response.status,redirected:response.redirected}));return response;});};})();</script>'; }, 99);
