<?php
/** ==============================================
 * In this custom redirections module, we store the old
 * links and new links to allow user find same information 
 * even if has old link.
*====================================================*/

function create_redirections_post_type() {
    $labels = array(
        'name' => 'Redirections',
        'singular_name' => 'Redirection',
        'menu_name' => 'Redirections',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Redirection',
        'edit_item' => 'Edit Redirection',
        'new_item' => 'New Redirection',
        'view_item' => 'View Redirection',
        'search_items' => 'Search Redirections',
        'not_found' => 'No redirections found',
        'not_found_in_trash' => 'No redirections found in Trash',
        'parent_item_colon' => '',
        'all_items' => 'All Redirections',
        'archives' => 'Redirection Archives',
        'insert_into_item' => 'Insert into redirection',
        'uploaded_to_this_item' => 'Uploaded to this redirection',
        'filter_items_list' => 'Filter redirections list',
        'items_list_navigation' => 'Redirections list navigation',
        'items_list' => 'Redirections list',
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => false,
        'show_in_nav_menus' => false,
        'capability_type' => 'post',
        'hierarchical' => false,
        'supports' => false,
        'has_archive' => false,
        'rewrite' => false, // Disable rewriting
        'menu_position' => 20,
        'menu_icon' => 'dashicons-randomize', 
    );

    register_post_type('redirection', $args);
}

add_action('init', 'create_redirections_post_type');
add_action('add_meta_boxes_redirections', 'add_custom_meta_boxes_redirections');
add_action('template_redirect', 'custom_redirection_logic');


//Add Custom Meta Boxes on directory - link DETAILS
function add_custom_meta_boxes_redirections() {
    add_meta_box('redirects', 'Redirect', 'render_custom_meta_box_redirections', 'redirection', 'normal', 'high');
}

// Render custom meta boxes
function render_custom_meta_box_redirections($post) {
    // Get existing values
	$post_id    = $post->ID;
    $old_link   = get_post_meta($post->ID, '_old_url', true);
    $new_link      = get_post_meta($post->ID, '_new_url', true);

    // Output fields
    ?>
    <div class="row">
        <div class="col-md-6 mb-3" style="width: 100%; margin-bottom:10px;">
            <label for="old"><b>Old URL </b></label><br/>
            <input type="text" id="old" name="old_url" style="width: 90%;" value="<?= esc_attr($old_link); ?>" placeholder="Enter full old website link ">
        </div>
        <div class="col-md-6 mb-3" style="width: 100%; margin-bottom:10px;">
            <label for="new" class="form-label"><b>New URL</b></label><br/>
            <input type="text" id="new" name="new_url" style="width: 90%;" value="<?= esc_attr($new_link); ?>" placeholder="Enter full new website link ">
        </div>
    </div>
    <?php
}

// Save custom meta box data
function save_custom_meta_box_redirections($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Save custom fields
    // Define an array of field names
    $fields = array('old_url', 'new_url');
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
        }
    }
}

add_action('add_meta_boxes_redirection', 'add_custom_meta_boxes_redirections');
add_action('save_post', 'save_custom_meta_box_redirections');


function custom_redirection_logic() {
    if (is_singular('redirection')) {
        // Get the custom fields for old link and new link
        $old_link = get_post_meta(get_the_ID(), '_old_url', true);
        $new_link = get_post_meta(get_the_ID(), '_new_url', true);

        if ($old_link && $new_link && is_string($old_link) && is_string($new_link)) {
            wp_redirect($new_link, 301); // Perform permanent redirect
            exit();
        }
    }
}

add_action('template_redirect', 'custom_redirection_logic');

