<?php

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

/*
 * human readable dump
 *
 */
if( ! function_exists('dd') ) {
    function dd( $what = '' ) {
        print '<pre class="ulz-dump">';
        print_r( $what );
        print '</pre>';
    }
}


/**
 * Add "Print receipt" link to Order Received page and View Order page
 */
if( ! function_exists('isa_woo_thankyou') ) {
/**
 * Add "Print receipt" link to Order Received page and View Order page
 */
function isa_woo_thankyou() {
    echo '<a href="javascript:window.print()" id="wc-print-button">Print receipt</a>';
}
add_action( 'woocommerce_thankyou', 'isa_woo_thankyou', 1);
add_action( 'woocommerce_view_order', 'isa_woo_thankyou', 8 );

}
/* Print Button Code End */


/*
 * shim for wp_body_open,
 * ensuring backward compatibility with versions of WordPress older than 5.2.
 *
 */
if( ! function_exists( 'wp_body_open' ) ) {
	function wp_body_open() {
		do_action( 'wp_body_open' );
	}
}

/*
 * define contstants
 *
 */
define( 'UTILLZ_THEME_VERSION', '2.4.0' );
define( 'UTILLZ_THEME_PATH', wp_normalize_path( get_template_directory() . DIRECTORY_SEPARATOR ) );
define( 'UTILLZ_THEME_URI', get_template_directory_uri() . '/' );


/*
* Show phone number field in edit account section if phone number enable 
*
*/
$enable_signup_phone = get_option('ulz_enable_signup_phone');
if( $enable_signup_phone ): 
// Display the mobile phone field
// add_action( 'woocommerce_edit_account_form_start', 'add_billing_phone_to_edit_account_form' ); // At start
add_action( 'woocommerce_edit_account_form', 'add_billing_phone_to_edit_account_form' ); // After existing fields
function add_billing_phone_to_edit_account_form() {
   $user = wp_get_current_user();
   ?>
    <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
       <label for="billing_phone"><?php _e( 'Mobile phone', 'woocommerce' ); ?> <span class="required">*</span></label>
       <input type="text" class="woocommerce-Input woocommerce-Input--phone input-text" name="billing_phone" id="billing_phone" value="<?php echo esc_attr( $user->billing_phone ); ?>" />
   </p>
   <?php
}

// Check and validate the mobile phone
add_action( 'woocommerce_save_account_details_errors','billing_phone_field_validation', 20, 1 );
function billing_phone_field_validation( $args ){
   if ( isset($_POST['billing_phone']) && empty($_POST['billing_phone']) )
       $args->add( 'error', __( 'Please fill in your Mobile phone', 'woocommerce' ),'');
}
// Save the mobile phone value to user data
add_action( 'woocommerce_save_account_details', 'my_account_saving_billing_phone', 20, 1 );
function my_account_saving_billing_phone( $user_id ) {
   if( isset($_POST['billing_phone']) && ! empty($_POST['billing_phone']) )
       update_user_meta( $user_id, 'billing_phone', sanitize_text_field($_POST['billing_phone']) );
}
endif;

/*
 * autoload
 *
 */
spl_autoload_register( function( $class_name ) {
    if ( strpos( $class_name, 'UtillzTheme' ) === false ) { return; }

    $file_parts = explode( '\\', $class_name );

    $namespace = '';
    for( $i = count( $file_parts ) - 1; $i > 0; $i-- ) {

        $current = strtolower( $file_parts[ $i ] );
        $current = str_ireplace( '_', '-', $current );

        if( count( $file_parts ) - 1 === $i ) {
            $file_name = "{$current}.php";
        }else{
            $namespace = '/' . $current . $namespace;
        }
    }

    $filepath  = trailingslashit( dirname( dirname( __FILE__ ) ) . $namespace );
    $filepath .= $file_name;

    if( file_exists( $filepath ) ) {
        include_once( $filepath );
    }else{
        wp_die( esc_html("The file attempting to be loaded at {$filepath} does not exist.") );
    }

});

function my_custom_script() {
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            // Get the two buttons by their IDs
            var socialLoginButton = $('#social_login_btn');
            var utillzLoginButton = $('#utillz_login_btn');

            // Attach a click event handler to the first button
            socialLoginButton.click(function() {
                // Set a timeout of 2 seconds (2000 milliseconds)
                setTimeout(function() {
                    // Trigger a click event on the second button after 2 seconds
                    utillzLoginButton.trigger('click');
                }, 2000);
            });
        });
    </script>
    <?php
}
add_action('wp_footer', 'my_custom_script');


/* Delete post with all files attached to it */
add_action( 'before_delete_post', 'ulz_remove_all_media_with_post', 10 );
function ulz_remove_all_media_with_post( $post_id ) {

    // Ensure this only runs for the custom post type 'rz_listing'
    if ( get_post_type( $post_id ) !== 'ulz_listing' ) {
        return;
    }

    // 1. Delete all attached media
    $attached_media = get_attached_media( '', $post_id );
    foreach ( $attached_media as $media ) {
        wp_delete_attachment( $media->ID, true );
    }

    // 2. Delete images embedded in the post content
    $post_content = get_post_field( 'post_content', $post_id );
    if ( ! empty( $post_content ) ) {
        preg_match_all( '/<img.*?src=[\'"](.*?)[\'"].*?>/', $post_content, $matches );
        if ( ! empty( $matches[1] ) ) {
            foreach ( $matches[1] as $url ) {
                $attachment_id = attachment_url_to_postid( $url );
                if ( $attachment_id ) {
                    wp_delete_attachment( $attachment_id, true );
                }
            }
        }
    }

    // 3. Delete images stored in the 'ulz_gallery' meta field
    $ulz_gallery = get_post_meta( $post_id, 'ulz_gallery', true );
    if ( ! empty( $ulz_gallery ) ) {
        $gallery_images = json_decode( $ulz_gallery, true );
        if ( is_array( $gallery_images ) ) {
            foreach ( $gallery_images as $image ) {
                if ( isset( $image['id'] ) ) {
                    wp_delete_attachment( $image['id'], true );
                }
            }
        }
    }
}
/* end delete post files attached */



/* add filedrag js file code*/

function enqueue_filedrag_js() {
    // Path to the JavaScript file in the theme's assets folder
    wp_enqueue_script(
        'filedrag-js', // Handle (a unique name for your script)
        get_template_directory_uri() . '/assets/src/scripts/filedrag.js', // URL to your script
        array(), // Dependencies (if any)
        null, // Version (set to null for auto versioning)
        true // Load in the footer (set to 'true' to load the script before the closing </body> tag)
    );
}
add_action('wp_enqueue_scripts', 'enqueue_filedrag_js');


// register utilities
include UTILLZ_THEME_PATH . 'inc/utils/utils.php';

function disable_inspect_element() {
    echo '<script>
        document.addEventListener("contextmenu", function (e) {
            e.preventDefault();
        });
 
        document.addEventListener("keydown", function (e) {
            if (e.key === "F12" || (e.ctrlKey && e.shiftKey && e.key === "I") || (e.ctrlKey && e.key === "U")) {
                e.preventDefault();
            }
        });
</script>';
}
add_action('wp_head', 'disable_inspect_element');




// init
UtillzTheme\Inc\Init::instance();