<?php

?>
<div class="wrap">
    <h1>Inception Importer</h1>
    <p>Please either enter the domain of the other site you've exported your pages, blog posts, templates, saved rows, or media library images from or upload an exported XML file.</p>
    <form method="post" action="" enctype="multipart/form-data">
        <div style="display:flex; align-items:center; margin-bottom: 10px; margin-top: 20px;">
            <label for="domain" style="margin-right:25px;">Domain To Import From:</label>
            <input type="text" name="domain" id="domain" style="flex:0; width: calc(100% + 300px);">
        </div>
        <div style="display:flex; align-items:center; margin-bottom: 10px;">
            <label for="xml_file" style="margin-right:115px;">XML File:</label>
            <input type="file" name="xml_file" accept=".xml">
        </div>
        <div style="display:flex; align-items:center; margin-bottom: 10px; margin-top: 20px;">
            <label for="import_type" style="margin-right:25px;">Import Type:</label>
            <select name="import_type" id="import_type">
                <option value="pages_blogs_templates">Blogs/Pages/Templates</option>
                <option value="media_library_images">Media Library Images</option>
            </select>
        </div>

        <input type="hidden" name="action" value="page_import">
        <?php wp_nonce_field('page_import_nonce'); ?>
        <?php submit_button('Submit'); ?>
    </form>
    <p><strong>Notice:</strong> Please make sure you've already exported on the other site using <strong>TechBoost's Exporter</strong> before you import!</p>
</div>
  <?php


if ( isset( $_POST['action'] ) && $_POST['action'] === 'page_import' ) {
    page_import_action();
}

// Process the search and replace action
function page_import_action() {
    if (!current_user_can('manage_options')) {
        return;
    }

    check_admin_referer('page_import_nonce');
    
    // Get the selected import type
    $import_type = isset($_POST['import_type']) ? $_POST['import_type'] : '';

    // Define the shell script file paths
    $script_file_pages = dirname(__FILE__) . '/inception-page-import.sh';
    $script_file_media = dirname(__FILE__) . '/inception-media-import.sh';
    
    $fromDomain = $_POST['domain'];
    $toDomain = parse_url( home_url(), PHP_URL_HOST );
    $toDomain = preg_replace( '/^www\./', '', $toDomain );
    
    // Handle file upload
    $xmlFile = $_FILES['xml_file'];
    $errors = [];

    // If there are any errors, display them
    if (!empty($fromDomain) && !empty($xmlFile['name'])) {
        $errors[] = 'ERROR: Please enter either the domain or upload an XML file, not both.';
    }
    
    if (empty($fromDomain) && empty($xmlFile['name'])) {
        $errors[] = 'ERROR: Please enter either the domain or upload an XML file before submitting.';
    }

    if (empty($fromDomain) && $xmlFile['error'] !== UPLOAD_ERR_OK) {
        $errors[] = 'ERROR: File upload failed.';
    }

    if (empty($fromDomain) && $xmlFile['type'] !== 'text/xml') {
        $errors[] = 'ERROR: Invalid file type. Please upload a valid XML file.';
    }
  
    if (!empty($errors)) {
        echo '<div class="notice notice-error">';
        foreach ($errors as $error) {
            echo '<p>' . esc_html($error) . '</p>';
        }
        echo '</div>';
        return;
    }

    // Check if Blogs/Pages/Templates option is selected
    if ($import_type === 'pages_blogs_templates') {
        $fromDomain = $_POST['domain'];
        $script_file = dirname(__FILE__) . '/inception-page-import.sh';
        // Capture the exit status of the shell command
        $output = array();
        $status = 0;
        
        // Check if a file is uploaded
        if (!empty($xmlFile['name'])) {
            // File is uploaded, handle the file
            $target_directory = dirname(dirname(dirname(dirname(dirname(__FILE__)))));
            $target_file = $target_directory . '/' . basename($xmlFile['name']);
    
            // Move the uploaded file to the target directory
            if (move_uploaded_file($xmlFile['tmp_name'], $target_file)) {
                // Escape the file path to handle spaces
                $escaped_target_file = escapeshellarg($target_file);
                // Pass the XML file path to the shell script
                exec("sh $script_file $toDomain $escaped_target_file", $output, $status);
            } else {
                $status = 1;
                $output[] = 'ERROR: Failed to move uploaded file.';
            }
        } else {
            // No file is uploaded, handle the domain
            exec("sh $script_file $toDomain $fromDomain", $output, $status);
        }
    
    
        // Display success or error message based on the exit status
        switch ($status) {
            case 1:
                echo '<div class="notice notice-error"><p><strong>' . esc_html__( 'ERROR!', 'text-domain' ) . '</strong></p>';
                foreach ($output as $output_line) {
                    echo '<p>' . esc_html($output_line) . '</p>';
                }
                echo '</div>';
                break;
            default:
                echo '<div class="notice notice-success"><p>' . esc_html__( 'Successfully Imported Pages! ', 'text-domain' ) . '</p>';
                foreach ($output as $output_line) {
                    echo '<p>' . esc_html($output_line) . '</p>';
                }
                echo '<p><strong>Carpe Diem - Seize The Day!</strong> 😃</p>'; 
                echo '</div>';
                break;
        }
    } elseif ($import_type === 'media_library_images') {
        // Execute the media import script directly
        $output = array();
        $status = 0;
        exec("sh $script_file_media $toDomain $fromDomain", $output, $status);
        // Display success or error message based on the exit status
        if ($status === 0) {
            echo '<div class="notice notice-success"><p>' . esc_html__('Successfully Imported Media Library Images!', 'text-domain') . '</p>';
            foreach ($output as $output_line) {
                echo '<p>' . esc_html($output_line) . '</p>';
            }
            echo '<p><strong>Carpe Diem - Seize The Day!</strong> 😃</p>'; 
            echo '</div>';
        } else {
            echo '<div class="notice notice-error"><p>' . esc_html__('ERROR! Failed To Import Media Library Images.', 'text-domain') . '</p>';
            foreach ($output as $output_line) {
                echo '<p>' . esc_html($output_line) . '</p>';
            }
            echo '</div>';
        }
        return;
    }
}
