<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php if ( !isset($_GET['user_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['user_nonce'])), 'DialBunny') ) {} ?>
<?php
global $wpdb;
$dialbunny_table = $wpdb->prefix . 'dialbunny_api_keys';
$dialbunny_keys = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_api_keys WHERE id = %s LIMIT 1", 'ACWJB59')); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$dialbunny_keys_auto_info = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_api_keys WHERE id = %s LIMIT 1", 'ACWJB59auto')); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$dialbunny_decrypt = new DialBunnyKeysClass();
?>

<div class="dialbunny-admin-wrap">
<?php if ($current_page == 'setup' && !isset($_GET['tabpage'])) { ?>
    <?php if (isset($_GET['warning1'])) { echo wp_kses_post('<div class="dialbunny-notice dialbunny-notice-error"><p><strong>Nothing Was Updated!</strong> You entered the same information that was previously saved so nothing was changed.</p><button class="dialbunny-notice-dismiss">Dismiss</button></div>'); }  ?>
    <?php if (isset($_GET['success1'])) { echo wp_kses_post('<div class="dialbunny-notice dialbunny-notice-success"><p><strong>API Keys Successfully Saved!</strong> Your API keys were saved successfully.</p><button class="dialbunny-notice-dismiss">Dismiss</button></div>'); }  ?>
    <?php if (isset($_GET['success2'])) { echo wp_kses_post('<div class="dialbunny-notice dialbunny-notice-success"><p><strong>API Keys Successfully Auto Created!</strong> You have successfully automatically created the necessary remaining API keys.</p><button class="dialbunny-notice-dismiss">Dismiss</button></div>'); }  ?>
    <?php if (isset($_GET['error']) && isset($_GET['errorcode'])) { echo wp_kses_post('<div class="dialbunny-notice dialbunny-notice-error"><p><strong>Error '.sanitize_text_field(wp_unslash($_GET['errorcode'])).'</strong> '.sanitize_text_field(wp_unslash($_GET['error'])).'. Possible incorrect Twilio SID & Token Keys.</p><button class="dialbunny-notice-dismiss">Dismiss</button></div>'); }  ?>
    <div class="dialbunny-card">
        <h2 class="dialbunny-title">DialBunny Setup</h2>
        <p class="dialbunny-description">Add the necessary API keys to enable DialBunny functionality. This section is visible only to administrators.</p>
        <p class="dialbunny-description">Refer to the <a href="https://dialbunny.com/documentation/" target="_blank" class="dialbunny-link">DialBunny Documentation</a> for detailed guidance.</p>
    </div>

    <?php if ( isset($dialbunny_keys[0]->twilio_sid) && isset($dialbunny_keys[0]->twilio_token) && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_sid) != '' && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_token) !='' ) { ?>
    <div class="dialbunny-card">
        <form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post" class="dialbunny-form">
        <?php wp_nonce_field('DialBunny', 'user_nonce'); ?>
        <input type="hidden" name="action" value="dialbunny_auto_setup_api_keys">
          <div class="dialbunny-form">
            <button type="submit" onclick="this.innerHTML='<span class=&quot;spinner-border spinner-border-sm&quot;></span>'; this.disabled=true; this.form.submit();" class="dialbunny-button dialbunny-button-primary">Automatically Setup API Keys</button>
            <?php if (isset($dialbunny_keys_auto_info[0]->updated_at)) { echo '<div class="dialbunny-notice dialbunny-notice-info"><span>API keys were automatically and successfully created '.dialbunny_timeElapsed($dialbunny_keys_auto_info[0]->updated_at).'</div>'; } // phpcs:ignore WordPress.Security.EscapeOutput
            ?>
            <p class="dialbunny-help-text">Note: The Twilio SID and Twilio Auth Token are required to complete the automatic process. This process will simply automatically create the TwiML app and the Twilio API SID Key & API Secret Key for you.</p>
          </div>
        </form>
    </div>
    <?php } ?>

    <form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post" class="dialbunny-form">
        <?php wp_nonce_field('DialBunny', 'user_nonce'); ?>
        <input type="hidden" name="action" value="dialbunny_setup_api_keys">

        <div class="dialbunny-card">
            <h2 class="dialbunny-title">Twilio SID & Token Keys</h2>
            <p class="dialbunny-description">Find your Account SID and Auth Token at the bottom of your Twilio dashboard and enter them below.</p>
            <div class="dialbunny-form-group mb-5">
                <label for="dialbunny_twilio_sid" class="dialbunny-label">Twilio Account SID</label>
                <input required type="password" name="TWILIO_SID" id="dialbunny_twilio_sid" value="<?php if (isset($dialbunny_keys[0]->twilio_sid)) { echo esc_html($dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_sid)); } ?>" placeholder="Enter Twilio SID" class="dialbunny-input">
            </div>
            <div class="dialbunny-form-group">
                <label for="dialbunny_twilio_token" class="dialbunny-label">Twilio Auth Token</label>
                <input required type="password" name="TWILIO_TOKEN" id="dialbunny_twilio_token" value="<?php if (isset($dialbunny_keys[0]->twilio_token)) { echo esc_html($dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_token)); } ?>" placeholder="Enter Twilio Auth Token" class="dialbunny-input">
            </div>
            <p class="dialbunny-help-text">Note: Twilio API keys are required for DialBunny to function.</p>
            <p style="display: none;" class="dialbunny-help-text" id="dialbunny_warning_save_text"><strong>API keys changed but not saved.</strong></p>
        </div>

        <div class="dialbunny-card">
            <h2 class="dialbunny-title">Twilio TwiML App Key</h2>
            <p class="dialbunny-description">In your Twilio account, navigate to TwiML apps, create a new app, name it as desired, and set the Request URLs as follows:</p>
            <ul class="dialbunny-list">
                <li><strong>Voice Configuration:</strong> <code><?php echo esc_url(admin_url('admin-post.php?action=dialbunny_calls_logic')); ?></code></li>
                <li><strong>Messaging Configuration:</strong> <code><?php echo esc_url(admin_url('admin-post.php?action=dialbunny_incoming_texts')); ?></code></li>
            </ul>
            <p class="dialbunny-description">Ensure the Request URLs are set to HTTP POST.</p>
            <div class="dialbunny-form-group">
                <label for="twiml_app_sid" class="dialbunny-label">TwiML App SID</label>
                <?php if ( isset($dialbunny_keys[0]->twilio_sid) && isset($dialbunny_keys[0]->twilio_token) && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_sid) != '' && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="TwiML_App_SID" id="twiml_app_sid" value="<?php if (isset($dialbunny_keys[0]->TwiML_App_SID)) { echo esc_html($dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->TwiML_App_SID)); } ?>" placeholder="Enter TwiML App SID" class="dialbunny-input">
                <?php } else { ?>
                <input type="text" disabled name="TwiML_App_SID" id="twiml_app_sid" value="" placeholder="Enter Twilio SID & Token Key first" class="dialbunny-input">
                <?php } ?>
            </div>
            <?php if ( isset($dialbunny_keys_auto_info[0]->TwiML_App_SID)) { ?>
                <div class="dialbunny-form-group">
                <label for="twiml_app_sid" class="dialbunny-label">Friendly Name That Was Given</label>
                <input type="text" disabled value="<?php echo esc_html($dialbunny_keys_auto_info[0]->TwiML_App_SID); ?>" placeholder="<?php echo esc_html($dialbunny_keys_auto_info[0]->TwiML_App_SID); ?>" class="dialbunny-input">
                </div>
                <?php } ?>
            <p class="dialbunny-help-text">Note: The TwiML App key is required for DialBunny to function.</p>
        </div>

        <div class="dialbunny-card">
            <h2 class="dialbunny-title">Twilio API Keys & Tokens</h2>
            <p class="dialbunny-description">In your Twilio account, go to API Keys & Tokens, create a new Standard key, name it as desired, and enter the credentials below.</p>
            <div class="dialbunny-form-group">
                <label for="api_key" class="dialbunny-label">API SID Key</label>
                <?php if ( isset($dialbunny_keys[0]->twilio_sid) && isset($dialbunny_keys[0]->twilio_token) && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_sid) != '' && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="API_KEY" id="api_key" value="<?php if (isset($dialbunny_keys[0]->API_KEY)) { echo esc_html($dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->API_KEY)); } ?>" placeholder="Enter API SID Key" class="dialbunny-input">
                <?php } else { ?>
                <input type="text" disabled name="API_KEY" id="api_key" value="" placeholder="Enter Twilio SID & Token Key first" class="dialbunny-input">
                <?php } ?>
            </div>
            <div class="dialbunny-form-group">
                <label for="api_secret" class="dialbunny-label">API Secret</label>
                <?php if ( isset($dialbunny_keys[0]->twilio_sid) && isset($dialbunny_keys[0]->twilio_token) && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_sid) != '' && $dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="API_SECRET" id="api_secret" value="<?php if (isset($dialbunny_keys[0]->API_SECRET)) { echo esc_html($dialbunny_decrypt->decrypt_data($dialbunny_keys[0]->API_SECRET)); } ?>" placeholder="Enter API Secret" class="dialbunny-input">
                <?php } else { ?>
                <input type="text" disabled name="API_SECRET" id="api_secret" value="" placeholder="Enter Twilio SID & Token Key first" class="dialbunny-input">
                <?php } ?>
            </div>
            <?php if ( isset($dialbunny_keys_auto_info[0]->API_KEY)) { ?>
                <div class="dialbunny-form-group">
                <label for="twiml_app_sid" class="dialbunny-label">Friendly Name That Was Given</label>
                <input type="text" disabled value="<?php echo esc_html($dialbunny_keys_auto_info[0]->API_KEY); ?>" placeholder="<?php echo esc_html($dialbunny_keys_auto_info[0]->API_KEY); ?>" class="dialbunny-input">
                </div>
                <?php } ?>
            <p class="dialbunny-help-text">Note: Twilio API keys are required for DialBunny to function.</p>
        </div>

        <div class="dialbunny-card">
          <div class="dialbunny-form">
            <?php if ( isset($dialbunny_keys_auto_info[0]->id)) { ?>
                <button type="submit" class="dialbunny-button dialbunny-button-danger">Manually Override API Keys</button>
                <p class="dialbunny-help-text">Note: This will manually update and override your API keys.</p>
             <?php } else { ?>
                <button type="submit" class="dialbunny-button dialbunny-button-primary">Save API Keys</button>
                <p class="dialbunny-help-text">Note: Twilio API keys are required for DialBunny to function.</p>
            <?php } ?>
        </div>
        </div>
    </form>
