<?php
/**
 * Plugin Name: Fusio Multilingual
 * Description: Developed by Fusio
 * Version: 2.0
 * Author: Tony O' Hare
 * Author URI: http://www.fusio.net
 */

/**INCLUDES**/
require_once(dirname(__FILE__) . "/walkers/admin/admin-ml.php");
require_once(dirname(__FILE__) . "/walkers/site/site-ml.php");

/**ACTIONS**/
add_action("admin_init", "addIrishAttachmentForm");
add_action("add_meta_boxes", "registerMetaBoxes");
add_action("category_add_form_fields", "addMetaBoxesForAddingCategories", 10, 2);
add_action("category_edit_form_fields", "addMetaBoxesForEditingCategories", 10, 2);
add_action("create_category", "saveMetaBoxesForCategory", 10, 2);
add_action("edit_attachment", "saveIrishAttachmentForm");
add_action("edited_category", "saveMetaBoxesForCategory", 10, 2);
add_action("init", "configureRewriteRules");
add_action('template_redirect', 'prefix_url_rewrite_templates');
add_action("init", "registerViewDirectory");
add_action("save_post", "saveTheIrishForm");
add_action("wp_update_nav_menu_item", "saveNavMenuMeta");
remove_action("template_redirect","redirect_canonical");

/**FILTERS**/
add_filter("wp_setup_nav_menu_item", "createCustomNavMenuItem");
add_filter("the_content", "translateContent");
add_filter('post_type_link', 'translatePermalink',10,2);
add_filter('attachment_link', 'attachmentPermalink');
add_filter("post_link", "translatePostLink", 10, 3);
add_filter('page_link', 'translatePageLink', 10, 3);
add_filter("the_title", "translateTitle", 10, 2);
add_filter('single_cat_title', 'translateCategory', 10, 2);
//add_filter('wp_edit_nav_menu_walker', 'setTheMenuAdminToLoadTheCustomWalker', 10, 2);
/**CONFIGURATION FUNCTIONS**/
function configureRewriteRules() {
    add_rewrite_tag('%event_slug%', '([^&]+)');
    add_rewrite_rule('^ga/event/([^/]*)/register/?', 'index.php?post_type=event&event_slug=$matches[1]&language=irish', 'top');
    add_rewrite_tag('%language%', '([^&]+)');

	add_rewrite_rule('^ga/staff/([^/]+)(?:/([0-9]+))?/?$', 'index.php?staff=$matches[1]&page=$matches[2]&language=irish', 'top');
	add_rewrite_rule('^ga/post-primary/search-a-z/(.+?)(?:/([0-9]+))?/?$', 'index.php?search-a-z=$matches[1]&page=$matches[2]&language=irish', 'top');
	add_rewrite_rule('^ga/post-primary/circulars/([^/]+)(?:/([0-9]+))?/?$', 'index.php?circulars=$matches[1]&page=$matches[2]&language=irish', 'top');
	add_rewrite_rule('^ga/post-primary/guidelines/([^/]+)(?:/([0-9]+))?/?$', 'index.php?guidelines=$matches[1]&page=$matches[2]&language=irish', 'top');
    add_rewrite_rule('^ga/(.?.+?)/page/?([0-9]{1,})/?$', 'index.php?pagename=$matches[1]&language=irish&paged=$matches[2]', 'top');
    add_rewrite_rule('^ga/(.*)/(.*)/(.*)/?', 'index.php?pagename=$matches[3]&language=irish', 'top');
    add_rewrite_rule('^ga/(.*)/(.*)/?', 'index.php?pagename=$matches[2]&language=irish', 'top');
    add_rewrite_rule('^ga/(.*)/?', 'index.php?pagename=$matches[1]&language=irish', 'top');
    add_rewrite_rule('^ga/([^/]*)/?', 'index.php?name=$matches[1]&language=irish', 'top');
}

function prefix_url_rewrite_templates()
{
    if (get_query_var('event_slug')) {
        add_filter('template_include', function () {
            return get_template_directory() . '/event-register-form.php';
        });
    }
}

