<?php

class Af2AjaxImport {

    private $Admin = null;

    function __construct($Admin) {
        $this->Admin = $Admin;
    }

    private function add_custom_post_type_to_export($post_type) {
        require_once AF2_MISC_FUNCTIONS_PATH;

        $json_array = array();
        $img_ref = array();

        $posts = $this->Admin->af2_get_posts($post_type);

        foreach($posts as $post) {
            $post_content_ = get_post_field('post_content', $post );
            $post_content = unserialize(urldecode($post_content_));

            if($post_type == FRAGE_POST_TYPE) {
                if($post_content['typ'] == 'af2_select' || $post_content['typ'] == 'af2_multiselect') {
                    $i = 0;
                    if(isset($post_content['answers'])) {
                        foreach( $post_content['answers'] as $answer ) {
                            if(af2_str_contains($answer['img'], 'http')) {
                                if(!in_array($answer['img'], $img_ref)) array_push($img_ref, $answer['img']);
                            }
                            $i++;
                        }
                    }
                }
                else if($post_content['typ'] == 'af2_slider') {
                    if(isset($post_content['slider_image'])) {
                        if(af2_str_contains($post_content['slider_image'], 'http')) {
                            if(!in_array($post_content['slider_image'], $img_ref)) array_push($img_ref, $post_content['slider_image']);
                        }
                    }
                }
            }
            if($post_type == KONTAKTFORMULAR_POST_TYPE) {
                if(isset($post_content['attachment_url'])) {
                    if(af2_str_contains($post_content['attachment_url'], 'http')) {
                        if(!in_array($post_content['attachment_url'], $img_ref)) array_push($img_ref, $post_content['attachment_url']);
                    }
                }
            }
            if($post_type == FORMULAR_POST_TYPE) {
                if(isset($post_content['success_image'])) {
                    if(af2_str_contains($post_content['success_image'], 'http')) {
                        if(!af2_str_contains($post_content['success_image'], 'res/images/success_standard')) {
                            if(!in_array($post_content['success_image'], $img_ref)) array_push($img_ref, $post_content['success_image']);
                        }
                    }
                }
            }

            $json = new stdClass();
            $json->post_content = $post_content_;
            $json->id = get_post_field('ID', $post);
            $json->post_type = get_post_field('post_type', $post);

            array_push($json_array, $json);
        }

        return ['json' => $json_array, 'img' => $img_ref];
    }

