<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Add CSS class to hide admin notices if enabled
function sapmfly_hide_admin_notices(  $classes  ) {
    $enabled = get_option( 'sapmfly_disable_admin_notices', 'no' );
    if ( $enabled === 'yes' ) {
        $classes .= ' sapmfly-hide-notices';
    }
    return $classes;
}

add_filter( 'admin_body_class', 'sapmfly_hide_admin_notices' );
// Add dark mood feature in admin panel
add_action( 'admin_footer', 'sapmfly_add_admin_dark_mode_toggle' );
function sapmfly_add_admin_dark_mode_toggle() {
    if ( get_option( 'sapmfly_dark_mood_for_admin_button', 'no' ) !== 'yes' ) {
        return;
    }
    ?>
    <button id="sapmfly-admin-dark-toggle"><?php 
    esc_html_e( '🌙 Dark Mode', 'minifly' );
    ?></button>
<?php 
}

// Duplicate page and post feature
function sapmfly_duplicate_post_as_draft() {
    // Verify request
    if ( !isset( $_GET['post'] ) || !isset( $_GET['_wpnonce'] ) ) {
        wp_die( esc_html__( 'No post to duplicate has been supplied!', 'minifly' ) );
    }
    $post_id = absint( $_GET['post'] );
    if ( !current_user_can( 'edit_posts' ) ) {
        wp_die( esc_html__( 'You do not have permission to duplicate this post.', 'minifly' ) );
    }
    check_admin_referer( 'sapmfly_duplicate_post_' . $post_id );
    $post = get_post( $post_id );
    if ( !$post ) {
        wp_die( esc_html__( 'Post not found.', 'minifly' ) );
    }
    // Create the duplicate
    $new_post_args = [
        'post_title'    => $post->post_title . ' (Copy)',
        'post_content'  => $post->post_content,
        'post_status'   => $post->post_status,
        'post_type'     => $post->post_type,
        'post_author'   => get_current_user_id(),
        'post_excerpt'  => $post->post_excerpt,
        'post_parent'   => $post->post_parent,
        'post_password' => $post->post_password,
        'post_name'     => '',
    ];
    $new_post_id = wp_insert_post( $new_post_args );
    // Copy taxonomy terms
    $taxonomies = get_object_taxonomies( $post->post_type );
    foreach ( $taxonomies as $taxonomy ) {
        $terms = wp_get_object_terms( $post_id, $taxonomy, [
            'fields' => 'slugs',
        ] );
        wp_set_object_terms(
            $new_post_id,
            $terms,
            $taxonomy,
            false
        );
    }
    // Copy meta fields
    $post_meta = get_post_meta( $post_id );
    foreach ( $post_meta as $key => $values ) {
        foreach ( $values as $value ) {
            update_post_meta( $new_post_id, $key, maybe_unserialize( $value ) );
        }
    }
    // Redirect to edit page
    wp_safe_redirect( admin_url( 'post.php?action=edit&post=' . $new_post_id ) );
    exit;
}

add_action( 'admin_action_sapmfly_duplicate_post_as_draft', 'sapmfly_duplicate_post_as_draft' );
// Toggle options value and nonce verification
function sapmfly_duplicate_post_link(  $actions, $post  ) {
    if ( get_option( 'sapmfly_duplicate_enable', 'no' ) !== 'yes' ) {
        return $actions;
    }
    // Only for pages and posts
    if ( in_array( $post->post_type, ['post', 'page'] ) ) {
        $url = wp_nonce_url( admin_url( 'admin.php?action=sapmfly_duplicate_post_as_draft&post=' . $post->ID ), 'sapmfly_duplicate_post_' . $post->ID );
        $actions['sapmfly_duplicate'] = '<a href="' . esc_url( $url ) . '" title="' . esc_attr__( 'Duplicate this item', 'minifly' ) . '">' . esc_html__( 'Duplicate', 'minifly' ) . '</a>';
    }
    return $actions;
}

add_filter(
    'post_row_actions',
    'sapmfly_duplicate_post_link',
    10,
    2
);
add_filter(
    'page_row_actions',
    'sapmfly_duplicate_post_link',
    10,
    2
);
// Disable Gutenberg editor related hooks goes here
$sapmfly_disable_gutenberg_editor = get_option( 'sapmfly_disable_gutenberg' );
if ( $sapmfly_disable_gutenberg_editor == 'yes' ) {
    add_filter( 'use_block_editor_for_post_type', '__return_false', 100 );
    add_filter( 'use_block_editor_for_post', '__return_false', 100 );
}
// Block all external REST API requests if toggle is enabled
function sapmfly_block_external_rest_api_requests(  $access  ) {
    $disable_restapi = get_option( 'sapmfly_disable_call_restapi' );
    if ( $disable_restapi === 'yes' ) {
        // Allow REST API access for logged-in users
        if ( is_user_logged_in() ) {
            return $access;
        }
        // Block external requests
        return new WP_Error('rest_disabled', __( 'External REST API access has been disabled by site administrator.', 'minifly' ), array(
            'status' => 403,
        ));
    }
    return $access;
}