/**FUNCTIONS**/
/**
 * Change the admin menu for menus to include Your Languages
 * @param $walker
 * @param $menu_id
 *
 * @return string
 */
function setTheMenuAdminToLoadTheCustomWalker($walker, $menu_id) {
    return 'Walker_Nav_Menu_Edit_Custom';
}

/**
 * Filter the category title to load the correct language
 * Functions:
 *  http://codex.wordpress.org/Function_Reference/get_query_var
 *  http://codex.wordpress.org/Function_Reference/get_post_meta
 * @param $title
 * @return string
 */
function translateCategory($title) {
    $lang = get_query_var('language');
    $term = get_term_by('name', $title, 'category');
    $termID = $term->term_id;
    $irishTitle = get_option('taxonomy_' . $termID)['irish-title'];

    return ('irish' == $lang && strlen($irishTitle) > 2) ? $irishTitle : $title;
}

/**
 * Filter the title to load the correct language
 * Functions:
 *  http://codex.wordpress.org/Function_Reference/get_query_var
 *  http://codex.wordpress.org/Function_Reference/get_post_meta
 * @param $title
 * @return string
 */
function translateTitle($title, $id = null)
{
    $lang = get_query_var('language');


    if ("irish" == $lang) {
        $irish_title = get_post_meta($id, "irishtitle", TRUE);
        $title = (strlen($irish_title) > 1) ? $irish_title : $title;
    }
    
    return $title;
}

/**
 * Filter the content to load the correct language
 * Functions:
 *  http://codex.wordpress.org/Function_Reference/get_query_var
 *  http://codex.wordpress.org/Function_Reference/do_shortcode
 *  http://codex.wordpress.org/Function_Reference/wpautop
 *
 * @param $content
 * @return string
 */
function translateContent($content) {
    $lang = get_query_var("language");

    if(!empty($GLOBALS["post"])) {
        $id = $GLOBALS["post"] -> ID;
    } else {
        return $content;
    }

    if("irish" == $lang) {
        $irishContent = do_shortcode(get_post_meta($id, "irishcontent", true));
        $irishContent = wpautop($irishContent);

        $content = (strlen($irishContent) > 1) ? $irishContent : $content;
    }

    return $content;

}

function translatePostLink($url, $post) {
    $lang = get_query_var('language');

    $domain = $_SERVER["HTTP_HOST"];

    if ($post->post_type != 'attachment') {
        if ("irish" == $lang) {
            $url = str_replace("//$domain/", "//$domain/ga/", $url);
        }
    }

    return $url;
}

function translatePageLink($url) {
    $lang = get_query_var('language');
    $domain = $_SERVER["HTTP_HOST"];

    if ("irish" == $lang) {
        $url = str_replace("//$domain/", "//$domain/ga/", $url);
    }

    return $url;
}
/**
 * Filter the permalink to insert the language code
 * Functions:
 *  http://codex.wordpress.org/Function_Reference/get_query_var
 * @param $url
 *
 * @return mixed
 */
function translatePermalink($url, $post = false) {
    $lang = get_query_var("language");
    $domain = $_SERVER["HTTP_HOST"];

    if(!$post) {
        if("irish" == $lang) {
            return str_replace("//$domain/", "//$domain/ga/", $url);
        }
    }

    if($post -> post_type != "attachment") {
        if("irish" == $lang) {
            $url = str_replace("//$domain/", "//$domain/", $url);
        }
    }

    return $url;
}

function attachmentPermalink($url) {
    return str_replace("/ga/", "/", $url);
}

function addCustomPageVariables($public_query_vars) {
    $public_query_vars[] = "language";

    return $public_query_vars;
}

function addMetaBoxesForAddingCategories() {
    Waiter::plates()->serve("ml::addCategory", []);
}

/**
 * @param $term
 */
function addMetaBoxesForEditingCategories($term) {
    $termId = $term -> term_id;
    $irishTitle = get_term_meta($termId, "irishTitle", true);

    Waiter::plates()->serve("ml::editCategory", compact("irishTitle"));
}

/**
 * @param $termID
 */
