<?php

$selected_type = isset($_POST['item_type']) ? $_POST['item_type'] : 'pages'; // Default to 'pages' if no selection is made

// Display the HTML form and user interface
echo '<div class="wrap">';
echo '<h1>Inception Templates</h1>';
echo '<p>Please select which pages or templates or images or plugins you would like to import.</p>';

// Form for selecting the item type (pages or templates)
echo '<form method="post">';
echo '<div class="filter-row">';
echo '<label for="item_type"style="margin-right: 5px;">Filter By:</label>';
echo '<select name="item_type" id="item_type">';
echo '<option value="pages"' . ($selected_type === 'pages' ? ' selected' : '') . '>Pages - Chiropractic</option>';
echo '<option value="pagesOPT"' . ($selected_type === 'pagesOPT' ? ' selected' : '') . '>Pages - Optometry</option>';
echo '<option value="landingpage"' . ($selected_type === 'landingpage' ? ' selected' : '') . '>Landing Pages</option>';
echo '<option value="templates"' . ($selected_type === 'templates' ? ' selected' : '') . '>Templates - Chiropractic</option>';
echo '<option value="templatesDEN"' . ($selected_type === 'templatesDEN' ? ' selected' : '') . '>Templates - Dental</option>';
echo '<option value="templatesOPT"' . ($selected_type === 'templatesOPT' ? ' selected' : '') . '>Templates - Optometry</option>';
echo '<option value="templatesPSY"' . ($selected_type === 'templatesPSY' ? ' selected' : '') . '>Templates - Psychiatric</option>';
echo '<option value="images"' . ($selected_type === 'images' ? ' selected' : '') . '>Images</option>';
echo '<option value="plugins"' . ($selected_type === 'plugins' ? ' selected' : '') . '>Plugins</option>';
echo '</select>';

// If a specific item type is selected, display the item group filter
if ($selected_type !== 'all') {
    echo '<label class="filter-label" for="item_group"style="margin-right: 5px;">Filter By Group:</label>';
    echo '<select name="item_group" id="item_group">';
    echo '<option value="all">All</option>';

    // Get the list of pages/templates from a file
    $page_list = include plugin_dir_path(__FILE__) . 'template-list.php';
    $groups = [];
    
    // Extract the groups based on the selected item type
    foreach ($page_list as $page) {
        if ($selected_type === 'pages' && isset($page['pagegroup'])) {
            $groups[] = $page['pagegroup'];
        } elseif ($selected_type === 'landingpage' && isset($page['landingpagegroup'])) {
            $groups[] = $page['landingpagegroup'];
        } elseif ($selected_type === 'pagesOPT' && isset($page['pageOPTgroup'])) {
            $groups[] = $page['pageOPTgroup'];
        } elseif ($selected_type === 'templates' && isset($page['templategroup'])) {
            $groups[] = $page['templategroup'];
        } elseif ($selected_type === 'templatesDEN' && isset($page['templateDENgroup'])) {
            $groups[] = $page['templateDENgroup'];
        } elseif ($selected_type === 'templatesOPT' && isset($page['templateOPTgroup'])) {
            $groups[] = $page['templateOPTgroup'];
        } elseif ($selected_type === 'templatesPSY' && isset($page['templatePSYgroup'])) {
            $groups[] = $page['templatePSYgroup'];
        } elseif ($selected_type === 'images' && isset($page['imagegroup'])) {
            $groups[] = $page['imagegroup'];
        } elseif ($selected_type === 'plugins' && isset($page['plugingroup'])) {
            $groups[] = $page['plugingroup'];
        }
    }

    $groups = array_unique($groups);
    sort($groups); // Alphabetically sort the groups

    // Display the group options in the dropdown
    foreach ($groups as $group) {
        echo '<option value="' . $group . '">' . $group . '</option>';
    }

    echo '</select>';
}

// Submit button for filtering the items
echo '<input type="submit" class="button button-filter" name="filter_items" value="Filter">';
echo '</div>';
echo '</form>';

// Display the table for listing the pages/templates
echo '<form method="post">';
echo '<table class="wp-list-table widefat fixed striped">';
if ($selected_type === 'images') {
    echo '<thead class="select-type-images"><tr>';
    echo '<th><input type="checkbox" id="select-all-pages"></th>';
    echo '<th></th>';
    echo '<th class="title-header">Title</th></tr></thead>';
} else {
    echo '<thead><tr>';
    echo '<th><input type="checkbox" id="select-all-pages"></th>';
    echo '<th class="title-header">Title</th></tr></thead>';
}
echo '<tbody>';