add_filter( 'rest_authentication_errors', 'sapmfly_block_external_rest_api_requests' );
// Hide toolbar on admin panel
add_action( 'admin_head', function () {
    $hide_admin_toolbar = get_option( 'sapmfly_hide_admin_toolbar', 'no' );
    if ( $hide_admin_toolbar === 'yes' ) {
        echo '<style>
            /* Hide entire admin toolbar */
            #wpadminbar { display: none !important; height: 0 !important; position: unset !important; }
            #wp-toolbar { display: none !important; height: 0 !important; position: unset !important; }
            #wpwrap { margin-top: -35px !important;}

        </style>';
    }
} );
// Add logout menu item in admin sidebar while toolbar hide
add_action( 'admin_menu', function () {
    $hide_admin_toolbar = get_option( 'sapmfly_hide_admin_toolbar', 'no' );
    if ( $hide_admin_toolbar === 'yes' ) {
        $logout_url = wp_logout_url();
        add_menu_page(
            __( 'Logout', 'minifly' ),
            __( 'Logout', 'minifly' ),
            'read',
            'logout',
            function () use($logout_url) {
                $logout_url = esc_url_raw( $logout_url );
                wp_safe_redirect( $logout_url );
                exit;
            },
            'dashicons-exit',
            999
        );
    }
} );
// SVG images upload related code
// Allow SVG upload if enabled
add_filter( 'upload_mimes', function ( $mimes ) {
    if ( get_option( 'sapmfly_enable_svg_images' ) === 'yes' ) {
        $mimes['svg'] = 'image/svg+xml';
    } else {
        unset($mimes['svg']);
    }
    return $mimes;
} );
// Basic SVG sanitization on upload
add_filter( 'wp_handle_upload_prefilter', function ( $file ) {
    if ( get_option( 'sapmfly_enable_svg_images' ) === 'yes' && $file['type'] === 'image/svg+xml' ) {
        $svg = file_get_contents( $file['tmp_name'] );
        // Strip script, iframe, and on* event handlers
        $svg = preg_replace( '/<script.*?<\\/script>/is', '', $svg );
        $svg = preg_replace( '/<iframe.*?<\\/iframe>/is', '', $svg );
        $svg = preg_replace( '/on\\w+="[^"]*"/i', '', $svg );
        $svg = preg_replace( '/on\\w+=\'[^\']*\'/i', '', $svg );
        // Overwrite file with sanitized version
        file_put_contents( $file['tmp_name'], $svg );
    }
    return $file;
} );
// Gravatar related code starts here
/**
 * Hide default Profile Picture row
 */
add_action( 'admin_head-profile.php', 'sapmfly_hide_default_profile_picture' );
add_action( 'admin_head-user-edit.php', 'sapmfly_hide_default_profile_picture' );
function sapmfly_hide_default_profile_picture() {
    if ( get_option( 'sapmfly_gravatar_img_change', 'no' ) === 'yes' ) {
        echo '<style>tr.user-profile-picture { display: none !important; }</style>';
    }
}

/**
 * Add custom Gravatar upload field
 */
add_action( 'show_user_profile', 'sapmfly_custom_gravatar_field' );
add_action( 'edit_user_profile', 'sapmfly_custom_gravatar_field' );
function sapmfly_custom_gravatar_field(  $user  ) {
    $toggle = get_option( 'sapmfly_gravatar_img_change' );
    if ( $toggle !== 'yes' ) {
        echo '<h3>' . esc_html__( 'Gravatar toggle not activated yet.', 'minifly' ) . '</h3>';
        return;
    }
    $custom_avatar = get_user_meta( $user->ID, 'sapmfly_custom_avatar', true );
    ?>
    <h3><?php 
    esc_html_e( 'Profile Picture', 'minifly' );
    ?></h3>
    <table class="form-table">
        <tr>
            <th><label><?php 
    esc_html_e( 'Custom Gravatar', 'minifly' );
    ?></label></th>
            <td>
                <div id="sapmfly-avatar-preview">
                    <?php 
    if ( $custom_avatar ) {
        ?>
                        <img src="<?php 
        echo esc_url( $custom_avatar );
        ?>" style="width:100px;height:100px;border-radius:50%;" />
                    <?php 
    } else {
        ?>
                        <p><?php 
        esc_html_e( 'No custom avatar selected.', 'minifly' );
        ?></p>
                    <?php 
    }
    ?>
                </div>
                <input type="hidden" name="sapmfly_custom_avatar" id="sapmfly_custom_avatar" value="<?php 
    echo esc_attr( $custom_avatar );
    ?>" />
                <button type="button" class="button button-primary" id="sapmfly-avatar-upload"><?php 
    esc_html_e( 'Change Gravatar', 'minifly' );
    ?></button>
            </td>
        </tr>
    </table>
    <?php 
}

