<?php
/**
 * Function rendering the options page in the administration panel.
 * Inside your main plugin file, add the hook to process the form.
 *
 * @return void
 */
function Irent_Plugin_Options_Page()
{
    global $wpdb;
    
    $message = '';

    // Check if the form has been submitted
    if (isset($_POST['irent_submit'])) {
        // Verify the nonce
        if (!isset($_POST['irent_submit_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['irent_submit_nonce'])), 'irent_submit_action')) {
            die('Invalid nonce for irent_submit');
        }

        // Sanitize the username and password
        $username = sanitize_user($_POST['irent_username']);
        $password = sanitize_text_field($_POST['irent_password']);

        // Get the configuration table
        $configuration_table = Irent_Get_Data_DB();
  
        // Check if the username is set and different from the input or if the table does not exist
        if (isset($configuration_table['username']) && $configuration_table['username'] !== $username) {
            // Restore the database
            Irent_Restore_DB();
        }

        // Update the database with the new username and password
        Irent_Update_DB(
            array(
                'username'  => $username,
                'password'  => $password
            )
        );

        // Receive the API response code
        $response = Irent_Connect_API();
        if (is_wp_error($response)) {
            $message = $response;
        } elseif (wp_remote_retrieve_response_code($response) === 200) {
            // Update the login status in the database
            Irent_Update_DB(
                array(
                    'login_status' => true
                )
            );

            $message =  __irent('common.login.success', 'Login successfully');
        }
    }

    // Check if the form has been submitted
    if (isset($_POST['irent_save_changes'])) {
        // Verify the nonce
        if (!isset($_POST['irent_save_changes_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['irent_save_changes_nonce'])), 'irent_save_changes_action')) {
            die('Invalid nonce for irent_save_changes');
        }

        // Set the new configurations
        $new_settings = array(
            'searchId'      =>  sanitize_text_field($_POST['irent_destination_search']),
            'language'      =>  sanitize_text_field($_POST['irent_language']),
            'theme'         =>  sanitize_text_field($_POST['irent_theme']),
            'code'          =>  sanitize_text_field($_POST['irent_accommodation']),
            'map_key'       =>  sanitize_text_field($_POST['irent_map'])
        );

        $message = Irent_Check_Entries($new_settings);
        if (!is_wp_error($message)) {
            Irent_Update_DB(
                array(
                    'searchId'=>$new_settings['searchId'],
                    'language'=>$new_settings['language'],
                    'theme'=>$new_settings['theme'],
                    'code'=>$new_settings['code'],
                    'map_key'=>$new_settings['map_key']
                )
            );
        }
    }

    if (isset($_POST['irent_close_session'])) {
        // Verify the nonce
        if (!isset($_POST['irent_close_session_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['irent_close_session_nonce'])), 'irent_close_session_action')) {
            die('Invalid nonce for irent_close_session');
        }
        
        // Call the function to log out the user
        Irent_LogOut();
    
        // Display a message to the user
        $message = __irent('common.login.loggedOut', 'You are logged out');
    }

    if (isset($_POST['irent_clear_shortcode'])) {
        // Verify the nonce
        if (!isset($_POST['irent_clear_shortcode_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['irent_clear_shortcode_nonce'])), 'irent_clear_shortcode_action')) {
            die('Invalid nonce for irent_clear_shortcode');
        }
    
        // Call the function to clear the shortcode
        $message = Irent_Clear_Shortcode();
    }

    ?>
    <form
        method="post"
        action=""
        id="Irent_Option_Page"
    >
        <div class="wrap">
            <div class="box1">
                <img
                    src="<?php echo esc_url(plugin_dir_url(__FILE__) . '../../assets/img/logo-black.png'); ?>"
                    alt="Logo"
                >
            </div>
            <p>
                <?php echo __irent('optionPage.underlogo', 'Booking system - Channel Gateway - Management'); ?>
            </p>
            <hr style='height: 1px;  background-color: black;'>
            <?php
            if (!empty($message)) {
                if (is_wp_error($message)) {
                    echo Irent_Get_Error_Messages($message->get_error_message());
                } else {
                    echo Irent_Get_Success_Messages($message);
                }
            }
            if (Irent_Get_Logged()) {
                // Receive the API response code
                $response = Irent_Connect_API();

                if (is_wp_error($response)) {
                    Irent_Logout();
                    echo Irent_Get_Error_Messages($response->get_error_message());
                    ?>
                        <div style="margin-left: 15px;">
                            <button class="button-primary"><?php echo __irent('common.login.signIn', 'Sign in') ?></button>
                        </div>
                    <?php
                    exit;
                } elseif (wp_remote_retrieve_response_code($response) === 200) {
                    // Process the API response
                    $api_response_body = wp_remote_retrieve_body($response);
                    $api_response_data = json_decode($api_response_body, true);
                    $json_output = json_encode($api_response_data, JSON_PRETTY_PRINT);
            
                    // Check if the response contains an array of elements with "name" and "code".
                    $elements = isset($api_response_data['websites']) && is_array($api_response_data['websites']) ? $api_response_data['websites'] : array();
                }
            
                $configuration_data = Irent_Get_Data_DB();

                $required_fields = array('searchId', 'language', 'theme', 'code', 'map_key');
                $missing_key = '';

                foreach ($required_fields as $field) {
                    $key = $configuration_data[$field];
                    if (empty($key)) {
                        $missing_key .= "$key. ";
                    }
                }

                if ($missing_key != '') {
                    $message = new WP_Error('Mising_keys', __irent('common.validators.missingKeys', 'Missing required configuration data'). ': ' . $key);
                }

                // Shortcodes
                $script_code = '[irent_script]';
                $quicksearch_code = '[irent_quicksearch]';
                ?>
                    <div>
                        <h4><?php echo __irent('optionPage.scriptConfig', 'Configuration of the booking script'); ?></h4>
                        <table
                            class="form-table"
                            role="presentation"
                        >
                            <tbody>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('optionPage.bookingSource', 'Booking Source/WebSite:'); ?>
                                        </label>
                                    </th>
                                    <td>
                                        <select
                                            class="custom-select"
                                            id="irent_accommodation"
                                            name="irent_accommodation"
                                        >
                                            <?php
                                            // Create the <select> element with the element options
                                            foreach ($elements as $element) {
                                                $name = esc_attr($element['name'] ?? '');
                                                $code = esc_attr($element['code'] ?? '');
                                                $selected = ($configuration_data['code'] === $code) ? ' selected' : '';
                                                printf('<option value="%s"%s>%s</option>', $code, esc_attr($selected), $name);
                                            }
                                            ?>
                                        </select>
                                        <p class="description">
                                            <?php echo __irent('optionPage.chooseSite', 'Choose from the list any of your websites published from your i-rent.net account to list the accommodations published on it.'); ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('common.langs.lang', 'Language').':'; ?>
                                        </label>
                                    </th>
                                    <td>
                                        <select
                                            class="custom-select"
                                            id="irent_language"
                                            name="irent_language"
                                        >
                                            <?php
                                            $languages = IRENT_SUPPORTED_LANGUAGES;
                                            
                                            // Sort languages by their translated names
                                            uasort($languages, function ($a, $b) {
                                                return strcmp($a, $b);
                                            });

                                            $languages = ['auto' => __irent('optionsPage.autoDetect', 'Auto detect')] + $languages;

                                            foreach ($languages as $code => $name) {
                                                $selected = ($configuration_data['language'] === $code) ? ' selected' : '';
                                                printf('<option value="%s"%s>%s</option>', esc_attr($code), esc_attr($selected), __irent("common.langs.{$code}", "{$name}"));
                                            }
                                            ?>
                                        </select>
                                        <p class="description">
                                            <?php echo __irent('optionPage.selectLang', 'Choose the language in which the accommodation search and booking engine.'); ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('common.theme', 'Theme').':'; ?>
                                        </label>
                                    </th>
                                    <td>
                                        <select
                                            class="custom-select"
                                            id="irent_theme"
                                            name="irent_theme"
                                        >
                                            <?php
                                            //Define an associative array with the language code keys and their display names
                                            $theme = IRENT_COLOR_SCHEMES;

                                            uasort($theme, function ($a, $b) {
                                                return strcmp($a, $b);
                                            });
                                            
                                            foreach ($theme as $code => $name) {
                                                $selected = ($configuration_data['theme'] === $code) ? ' selected' : '';
                                                printf('<option value="%s"%s>%s</option>', esc_attr($code), esc_attr($selected), __irent("common.colours.{$code}", "{$name}"));
                                            }
                                            ?>
                                        </select>
                                        <p class="description">
                                            <?php echo __irent('optionPage.selectColour', 'Select from the options the colour palette that best suits your website.'); ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('optionPage.GApiKey', 'Google Map Api Key: '); ?>
                                        </label>
                                    </th>
                                    <td>
                                        <input
                                            class="regular-text"
                                            id="irent_map"
                                            name="irent_map"
                                            value="<?php echo esc_attr($configuration_data['map_key'])?>"
                                            type="text"
                                        >
                                        <p class="description">
                                            <?php echo __irent('optionPage.warningMapKey', 'For the accommodation map to display correctly, you must have the map code generated in your Google Cloud Platform account.'); ?>
                                        </p>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('optionPage.shortcode.script.title', 'Script shortcode:'); ?>
                                        </label>
                                    </th>
                                    <td>
                                        <p>
                                            <?php echo __irent('optionPage.shortcode.script.subtitle', 'You can easily add the following shortcode anywhere on the page to display the booking system exactly where you’d like:');?>
                                        </p>
                                        <div class="clipboard">
                                            <input
                                                type="text"
                                                id="Input_Script"
                                                value="<?php echo esc_attr($script_code); ?>"
                                                readonly
                                            >
                                            <span
                                                class="icon dashicons dashicons-clipboard"
                                                id="Copy_Script"
                                                title="<?php echo __irent('common.copyClipboard', 'Copy to clipboard')?>"
                                                data-tooltip="<?php echo __irent('common.copied', 'Copied')?>"
                                            >
                                            </span>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <th scope="row">
                                        <label for="blogname">
                                            <?php echo __irent('optionPage.shortcode.quicksearch.title', 'Quicksearch shortcode:'); ?>
                                        </label>
                                    </th>
                                    <td>
                                        <select
                                            class="custom-select"
                                            id="irent_destination_search"
                                            name="irent_destination_search"
                                        >
                                            <option value="0"<?php echo ($configuration_data['searchId'] == 0) ? ' selected' : ''; ?>>
                                                <?php echo __irent('common.selectPage', 'Select page'); ?>
                                            </option>

                                            <?php
                                            // Get the list of pages
                                            $pages_search = get_pages();
                                            foreach ($pages_search as $page) {
                                                echo ("<pre>" . ($configuration_data['searchId']) . " " . esc_attr($page->ID) . '</pre>');
                                                $selected = ($configuration_data['searchId'] == esc_attr($page->ID)) ? ' selected' : '';
                                                printf('<option value="%s"%s>%s</option>', esc_attr($page->ID), esc_attr($selected), esc_html($page->post_title));
                                            }
                                            ?>
                                        </select>
                                        <p class="description">
                                            <?php echo __irent('optionPage.shortcode.quicksearch.warning', 'To enable the quick search to redirect correctly, select a page from the list of published pages.')?>
                                        </p>
                                        <p>
                                            <?php echo __irent('optionPage.shortcode.quicksearch.subtitle', 'You can easily insert the following shortcode anywhere on the page to display the quick search widget in your preferred spot:');?>
                                        </p>
                                        <div class="clipboard">
                                            <input
                                                type="text"
                                                id="Input_Quicksearch"
                                                value="<?php echo esc_attr($quicksearch_code); ?>"
                                                readonly
                                            >
                                            <span
                                                class="icon dashicons dashicons-clipboard"
                                                id="Copy_Quicksearch"
                                                style="cursor: pointer; margin-left: 10px;"
                                                title="<?php echo __irent('common.copyClipboard', 'Copy to clipboard')?>"
                                                data-tooltip="<?php echo __irent('common.copied', 'copied')?>"
                                            >
                                            </span>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td></td>
                                    <input
                                        type="hidden"
                                        name="irent_close_session_nonce"
                                        value="<?php echo esc_attr(wp_create_nonce('irent_close_session_action')); ?>"
                                    >
                                    <input
                                        type="hidden"
                                        name="irent_save_changes_nonce"
                                        value="<?php echo esc_attr(wp_create_nonce('irent_save_changes_action')); ?>"
                                    >
                                    <td>
                                        <span>
                                            <input
                                                type="submit"
                                                name="irent_save_changes"
                                                value="<?php echo __irent('common.saveChanges', 'Save Changes');?>" class="button-primary"
                                            >
                                        </span>
                                        <span style="margin-left:20px">
                                            <input
                                                type="submit"
                                                name="irent_close_session"
                                                value="<?php echo __irent('common.login.logout', 'Log Out'); ?>" class="button-secondary"
                                            >
                                        </span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                        <br>
                    </div>
                <?php
            } else {
                // Get the current values of the plugin option
                $plugin_options = get_option('irent_plugin_options');
                $username = isset($plugin_options['username']) ? $plugin_options['username'] : '';
                $password = isset($plugin_options['password']) ? $plugin_options['password'] : '';
            
                ?>
                    <div>
                        <h4>
                            <?php echo __irent('optionPage.welcome', 'Welcome to your holiday rental booking system') ?>
                        </h4>
                        <table>
                            <tr>
                                <td>
                                    <label for="irent_username">
                                        <?php echo __irent('common.login.user', 'User') ?>:
                                    </label>
                                </td>
                                <td>
                                    <input
                                        type="text"
                                        id="irent_username"
                                        name="irent_username"
                                        value="<?php echo esc_attr($username); ?>"
                                    >
                                    <br>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <label for="irent_password">
                                        <?php echo __irent('common.login.password', 'Password') ?>:
                                    </label>
                                </td>
                                <td>
                                    <input
                                     type="password"
                                     id="irent_password"
                                     name="irent_password"
                                     value="<?php echo esc_attr($password); ?>"
                                    >
                                    <br>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <input
                                        type="hidden"
                                        name="irent_submit_nonce"
                                        value="<?php echo esc_attr(wp_create_nonce('irent_submit_action')) ?>"
                                    >
                                </td>
                                <td>
                                    <input
                                        type="submit"
                                        name="irent_submit"
                                        value="<?php echo __irent('common.login.login', 'Login'); ?>" class="button-primary"
                                    >
                                </td>
                            </tr>
                        </table>
                        <br>
                    </div>
                <?php
            }
            ?>

        </div>
    </form>
    <?php
}