$page_list = include plugin_dir_path(__FILE__) . 'template-list.php';

// Sort the page list alphabetically by label
usort($page_list, function ($a, $b) {
    return strcmp($a['label'], $b['label']);
});

$row_counter = 0; // Initialize row counter

// Function to display rows
function display_row($page, $selected_type, &$row_counter) {
    echo '<tr>';
    if ($selected_type === 'images') {
        echo '<tr style="background-color: ' . (($row_counter % 2 === 0) ? '#e3e3e5' : '#ebedef') . ';">';
    }
    echo '<td class="centered">';
    // Check if the selected type is "Images" and add "label" to checkbox value
    if ($selected_type === 'images') {
        echo '<input type="checkbox" name="pages[]" value="' . $page['id'] . '|' . $page['label'] . '" style="margin-top: 50px;">';
    } else {
        echo '<input type="checkbox" name="pages[]" value="' . $page['id'] . '|' . $page['label'] . '">';
    }

    // Display the image if available
    if ($selected_type === 'images') {
        if (isset($page['id'])) {
            echo '<td>';
            echo '<img src="' . $page['id'] . '" alt="Image" style="height: 100px;"><br>';
        }
    }

    if ($selected_type === 'images') {
        echo '<td style="padding-top: 50px;">' . $page['label'] . '</td>';
    } else {
        echo '<td>' . $page['label'] . '</td>';
    }
    echo '</tr>';
    $row_counter++;
}

// If the form is submitted and the filter is applied, display filtered items
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['filter_items'])) {
    $selected_group = $_POST['item_group'];

    if ($selected_group === 'all') {
        foreach ($page_list as $page) {
            if (($selected_type === 'pages' && strcasecmp($page['type'], 'Pages') === 0)
                || ($selected_type === 'landingpage' && strcasecmp($page['type'], 'Landing Pages') === 0)
                || ($selected_type === 'pagesOPT' && strcasecmp($page['type'], 'Pages - OPT') === 0)
                || ($selected_type === 'templates' && strcasecmp($page['type'], 'Templates') === 0)
                || ($selected_type === 'templatesDEN' && strcasecmp($page['type'], 'Templates - DEN') === 0)
                || ($selected_type === 'templatesOPT' && strcasecmp($page['type'], 'Templates - OPT') === 0)
                || ($selected_type === 'templatesPSY' && strcasecmp($page['type'], 'Templates - PSY') === 0)
                || ($selected_type === 'images' && strcasecmp($page['type'], 'Images') === 0)
                || ($selected_type === 'plugins' && strcasecmp($page['type'], 'Plugins') === 0)
            ) {
                display_row($page, $selected_type, $row_counter);
            }
        }
    } else {
        // Iterate over the filtered page list and display the pages/templates
        foreach ($page_list as $page) {
            if (($selected_type === 'pages' && isset($page['pagegroup']) && strcasecmp($page['pagegroup'], $selected_group) === 0)
                || ($selected_type === 'landingpage' && isset($page['landingpagegroup']) && strcasecmp($page['landingpagegroup'], $selected_group) === 0)
                || ($selected_type === 'pagesOPT' && isset($page['pageOPTgroup']) && strcasecmp($page['pageOPTgroup'], $selected_group) === 0)
                || ($selected_type === 'templates' && isset($page['templategroup']) && strcasecmp($page['templategroup'], $selected_group) === 0)
                || ($selected_type === 'templatesDEN' && isset($page['templateDENgroup']) && strcasecmp($page['templateDENgroup'], $selected_group) === 0)
                || ($selected_type === 'templatesOPT' && isset($page['templateOPTgroup']) && strcasecmp($page['templateOPTgroup'], $selected_group) === 0)
                || ($selected_type === 'templatesPSY' && isset($page['templatePSYgroup']) && strcasecmp($page['templatePSYgroup'], $selected_group) === 0)
                || ($selected_type === 'images' && isset($page['imagegroup']) && strcasecmp($page['imagegroup'], $selected_group) === 0)
                || ($selected_type === 'plugins' && isset($page['plugingroup']) && strcasecmp($page['plugingroup'], $selected_group) === 0)
            ) {
                display_row($page, $selected_type, $row_counter);
            }
        }
    }
} else {
    // If no filter is applied, display all pages/templates
    foreach ($page_list as $page) {
        if (($selected_type === 'pages' && strcasecmp($page['type'], 'Pages') === 0)
            || ($selected_type === 'landingpage' && strcasecmp($page['type'], 'Landing Pages') === 0)
            || ($selected_type === 'pagesOPT' && strcasecmp($page['type'], 'Pages - OPT') === 0)
            || ($selected_type === 'templates' && strcasecmp($page['type'], 'Templates') === 0)
            || ($selected_type === 'templatesDEN' && strcasecmp($page['type'], 'Templates - DEN') === 0)
            || ($selected_type === 'templatesOPT' && strcasecmp($page['type'], 'Templates - OPT') === 0)
            || ($selected_type === 'templatesPSY' && strcasecmp($page['type'], 'Templates - PSY') === 0)
            || ($selected_type === 'images' && strcasecmp($page['type'], 'Images') === 0)
            || ($selected_type === 'plugins' && strcasecmp($page['type'], 'Plugins') === 0)
        ) {
            display_row($page, $selected_type, $row_counter);
        }
    }
}


