<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link       -
 * @since      1.0.0
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Accordion_Md_Plugin
 * @subpackage Accordion_Md_Plugin/public
 * @author     Max Sternitzke <max.sternitzke@th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Addon_Patch{


    public function __construct() {


    }

    public function backendAdminCreate()
    {
        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        echo $twig->render('admin-backend/admin-backend-patch.html');
    }

    public function patchFile() 
    {
        global $wpdb;

        $option_name = TRAININGSSYSTEM_PLUGIN_DBUPDATE . "installed_patches";

        $current_user = wp_get_current_user();
        if (0 == $current_user->ID) {
            $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;
			echo $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
			//exit;
		} else {

            if (isset($_FILES['file']) &&
                $_FILES['file']['error'] == UPLOAD_ERR_OK &&
                is_uploaded_file($_FILES['file']['tmp_name'])) {

                $json = json_decode(file_get_contents($_FILES['file']['tmp_name']), true);

                if (json_last_error() === JSON_ERROR_NONE) {

                    if(isset($json['tables']) && isset($json['hash']) && strlen(trim($json['hash'])) == 16) {

                        $success = true;

                        $hash = $json['hash'];
                        $installed_patches = get_option($option_name, array());

                        foreach($json['tables'] as $tablename => $table_patch) {
                            foreach($table_patch as $method => $patch_data) {
                                switch($method) {
                                    case "replace":
                                        $i=0;
                                        foreach($patch_data as $replace_data) {
                                            if(isset($replace_data['column']) && trim($replace_data['column']) != "" &&
                                            isset($replace_data['old']) && trim($replace_data['old']) != "" &&
                                            isset($replace_data['new']) && trim($replace_data['new']) != "") {
                                                
                                                if(!isset($installed_patches[$hash.$tablename.$method.$i])) {

                                                    $installed_patches[$hash.$tablename.$method.$i] = date("Y-m-d H:i:s");
                                                    update_option($option_name, $installed_patches);
                                                    
                                                    $sql = "UPDATE `$wpdb->prefix$tablename` SET {$replace_data['column']} = REPLACE({$replace_data['column']}, %s, %s) WHERE {$replace_data['column']} LIKE '%%{$wpdb->esc_like($replace_data['old'])}%%' ";
                                                    if($tablename == "posts") {
                                                        $sql .= " AND post_status = 'publish'";
                                                    }
                                                    $prepared = $wpdb->prepare($sql, $replace_data['old'], $replace_data['new']);

                                                    $wpdb->query($prepared);

                                                }

                                            } else {
                                                echo "Ungültige Struktur des Replace-Arrays.";
                                                wp_die();
                                            }
                                            $i++;
                                        }
                                        break;
                                    default:
                                        $success = false;
                                        echo "Unbekannte Patch-Methode";
                                }
                            }
                        }

                        if($success)
                            echo "success";

                    } else {
                        echo "invalid data structure";
                    }
                }
            }
            wp_die();
        }
    }
}