/**
 * Save uploaded Gravatar
 */
add_action( 'personal_options_update', 'sapmfly_save_custom_gravatar' );
add_action( 'edit_user_profile_update', 'sapmfly_save_custom_gravatar' );
function sapmfly_save_custom_gravatar(  $user_id  ) {
    // Nonce verification
    if ( !isset( $_POST['sapmfly_custom_avatar_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sapmfly_custom_avatar_nonce'] ) ), 'sapmfly_custom_avatar_action' ) ) {
        return;
    }
    // Permission check
    if ( !current_user_can( 'edit_user', $user_id ) ) {
        return;
    }
    // Process field safely
    if ( isset( $_POST['sapmfly_custom_avatar'] ) ) {
        $avatar = esc_url_raw( wp_unslash( $_POST['sapmfly_custom_avatar'] ) );
        update_user_meta( $user_id, 'sapmfly_custom_avatar', $avatar );
    }
}

/**
 * Add Media Uploader
 */
add_action( 'admin_enqueue_scripts', function ( $hook ) {
    if ( 'profile.php' !== $hook && 'user-edit.php' !== $hook ) {
        return;
    }
    wp_enqueue_media();
    wp_add_inline_script( 'jquery-core', "\r\n        jQuery(document).ready(function(\$){\r\n            var frame;\r\n            \$('#sapmfly-avatar-upload').on('click', function(e){\r\n                e.preventDefault();\r\n                if(frame){ frame.open(); return; }\r\n                frame = wp.media({\r\n                    title: 'Select Avatar',\r\n                    button: { text: 'Use this image' },\r\n                    multiple: false\r\n                });\r\n                frame.on('select', function(){\r\n                    var attachment = frame.state().get('selection').first().toJSON();\r\n                    \$('#sapmfly_custom_avatar').val(attachment.url);\r\n                    \$('#sapmfly-avatar-preview').html('<img src=\"'+attachment.url+'\" style=\"width:100px;height:100px;border-radius:50%;\" />');\r\n                });\r\n                frame.open();\r\n            });\r\n        });\r\n    " );
} );
/**
 * Override get_avatar site-wide
 */
add_filter(
    'get_avatar',
    'sapmfly_custom_gravatar_display',
    10,
    6
);
function sapmfly_custom_gravatar_display(
    $avatar,
    $id_or_email,
    $size,
    $default,
    $alt,
    $args
) {
    if ( get_option( 'sapmfly_gravatar_img_change', 'no' ) !== 'yes' ) {
        return $avatar;
    }
    $user = false;
    if ( is_numeric( $id_or_email ) ) {
        $user = get_user_by( 'id', (int) $id_or_email );
    } elseif ( is_object( $id_or_email ) && !empty( $id_or_email->user_id ) ) {
        $user = get_user_by( 'id', (int) $id_or_email->user_id );
    } elseif ( is_email( $id_or_email ) ) {
        $user = get_user_by( 'email', $id_or_email );
    }
    if ( $user ) {
        $custom_avatar = get_user_meta( $user->ID, 'sapmfly_custom_avatar', true );
        if ( $custom_avatar ) {
            return sprintf(
                '<img alt="%s" src="%s" class="%s" height="%d" width="%d" />',
                esc_attr( $alt ),
                esc_url( $custom_avatar ),
                esc_attr( $args['class'] ),
                (int) $size,
                (int) $size
            );
        }
    }
    return $avatar;
}

// External links related code starts here
add_action( 'admin_init', function () {
    register_setting( 'reading', 'sapmfly_external_link', array(
        'sanitize_callback' => 'sapmfly_sanitize_external_link',
        'default'           => 'no',
    ) );
    add_settings_field(
        'sapmfly_external_link',
        esc_html__( 'Enable External Link Override', 'minifly' ),
        function () {
            $enabled = get_option( 'sapmfly_external_link', 'no' );
            ?>
        <label>
            <input type="checkbox" name="sapmfly_external_link" value="yes" <?php 
            checked( $enabled, 'yes' );
            ?>>
            <?php 
            esc_html_e( 'Allow posts/pages to use external URLs instead of permalinks', 'minifly' );
            ?>
        </label>
    <?php 
        },
        'reading'
    );
} );
// Add meta box in post/page edit panel
add_action( 'add_meta_boxes', function () {
    if ( get_option( 'sapmfly_external_link' ) === 'yes' ) {
        add_meta_box(
            'sapmfly_external_link_box',
            __( 'External URL', 'minifly' ),
            'sapmfly_external_link_box_callback',
            ['post', 'page'],
            'side',
            'high'
        );
    }
} );
function sapmfly_sanitize_external_link(  $value  ) {
    $value = sanitize_text_field( $value );
    if ( $value === 'yes' ) {
        return 'yes';
    }
    return 'no';
}