    public function af2_export() {
        require_once AF2_MISC_FUNCTIONS_PATH;
        if (extension_loaded('zip')) {
    
            /** Create Archive **/
            $zip = new ZipArchive;
            $upload_dir = wp_upload_dir();
            $base_dir = $upload_dir['basedir'];
            $imp_exp_file_path = $base_dir . '/af2_imports_exports/';
            $imp_exp_json_file = $imp_exp_file_path . 'af2_export.txt'; // Export JSON File
            $zip_file_name = 'af2_export-' . md5(microtime()) . '.zip'; // Name of Zip File
            $imp_exp_file_name = $imp_exp_file_path . $zip_file_name; // Zip File Path Basedir
            $imp_exp_file_url = $upload_dir['baseurl'] . '/af2_imports_exports/' . $zip_file_name; // Zip File Path Uploaddir
            $json_array = array();
            $img_array = array();


            $add = $this->add_custom_post_type_to_export(FRAGE_POST_TYPE);
            $json_array = array_merge($add['json'], $json_array);
            $img_array = array_merge($add['img'], $img_array);

            $add = $this->add_custom_post_type_to_export(KONTAKTFORMULAR_POST_TYPE);
            $json_array = array_merge($add['json'], $json_array);
            $img_array = array_merge($add['img'], $img_array);

            $add = $this->add_custom_post_type_to_export(FORMULAR_POST_TYPE);
            $json_array = array_merge($add['json'], $json_array);
            $img_array = array_merge($add['img'], $img_array);
    
            if (!file_exists($imp_exp_file_path)) {
                try {
                    mkdir($imp_exp_file_path);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            }
    
            $toJSON = urlencode(serialize($json_array));

            $fp = fopen($imp_exp_json_file, 'w');
            fwrite($fp, $toJSON);
            fclose($fp);
    
            if (true === $zip->open($imp_exp_file_name, ZipArchive::CREATE)) {
                $zip->addFile($imp_exp_json_file, 'af2_export.txt');
    
                if ($zip->addEmptyDir('images')) {
                    foreach ($img_array as $image) {
                        $img_name = explode('/', $image);
                        $img_path = $base_dir;
                        
                        $upload = false;
                        foreach($img_name as $path_part) {
                            if($upload) $img_path .= '/'.$path_part;
                            if($path_part == 'uploads') $upload = true;
                        }

                        $img_name = end($img_name);
                        $zip->addFile($img_path, 'images/' . $img_name);
                    }
                }
    
                $zip->close();
    
                $return = array (
                    'type' => 'success',
                    'file' => $imp_exp_file_url,
                );
    
                echo json_encode($return);
                unlink($imp_exp_json_file);
            } else {
                echo 'failed';
            }
        } else {
            echo 'ZIP Archive extension not found!';
        }
    
        wp_die();
    }

    function af2_import() {
        require_once AF2_MISC_FUNCTIONS_PATH;
        if (extension_loaded('zip')) {
            $zip = new ZipArchive;
            $upload_dir = wp_upload_dir();
            $base_dir = $upload_dir['basedir'];
            $imp_exp_tmp_path = $base_dir . '/af2_import_export_tmp/';
            $import_data = $_FILES['af2_import_data'];
            $zip_file_name = $imp_exp_tmp_path . $import_data['name'];
    
            if (!file_exists($imp_exp_tmp_path)) {
                try {
                    mkdir($imp_exp_tmp_path);
                } catch (Exception $e) {
                    $return = [
                        'type' => 'error',
                        'msg' => $e->getMessage(),
                    ];
    
                    echo json_encode($return);
                    wp_die();
                }
            }
    
            try {
                move_uploaded_file($import_data['tmp_name'], $zip_file_name);
                $res = $zip->open($zip_file_name);
    
                if (true === $res) {
                    $zip->extractTo($imp_exp_tmp_path);
                    $zip->close();
    
                    $jsonFile = file_get_contents($imp_exp_tmp_path . 'af2_export.txt');
                    $image_files = $imp_exp_tmp_path . 'images';
                    unlink($imp_exp_tmp_path . 'af2_export.txt'); // Get rid of the file now.
    
                    if ($jsonFile) {
                        $toImport = unserialize(urldecode($jsonFile));
    
                        if (is_array($toImport) && !empty($toImport)) {
    
                            $img_links = array();

                            // Move files to the latest media folder.
                            if (is_dir($image_files)) {
                                if ($dh = opendir($image_files)) {
    
                                    while (( $file = readdir($dh) ) !== false) {
                                        if ($file != '.' && $file != '..') {
                                            $full_img_path = $image_files . '/' . $file;
                                            $new_file_path = $upload_dir['path'] . '/' . $file;

    
                                            if (rename($full_img_path, $new_file_path)) {
                                                $new_file_mime = mime_content_type($new_file_path);
                                                $upload_id = wp_insert_attachment(array(
                                                    'guid' => $new_file_path,
                                                    'post_mime_type' => $new_file_mime,
                                                    'post_title' => preg_replace('/\.[^.]+$/', '', $file),
                                                    'post_content' => '',
                                                    'post_status' => 'inherit'
                                                        ), $new_file_path);


                                                array_push($img_links, array('old_path' => $file, 'new_path' => $upload_id));
    
                                                require_once( ABSPATH . 'wp-admin/includes/image.php' );
    
                                                wp_update_attachment_metadata($upload_id, wp_generate_attachment_metadata($upload_id, $new_file_path));
                                            }
                                        }
                                    }
                                    closedir($dh);
                                }
    
                                unlink($image_files);
                            }

                            $import_data_ids = array();
                            $import_data_form_ids = array();
    
                            // Insert data to database.
                            foreach ($toImport as $data) {
                                $data->post_content = unserialize(urldecode($data->post_content));
                                if($data->post_type == FRAGE_POST_TYPE) {
                                    $i = 0;
                                    if(isset($data->post_content['answers'])) {
                                        foreach($data->post_content['answers'] as $answer) {
                                            if(af2_str_contains($answer['img'], 'http')) {
                                                $img_name = explode('/', $answer['img']);
                                                $img_name = end($img_name);
    
                                                foreach($img_links as $link) {
                                                    if($link['old_path'] == $img_name) {
                                                        $data->post_content['answers'][$i]['img'] = wp_get_attachment_url( $link['new_path'] );
                                                    }
                                                }
    
                                            }
                                            $i++;
                                        }
                                    }
                                    if(isset($data->post_content['slider_image'])) {
                                        if(af2_str_contains($data->post_content['slider_image'], 'http')) {
                                            $img_name = explode('/', $data->post_content['slider_image']);
                                            $img_name = end($img_name);

                                            foreach($img_links as $link) {
                                                if($link['old_path'] == $img_name) {
                                                    $data->post_content['slider_image'] = wp_get_attachment_url( $link['new_path'] );
                                                }
                                            }

                                        }
                                    }
                                }
                                if($data->post_type == KONTAKTFORMULAR_POST_TYPE) {
                                    if(isset($data->post_content['attachment_url'])) {
                                        if(af2_str_contains($data->post_content['attachment_url'], 'http')) {
                                            $img_name = explode('/', $data->post_content['attachment_url']);
                                            $img_name = end($img_name);

                                            foreach($img_links as $link) {
                                                if($link['old_path'] == $img_name) {
                                                    $data->post_content['attachment_url'] = wp_get_attachment_url( $link['new_path'] );
                                                }
                                            }
                                        }
                                    }
                                }
                                if($data->post_type == FORMULAR_POST_TYPE) {
                                    if(isset($data->post_content['success_image'])) {
                                        if(af2_str_contains($data->post_content['success_image'], 'http')) {
                                            if(!af2_str_contains($post_content['success_image'], 'res/images/success_standard')) {
                                                $img_name = explode('/', $data->post_content['success_image']);
                                                $img_name = end($img_name);

                                                foreach($img_links as $link) {
                                                    if($link['old_path'] == $img_name) {
                                                        $data->post_content['success_image'] = wp_get_attachment_url( $link['new_path'] );
                                                    }
                                                }
                                            }
                                            else {
                                                $data->post_content['success_image'] = plugins_url('/res/images/success_standard.png', AF2_PLUGIN);
                                            }
                                        }
                                    }

                                }

                                $data->post_content = urlencode(serialize($data->post_content));
                                $id = wp_insert_post( array('post_content' => $data->post_content, 'post_status' => 'privat', 'post_type' => $data->post_type) );

                                array_push($import_data_ids, array('old' => $data->id, 'new' => $id));
                                if($data->post_type == FORMULAR_POST_TYPE) array_push($import_data_form_ids, $id);
                            }

                            foreach($import_data_form_ids as $form) {
                                $form_content = unserialize(urldecode(get_post_field( 'post_content', $form )));

                                if(isset($form_content['all_entries']) && !empty($form_content['all_entries']) && sizeof($form_content['all_entries']) > 1) {
                                    for ($i=0; $i < sizeof($form_content['all_entries']); $i++) { 
                                        $entry = $form_content['all_entries'][$i];
                                        $import_data_id_array = array_filter($import_data_ids, function($var) use ($entry) { return $var['old'] == $entry['elementid']; });
                                        if(sizeof($import_data_id_array) < 1) continue;

                                        $import_data_id = array_shift($import_data_id_array);

                                        $form_content['all_entries'][$i]['elementid'] = $import_data_id['new'];
                                    }
                                }

                                if(isset($form_content['sections']) && !empty($form_content['sections'])) {
                                    for ($i=0; $i < sizeof($form_content['sections']); $i++) { 
                                        if(isset($form_content['sections'][$i]['contents']) && !empty($form_content['sections'][$i]['contents'])) {
                                            for ($j=0; $j < sizeof($form_content['sections'][$i]['contents']); $j++) { 
                                                $entry = $form_content['sections'][$i]['contents'][$j];
                                                $import_data_id_array = array_filter($import_data_ids, function($var) use ($entry) { return $var['old'] == $entry['data']; });
                                                if(sizeof($import_data_id_array) < 1) continue;

                                                $import_data_id = array_shift($import_data_id_array);

                                                $form_content['sections'][$i]['contents'][$j]['data'] = $import_data_id['new'];
                                            }
                                        }
                                    }
                                }

                                wp_update_post( array('ID' => $form,'post_content' => urlencode(serialize($form_content)) ) );
                            }

                            $return = [
                                'type' => 'success',
                                'msg' => 'Daten erfolgreich importiert!',
                            ];
    
                            unlink($zip_file_name);
                        }
                    } else {
                        $return = [
                            'type' => 'error',
                            'msg' => 'Fehler im Input File!',
                            'input_file' => $jsonFile
                        ];
                    }
                } else {
                    $return = [
                        'type' => 'error',
                        'msg' => 'FEHLER: Konnte das zip Archiv nicht öffnen!',
                        'zip_filename' => $zip_file_name
                    ];
                }
            } catch (Exception $e) {
                $return = [
                    'type' => 'error',
                    'msg' => $e->getMessage(),
                ];
            }
        } else {
            $return = [
                'type' => 'error',
                'msg' => 'ZIP extension not enabled on server!',
            ];
        }
    
        echo json_encode($return);
        wp_die();
    }
}