echo '</tbody></table>';
// Submit, Clear Selection, & Download Selection Buttons
echo '<div class="button-row">';
echo '<input type="hidden" name="action" value="import_pages">';
echo wp_nonce_field('import_pages_nonce', '', false);

// Determine the name attribute for the submit button
$selected_type = isset($_POST['item_type']) ? $_POST['item_type'] : 'pages';
$submit_button_name = $selected_type === 'images' ? 'import_images' : 
                     ($selected_type === 'plugins' ? 'activate_plugins' : 
                     ($selected_type === 'pagesOPT' ? 'import_pages_opt' : 
                     ($selected_type === 'templatesOPT' ? 'import_pages_opt' :
                     ($selected_type === 'templatesPSY' ? 'import_pages_psy' :
                     ($selected_type === 'templatesDEN' ? 'import_templates_den' : 'import_pages')))));
$download_button_name = $selected_type === 'images' ? 'download_images' : 'download_selection';


echo '<input type="submit" class="button button-primary" name="' . $submit_button_name . '" value="Submit" style="margin-right: 5px;">';
echo '<input type="submit" class="button" name="clear_selection" value="Clear Selection" onclick="clearSelection(); return false;">';

// Check if selected_type is NOT equal to "plugins" before displaying the "Download Selection" button
// if ($selected_type !== 'plugins') {
//     echo '<input type="submit" name="' . $download_button_name . '" value="Download Selection" style="margin-left: 5px; height:30px;">';
// }
echo '</form>';

echo '</div>';
echo '</div>';
?>

<?php
$page_list = include plugin_dir_path(__FILE__) . 'template-list.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check the request method and handle different actions based on the submitted form
    if (isset($_POST['import_pages'])) {
        import_templates_action();
    } elseif (isset($_POST['import_templates_den'])) {
        import_den_templates_action();
    } elseif (isset($_POST['import_pages_opt'])) {
        import_opt_templates_action();
    } elseif (isset($_POST['import_pages_psy'])) {
        import_psy_templates_action();
    } elseif (isset($_POST['import_images'])) {
        import_images_action();
    } elseif (isset($_POST['activate_plugins'])) {
        activate_plugins_action();
    } elseif (isset($_POST['clear_selection'])) {
        clear_selection_action();
    } elseif (isset($_POST['download_selection'])) {
        download_selection_action();
    } elseif (isset($_POST['download_images'])) {
        download_images_action();
    }
}