<?php } if ($current_page == 'setup' && isset($_GET['tabpage']) && sanitize_text_field(wp_unslash($_GET['tabpage']) == 'additional')) { ?>
<?php if (isset($_GET['success1'])) { echo wp_kses_post('<div class="dialbunny-notice dialbunny-notice-success"><p><strong>Settings Saved Successfully!</strong> Your settings have been updated successfully.</p><button class="dialbunny-notice-dismiss">Dismiss</button></div>'); }  ?>
<div class="dialbunny-card">
        <h2 class="dialbunny-title">Additional Settings</h2>
        <p>This settings page is dedicated to additional, optional setup and configuration to help you customize and enhance your DialBunny experience.</p>
    </div>

    <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
    <?php wp_nonce_field( 'DialBunny', 'user_nonce' ); ?>
    <input type="hidden" name="action" value="dialbunny_additional_setup">
    <div class="dialbunny-card">
        <h2 class="dialbunny-title">Requesting Phone Numbers</h2>
        <p class="dialbunny-description">Select who can request phone numbers from the DialBunny dashboard. Administrators will always be able to manually add and remove phone numbers from the admin pages.</p>
            <div class="dialbunny-form-group">
                <label class="dialbunny-label">Permission Level</label>
                <div class="dialbunny-input-group">
                    <select name="dialbunny_user_can_request_number" id="dialbunny_user_can_request_number" class="form-select">
                        <option value="true" <?php if (get_option('dialbunny_user_can_request_number') == true) { echo 'selected'; } ?>>Anyone can request</option>
                        <option value="false" <?php if (get_option('dialbunny_user_can_request_number') == false) { echo 'selected'; } ?>>Only administrators</option>
                    </select>
                </div>
            </div>
    </div>
    <div class="dialbunny-card">
        <h2 class="dialbunny-title">Video Call Guest Page</h2>
        <p class="dialbunny-description">The website page in which guests can join and create video calls. When disabled only WordPress users that are logged in and have access to the DialBunny dashboard will be able to start and join video calls.</p>
            <div class="dialbunny-form-group">
                <label class="dialbunny-label">Select Page</label>
                <div class="dialbunny-input-group">
                    <select name="dialbunny_user_guest_video_page" id="dialbunny_user_guest_video_page" class="form-select">
                        <option value="dialbunny_disabled_dialbunny" <?php if (get_option('dialbunny_user_guest_video_page') == 'dialbunny_disabled_dialbunny') { echo 'selected'; } ?>>- Disabled -</option>
                        <?php
                        $pages = get_pages([
                            'sort_column' => 'post_title',
                            'sort_order'  => 'ASC'
                        ]);
                        foreach ($pages as $page) {
                            if (get_option('dialbunny_user_guest_video_page') == $page->ID) { echo '<option selected value="'.esc_attr($page->ID).'">'. esc_html($page->post_title).'</option>'; }
                            else { echo '<option value="'.esc_attr($page->ID).'">'. esc_html($page->post_title).'</option>'; }
                        }
                        ?>
                    </select>
                </div>
            </div>
    </div>
    <div class="dialbunny-card">
        <div class="dialbunny-form">
        <button type="submit" class="dialbunny-button dialbunny-button-primary">Save Settings</button>
        </div>
    </form>
<?php } ?>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {

    // IDs or selectors of inputs to watch
    const watchedInputs = [
        '#dialbunny_twilio_sid',
        '#dialbunny_twilio_token'
    ];

    const warning = document.getElementById('dialbunny_warning_save_text');

    watchedInputs.forEach(selector => {
        const input = document.querySelector(selector);
        if (!input) return;

        input.addEventListener('change', () => {
            warning.style.display = 'block';
        });

        input.addEventListener('input', () => {
            warning.style.display = 'block';
        });
    });

});
</script>