function saveMetaBoxesForCategory($termID) {
    $irishTitle = $_POST["irishTitle"] ?? "";
    update_term_meta($termID, "irishTitle", $irishTitle);
}


/**
 * Make views in this plugin available
 */
function registerViewDirectory() {
    $viewPath = dirname(__DIR__) . "/fusio-multilingual/views";
    Waiter::plates()->registerViewsFromFolder("ml", $viewPath);
}

/**
 * TODO: Find out what the post types are
 */
function registerMetaBoxes() {
    foreach ( get_post_types( '', 'names' ) as $postType ) {
        add_meta_box("irish-content", "Irish Version", "showIrishForm", $postType, "normal", "high");
    }
}

/**
 * Show the form on post types that allow it
 */
function showIrishForm() {
    global $post;

    $irishTitle = get_post_meta($post -> ID, 'irishTitle', true);
    $irishContent = get_post_meta($post -> ID, 'irishContent', true);

    Waiter::plates()->serve("ml::irishForm", compact('irishTitle', 'irishContent'));
}

/**
 * Save post meta
 */
function saveTheIrishForm() {
    global $post;
    $irishTitle = $_POST["irishtitle"] ?? "";
    $irishContent = $_POST["irishContent"] ?? "";

	if ($post) {
    update_post_meta($post -> ID, "irishTitle", $irishTitle ?? "");
    update_post_meta($post -> ID, "irishContent", $irishContent ?? "");
	}
}

/**
 * Add a ML form for Attachment
 */
function addIrishAttachmentForm() {
    add_meta_box("custom-attachment-meta-box", "Irish Translation", "showIrishAttachmentForm", "attachment", "normal", "low");
}

/**
 * Show the ML form for attachments
 */
function showIrishAttachmentForm() {
    global $post;
    $irishCaption = get_post_meta($post -> ID, "irishCaption", 1);
    Waiter::plates()->serve("ml:attachmentForm", compact("irishCaption"));
}

/**
 * Save the ML form for attachments
 */
function saveIrishAttachmentForm() {
    global $post;
    $irishCaption = $_POST["irishCaption"] ?? "";
    update_post_meta($post -> ID, "irishCaption", $irishCaption);
}

/**
 * I'm not actually sure if this is used but I'm scared to remove it
 * @param $menuItem
 * @return mixed
 */
function createCustomNavMenuItem($menuItem) {
    $menuItem -> custom = get_post_meta($menuItem -> ID, "_menu_item_irish", true);
    return $menuItem;
}

/**
 * @param $menuID
 * @param $menuItemDBID
 * @param $args
 */
function saveNavMenuMeta($menuID, $menuItemDBID = 0, $args = []) {
    if(is_array($_REQUEST["menu-item-irish"])) {
        $customValue = $_REQUEST["menu-item-irish"][$menu_item_db_id];
        update_post_meta($menu_item_db_id, '_menu_item_irish', $customValue);
    }

    if (is_array($_REQUEST['menu-item-accesskey'])) {
        $customValue = $_REQUEST['menu-item-accesskey'][$menu_item_db_id];
        update_post_meta($menu_item_db_id, '_menu_item_accesskey', $customValue);
    }
}

/**
 * Generate the language switcher url
 * @param  [String] $url [The source URL]
 * @return [String]      [The transated URL]
 */
function generateLanguageSwitcherUrl($url)
{
    if (is_home()) {
        $url = $url . '/';
    }

    $language = get_query_var("language");
    $site_url = get_home_url() . '/';
    $new_url = $site_url . "ga/";

    $replace_url = ("irish" == $language) ? str_replace($new_url, $site_url, $url) : str_replace($site_url, $new_url, $url);
    return $replace_url;
}

/**
 * Determine the correct URL based on the language
 * @param  [String] $url [The source URL]
 * @return [String]      [The transated URL]
 */
function generateCorrectCrl($url)
{
    $language = get_query_var("language");

    $site_url = get_site_url();
    $new_url = $site_url . "/ga";

    $replace_url = ("irish" == $language) ? str_replace($site_url, $new_url, $url) : $url;

    return $replace_url;
}