// Function to handle the action of downloading selected templates
function download_selection_action() {
    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No templates selected!</p></div>';
        } else {
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            // Convert the selected page IDs into a comma-separated string
            $ids = implode(',', $selected_pages);

            // Construct the command to execute the download-templates.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'download-templates.sh';
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . escapeshellarg($ids);

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                // Set the path of the file to be downloaded
                $file_path = $_SERVER['DOCUMENT_ROOT'] . '/templateCopy1.xml';

                // Set the desired file name
                $file_name = 'templateCopy1.xml';
            
                // Check if the file exists
                if (file_exists($file_path)) {
                    // Set headers to force the browser to download the file
                    header('Content-Type: application/octet-stream');
                    header('Content-Transfer-Encoding: Binary');
                    header('Content-disposition: attachment; filename="' . $file_name . '"');
            
                    // Read the file contents
                    $file_contents = file_get_contents($file_path);
            
                    // Output the file contents to the browser
                    echo $file_contents;
                    
                    // Run the script to remove the excess files
                    $domain = parse_url(home_url(), PHP_URL_HOST);
                    $domain = preg_replace('/^www\./', '', $domain);
        
                    // Construct the command to execute the remove-download.sh script
                    $scriptPath = plugin_dir_path(__FILE__) . 'remove-download.sh';
                    $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain);
        
                    // Execute the command and capture the output and exit status
                    $descriptors = array(
                        1 => array('pipe', 'w'), // Capture stdout
                        2 => array('pipe', 'w'), // Capture stderr
                    );
        
                    $process = proc_open($command, $descriptors, $pipes);
                    $output = stream_get_contents($pipes[1]);
                    $errorOutput = stream_get_contents($pipes[2]);
                    fclose($pipes[1]);
                    fclose($pipes[2]);
                    
                    // Terminate the script to prevent any additional output
                    exit;
                } else {
                    // File doesn't exist, show error message
                    $error_msg = 'Inception Templates encountered an error: file does not exist. Please try again. ';
                }
            } else {
                echo '<div class="notice notice-error"><p>Error Downloading Files! ' . htmlspecialchars($output) . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Pages Or Templates Were Selected!</p></div>';
    }
}

// Function to handle the action of downloading selected images
function download_images_action() {
    global $page_list; // Access the global $page_list array

    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Debugging output
        // echo '<pre>';
        // print_r($selected_pages);
        // echo '</pre>';
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No images selected!</p></div>';
        } else {
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Construct the command to execute the download-images.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'download-images.sh';
    
            // Prepare the selected pages array for the shell script
            $selected_pages_argument = implode(' ', array_map('escapeshellarg', $selected_pages));
            
            // Construct the command with the selected pages array as an argument
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . $selected_pages_argument;
            
            echo "Command: $command";

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                // Set the path of the file to be downloaded
                $file_path = $_SERVER['DOCUMENT_ROOT'] . '/downloaded_images.zip';

                // Set the desired file name
                $file_name = 'downloaded_images.zip';
            
                if (file_exists($file_path)) {
                    // Set headers to force the browser to download the file
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename="' . $file_name . '"');
                    header('Content-Length: ' . filesize($file_path));
                    header('Content-Transfer-Encoding: binary');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Expires: 0');
                
                    // Use a buffer to read and output the file contents in chunks
                    ob_clean();
                    flush();
                    $file = fopen($file_path, 'rb');
                    while (!feof($file)) {
                        echo fread($file, 8192); // Adjust the chunk size as needed
                        ob_flush();
                        flush();
                    }
                    fclose($file);
                
                    // Run the script to remove the excess files
                    $domain = parse_url(home_url(), PHP_URL_HOST);
                    $domain = preg_replace('/^www\./', '', $domain);
        
                    // Construct the command to execute the remove-image-download.sh script
                    $scriptPath = plugin_dir_path(__FILE__) . 'remove-image-download.sh';
                    $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain);
        
                    // Execute the command and capture the output and exit status
                    $descriptors = array(
                        1 => array('pipe', 'w'), // Capture stdout
                        2 => array('pipe', 'w'), // Capture stderr
                    );
        
                    $process = proc_open($command, $descriptors, $pipes);
                    $output = stream_get_contents($pipes[1]);
                    $errorOutput = stream_get_contents($pipes[2]);
                    fclose($pipes[1]);
                    fclose($pipes[2]);
                    
                    // Terminate the script to prevent any additional output
                    exit;

                } else {
                    // File doesn't exist, show error message
                    $error_msg = 'Inception Templates encountered an error: file does not exist. Please try again. ';
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Images Were Selected!</p></div>';
    }
}
}
}

// Function to handle the action of importing selected plugins
function activate_plugins_action() {
    global $page_list; // Access the global $page_list array

    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Debugging output
        // echo '<pre>';
        // print_r($selected_pages);
        // echo '</pre>';
        
        // Check if any plugins are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No plugins selected!</p></div>';
        } else {
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Construct the command to execute the import-images.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'activate-plugins.sh';
    
            // Prepare the selected pages array for the shell script
            $selected_pages_argument = implode(' ', array_map('escapeshellarg', $selected_pages));
            
            // Construct the command with the selected pages array as an argument
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . $selected_pages_argument;
            
            echo "Command: $command";

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Plugins Activated Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Plugins!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No plugins selected
        echo '<div class="notice notice-error"><p>ERROR: No Plugins Were Selected!</p></div>';
    }

}