function sapmfly_external_link_box_callback(  $post  ) {
    $use_external = get_post_meta( $post->ID, '_sapmfly_use_external', true );
    $external_url = get_post_meta( $post->ID, '_sapmfly_external_url', true );
    wp_nonce_field( 'sapmfly_external_link_nonce', 'sapmfly_external_link_nonce' );
    ?>
    <p>
        <label>
            <input type="checkbox" id="sapmfly_use_external" name="sapmfly_use_external" value="yes" <?php 
    checked( $use_external, 'yes' );
    ?>>
            <?php 
    esc_html_e( 'Use External URL as Permalink', 'minifly' );
    ?>
        </label>
    </p>
    <p id="sapmfly_url_wrap" style="<?php 
    echo ( $use_external === 'yes' ? '' : 'display:none;' );
    ?>">
        <input type="url" class="widefat" name="sapmfly_external_url" placeholder="https://brainywp.com"
            value="<?php 
    echo esc_attr( $external_url );
    ?>">
    </p>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const toggle = document.getElementById('sapmfly_use_external');
            const urlWrap = document.getElementById('sapmfly_url_wrap');
            toggle.addEventListener('change', function() {
                urlWrap.style.display = this.checked ? '' : 'none';
            });
        });
    </script>
<?php 
}

// ========== SAVE META ==========
add_action( 'save_post', function ( $post_id ) {
    // Verify nonce
    if ( !isset( $_POST['sapmfly_external_link_nonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sapmfly_external_link_nonce'] ) ), 'sapmfly_external_link_nonce' ) ) {
        return;
    }
    // Prevent autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    // Sanitize checkbox/select value
    $use_external = ( isset( $_POST['sapmfly_use_external'] ) ? sanitize_text_field( wp_unslash( $_POST['sapmfly_use_external'] ) ) : '' );
    if ( $use_external === 'yes' ) {
        update_post_meta( $post_id, '_sapmfly_use_external', 'yes' );
        if ( !empty( $_POST['sapmfly_external_url'] ) ) {
            $external_url = esc_url_raw( wp_unslash( $_POST['sapmfly_external_url'] ) );
            update_post_meta( $post_id, '_sapmfly_external_url', $external_url );
        }
    } else {
        update_post_meta( $post_id, '_sapmfly_use_external', 'no' );
        delete_post_meta( $post_id, '_sapmfly_external_url' );
    }
} );
// Override permalink
add_filter(
    'post_type_link',
    function ( $permalink, $post ) {
        if ( get_option( 'sapmfly_external_link' ) !== 'yes' ) {
            return $permalink;
            // feature globally disabled
        }
        $use_external = get_post_meta( $post->ID, '_sapmfly_use_external', true );
        $external_url = get_post_meta( $post->ID, '_sapmfly_external_url', true );
        if ( $use_external === 'yes' && !empty( $external_url ) ) {
            return $external_url;
        }
        return $permalink;
    },
    10,
    2
);
// Redirect to external url on frontend redirection
add_action( 'template_redirect', function () {
    if ( get_option( 'sapmfly_external_link' ) !== 'yes' ) {
        return;
        // feature globally disabled
    }
    if ( is_singular() ) {
        global $post;
        $use_external = get_post_meta( $post->ID, '_sapmfly_use_external', true );
        $external_url = get_post_meta( $post->ID, '_sapmfly_external_url', true );
        if ( $use_external === 'yes' && !empty( $external_url ) ) {
            wp_safe_redirect( esc_url_raw( $external_url ), 301 );
            exit;
        }
    }
} );
//silence is golden
// Limit revision number for post and page
add_action( 'init', function () {
    if ( get_option( 'sapmfly_limit_revision_number', 'no' ) === 'yes' ) {
        if ( !defined( 'WP_POST_REVISIONS' ) ) {
            define( 'WP_POST_REVISIONS', 5 );
        }
    }
} );
/**
 * Enable Categories and Tags support to Pages
 */
function sapmfly_add_taxonomies_to_pages() {
    $enable_page_category_tag = get_option( 'sapmfly_enable_page_category_tag', 'no' );
    // Stop if option is disabled
    if ( 'yes' !== $enable_page_category_tag ) {
        return;
    }
    // Add Categories to Pages
    register_taxonomy_for_object_type( 'category', 'page' );
    // Add Tags to Pages
    register_taxonomy_for_object_type( 'post_tag', 'page' );
}

add_action( 'init', 'sapmfly_add_taxonomies_to_pages' );