// Function to handle the action of importing selected templates
function import_templates_action() {
    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No templates selected!</p></div>';
        } else {
            // Extract IDs and labels from the selected pages
            $ids = [];
            $labels = [];
            foreach ($selected_pages as $selected_page) {
                list($id, $label) = explode('|', $selected_page);
                $ids[] = $id;
                $labels[] = $label;
            }
            
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Convert the selected page IDs and labels into comma-separated strings
            $ids_str = implode(',', $ids);
            $labels_str = implode(',', $labels);

            // Construct the command to execute the templates.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'templates.sh';
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . escapeshellarg($ids_str) . ' ' . escapeshellarg($labels_str);

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Files Imported Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Files!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Pages Or Templates Were Selected!</p></div>';
    }
}

// Function to handle the action of importing selected templates for Optometry
function import_opt_templates_action() {
    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No templates selected!</p></div>';
        } else {
            // Extract IDs and labels from the selected pages
            $ids = [];
            $labels = [];
            foreach ($selected_pages as $selected_page) {
                list($id, $label) = explode('|', $selected_page);
                $ids[] = $id;
                $labels[] = $label;
            }
            
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Convert the selected page IDs and labels into comma-separated strings
            $ids_str = implode(',', $ids);
            $labels_str = implode(',', $labels);

            // Construct the command to execute the optTemplates.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'optTemplates.sh';
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . escapeshellarg($ids_str) . ' ' . escapeshellarg($labels_str);

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Files Imported Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Files!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Optometry Pages Or Templates Were Selected!</p></div>';
    }
}

// Function to handle the action of importing selected templates for Psychiatric Health (PSY)
function import_psy_templates_action() {
    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No templates selected!</p></div>';
        } else {
            // Extract IDs and labels from the selected pages
            $ids = [];
            $labels = [];
            foreach ($selected_pages as $selected_page) {
                list($id, $label) = explode('|', $selected_page);
                $ids[] = $id;
                $labels[] = $label;
            }
            
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Convert the selected page IDs and labels into comma-separated strings
            $ids_str = implode(',', $ids);
            $labels_str = implode(',', $labels);

            // Construct the command to execute the psyTemplates.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'psyTemplates.sh';
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . escapeshellarg($ids_str) . ' ' . escapeshellarg($labels_str);

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Files Imported Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Files!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Psychiatric Pages Or Templates Were Selected!</p></div>';
    }
}

// Function to handle the action of importing selected templates for Dental
function import_den_templates_action() {
    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No templates selected!</p></div>';
        } else {
            // Extract IDs and labels from the selected pages
            $ids = [];
            $labels = [];
            foreach ($selected_pages as $selected_page) {
                list($id, $label) = explode('|', $selected_page);
                $ids[] = $id;
                $labels[] = $label;
            }
            
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Convert the selected page IDs and labels into comma-separated strings
            $ids_str = implode(',', $ids);
            $labels_str = implode(',', $labels);

            // Construct the command to execute the denTemplates.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'denTemplates.sh';
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . escapeshellarg($ids_str) . ' ' . escapeshellarg($labels_str);

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Files Imported Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Files!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Dental Pages Or Templates Were Selected!</p></div>';
    }
}

function import_images_action() {
    global $page_list; // Access the global $page_list array

    if (isset($_POST['pages'])) {
        $selected_pages = $_POST['pages'];
        
        // Debugging output
        // echo '<pre>';
        // print_r($selected_pages);
        // echo '</pre>';
        
        // Check if any templates are selected
        if (count($selected_pages) === 0) {
            echo '<div class="notice notice-error"><p>No images selected!</p></div>';
        } else {
            // Get the domain of the website
            $domain = parse_url(home_url(), PHP_URL_HOST);
            $domain = preg_replace('/^www\./', '', $domain);
            
            // Construct the command to execute the import-images.sh script
            $scriptPath = plugin_dir_path(__FILE__) . 'import-images.sh';
    
            // Prepare the selected pages array for the shell script
            $selected_pages_argument = implode(' ', array_map('escapeshellarg', $selected_pages));
            
            // Construct the command with the selected pages array as an argument
            $command = 'bash ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($domain) . ' ' . $selected_pages_argument;
            
            echo "Command: $command";

            // Execute the command and capture the output and exit status
            $descriptors = array(
                1 => array('pipe', 'w'), // Capture stdout
                2 => array('pipe', 'w'), // Capture stderr
            );

            $process = proc_open($command, $descriptors, $pipes);
            $output = stream_get_contents($pipes[1]);
            $errorOutput = stream_get_contents($pipes[2]);
            fclose($pipes[1]);
            fclose($pipes[2]);

            $exit_status = proc_close($process);

            if ($exit_status === 0) {
                echo '<div class="notice notice-success"><p>Images Imported Successfully! <strong>Now Go Do Something Awesome!</strong></p></div>';
            } else {
                $error_message = str_replace("\n", "<br>", htmlspecialchars($output));
                echo '<div class="notice notice-error"><p>Error Importing Images!<br>' . $error_message . '</p></div>';
            }
        }
    } else {
        // No templates selected
        echo '<div class="notice notice-error"><p>ERROR: No Images Were Selected!</p></div>';
    }
}

// Function to handle the action of clearing the selection
function clear_selection_action() {
    echo '<div class="notice notice-info"><p>Selection cleared!</p></div>';
}
?>

<style>
    table.wp-list-table {
        width: auto;
    }

    table.wp-list-table td input[type="checkbox"] {
        vertical-align: middle;
    }

    table.wp-list-table th:nth-child(1),
    table.wp-list-table td.centered {
        width: 25px; /* Reduce the width of the checkbox column to 25px */
        text-align: center;
    }
    
    table.wp-list-table th:nth-child(2),
    table.wp-list-table td.title-cell {
        padding-left: 10px; /* Add 10px left padding to the Title column */
    }

    .filter-label {
        margin-left: 10px;
    }

    .filter-row {
        margin-top: 0px;
    }
    
    .filter-row input[type="submit"][name="filter_items"] {
        margin-left: 10px;
        margin-bottom: 10px;
    }
    
    .button-row {
        margin-top: 20px;
    }
    
    .button-row form {
        display: inline-block;
        margin-right: 10px;
    }
    .button-row form input[name="clear_selection"] {
        margin-left: 10px;
    }
    
    .wp-list-table th:nth-child(1) input[type="checkbox"] {
        margin-left: -3px;
        margin-top: 3px;
    }
    
    .hidden {
      display: none;
    }
    
    table.wp-list-table th.title-header,
    table.wp-list-table td.title-cell {
        padding-left: 10px; /* Add 10px left padding to the Title column */
    }
    
    /* Additional styling for Images category */
    table.wp-list-table.th.select-type-images th.title-header,
    table.wp-list-table.th.select-type-images td.title-cell {
        padding-left: 110px; /* Add 110px left padding to the Title column for Images */
    }
</style>

<script>
    // Select all checkboxes in the table when the "Select All" checkbox is clicked
    var selectAllCheckbox = document.getElementById('select-all-pages');
    selectAllCheckbox.addEventListener('click', function () {
        var pageCheckboxes = document.getElementsByName('pages[]');
        for (var i = 0; i < pageCheckboxes.length; i++) {
            pageCheckboxes[i].checked = selectAllCheckbox.checked;
        }
    });

    var checkboxes = document.getElementsByName('pages[]');
    var lastSelectedIndex = -1; // Index of the last selected checkbox
    
    // Select all checkboxes in between selected checkboxes when Shift+Clicking
    function handleCheckboxShiftClick(event) {
        var currentIndex = Array.prototype.indexOf.call(checkboxes, event.target);

        if (lastSelectedIndex !== -1 && currentIndex !== -1) {
            var min = Math.min(lastSelectedIndex, currentIndex);
            var max = Math.max(lastSelectedIndex, currentIndex);

            for (var i = min + 1; i < max; i++) {
                checkboxes[i].checked = event.target.checked;
            }
        }

        lastSelectedIndex = currentIndex;
    }

    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].addEventListener('click', function (event) {
            if (event.shiftKey) {
                handleCheckboxShiftClick(event);
            } else {
                lastSelectedIndex = Array.prototype.indexOf.call(checkboxes, event.target);
            }
        });
    }

    // Clear all checkboxes when the Clear Selection Button is clicked
    function clearSelection() {
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = false;
        });
        lastSelectedIndex = -1;
        
        selectAllCheckbox.checked = false; // Uncheck the "Select All" checkbox
    }
</script>
