<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php if ( !isset($_GET['user_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['user_nonce'])), 'Copuloo') ) {} ?>
<?php
global $wpdb;
$copuloo_table = $wpdb->prefix . 'copuloo_api_keys';
$copuloo_keys = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_api_keys WHERE id = %s LIMIT 1", 'ACWJB59')); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$copuloo_keys_auto_info = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_api_keys WHERE id = %s LIMIT 1", 'ACWJB59auto')); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$copuloo_decrypt = new CopulooKeysClass();
?>

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

    <?php if ( isset($copuloo_keys[0]->twilio_sid) && isset($copuloo_keys[0]->twilio_token) && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_sid) != '' && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_token) !='' ) { ?>
    <div class="copuloo-card">
        <form action="<?php echo esc_url(admin_url('admin-post.php')); ?>" method="post" class="copuloo-form">
        <?php wp_nonce_field('Copuloo', 'user_nonce'); ?>
        <input type="hidden" name="action" value="copuloo_auto_setup_api_keys">
          <div class="copuloo-form">
            <button type="submit" onclick="this.innerHTML='<span class=&quot;spinner-border spinner-border-sm&quot;></span>'; this.disabled=true; this.form.submit();" class="copuloo-button copuloo-button-primary">Automatically Setup API Keys</button>
            <?php if (isset($copuloo_keys_auto_info[0]->updated_at)) { echo '<div class="copuloo-notice copuloo-notice-info"><span>API keys were automatically and successfully created '.copuloo_timeElapsed($copuloo_keys_auto_info[0]->updated_at).'</div>'; } // phpcs:ignore WordPress.Security.EscapeOutput
            ?>
            <p class="copuloo-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="copuloo-form">
        <?php wp_nonce_field('Copuloo', 'user_nonce'); ?>
        <input type="hidden" name="action" value="copuloo_setup_api_keys">

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

        <div class="copuloo-card">
            <h2 class="copuloo-title">Twilio TwiML App Key</h2>
            <p class="copuloo-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="copuloo-list">
                <li><strong>Voice Configuration:</strong> <code><?php echo esc_url(admin_url('admin-post.php?action=copuloo_calls_logic')); ?></code></li>
                <li><strong>Messaging Configuration:</strong> <code><?php echo esc_url(admin_url('admin-post.php?action=copuloo_incoming_texts')); ?></code></li>
            </ul>
            <p class="copuloo-description">Ensure the Request URLs are set to HTTP POST.</p>
            <div class="copuloo-form-group">
                <label for="twiml_app_sid" class="copuloo-label">TwiML App SID</label>
                <?php if ( isset($copuloo_keys[0]->twilio_sid) && isset($copuloo_keys[0]->twilio_token) && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_sid) != '' && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="TwiML_App_SID" id="twiml_app_sid" value="<?php if (isset($copuloo_keys[0]->TwiML_App_SID)) { echo esc_html($copuloo_decrypt->decrypt_data($copuloo_keys[0]->TwiML_App_SID)); } ?>" placeholder="Enter TwiML App SID" class="copuloo-input">
                <?php } else { ?>
                <input type="text" disabled name="TwiML_App_SID" id="twiml_app_sid" value="" placeholder="Enter Twilio SID & Token Key first" class="copuloo-input">
                <?php } ?>
            </div>
            <?php if ( isset($copuloo_keys_auto_info[0]->TwiML_App_SID)) { ?>
                <div class="copuloo-form-group">
                <label for="twiml_app_sid" class="copuloo-label">Friendly Name That Was Given</label>
                <input type="text" disabled value="<?php echo esc_html($copuloo_keys_auto_info[0]->TwiML_App_SID); ?>" placeholder="<?php echo esc_html($copuloo_keys_auto_info[0]->TwiML_App_SID); ?>" class="copuloo-input">
                </div>
                <?php } ?>
            <p class="copuloo-help-text">Note: The TwiML App key is required for Copuloo to function.</p>
        </div>

        <div class="copuloo-card">
            <h2 class="copuloo-title">Twilio API Keys & Tokens</h2>
            <p class="copuloo-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="copuloo-form-group">
                <label for="api_key" class="copuloo-label">API SID Key</label>
                <?php if ( isset($copuloo_keys[0]->twilio_sid) && isset($copuloo_keys[0]->twilio_token) && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_sid) != '' && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="API_KEY" id="api_key" value="<?php if (isset($copuloo_keys[0]->API_KEY)) { echo esc_html($copuloo_decrypt->decrypt_data($copuloo_keys[0]->API_KEY)); } ?>" placeholder="Enter API SID Key" class="copuloo-input">
                <?php } else { ?>
                <input type="text" disabled name="API_KEY" id="api_key" value="" placeholder="Enter Twilio SID & Token Key first" class="copuloo-input">
                <?php } ?>
            </div>
            <div class="copuloo-form-group">
                <label for="api_secret" class="copuloo-label">API Secret</label>
                <?php if ( isset($copuloo_keys[0]->twilio_sid) && isset($copuloo_keys[0]->twilio_token) && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_sid) != '' && $copuloo_decrypt->decrypt_data($copuloo_keys[0]->twilio_token) !='' ) { ?>
                <input type="password" name="API_SECRET" id="api_secret" value="<?php if (isset($copuloo_keys[0]->API_SECRET)) { echo esc_html($copuloo_decrypt->decrypt_data($copuloo_keys[0]->API_SECRET)); } ?>" placeholder="Enter API Secret" class="copuloo-input">
                <?php } else { ?>
                <input type="text" disabled name="API_SECRET" id="api_secret" value="" placeholder="Enter Twilio SID & Token Key first" class="copuloo-input">
                <?php } ?>
            </div>
            <?php if ( isset($copuloo_keys_auto_info[0]->API_KEY)) { ?>
                <div class="copuloo-form-group">
                <label for="twiml_app_sid" class="copuloo-label">Friendly Name That Was Given</label>
                <input type="text" disabled value="<?php echo esc_html($copuloo_keys_auto_info[0]->API_KEY); ?>" placeholder="<?php echo esc_html($copuloo_keys_auto_info[0]->API_KEY); ?>" class="copuloo-input">
                </div>
                <?php } ?>
            <p class="copuloo-help-text">Note: Twilio API keys are required for Copuloo to function.</p>
        </div>

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

    <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
    <?php wp_nonce_field( 'Copuloo', 'user_nonce' ); ?>
    <input type="hidden" name="action" value="copuloo_additional_setup">
    <div class="copuloo-card">
        <h2 class="copuloo-title">Requesting Phone Numbers</h2>
        <p class="copuloo-description">Select who can request phone numbers from the Copuloo dashboard. Administrators will always be able to manually add and remove phone numbers from the admin pages.</p>
            <div class="copuloo-form-group">
                <label class="copuloo-label">Permission Level</label>
                <div class="copuloo-input-group">
                    <select name="copuloo_user_can_request_number" id="copuloo_user_can_request_number" class="form-select">
                        <option value="true" <?php if (get_option('copuloo_user_can_request_number') == true) { echo 'selected'; } ?>>Anyone can request</option>
                        <option value="false" <?php if (get_option('copuloo_user_can_request_number') == false) { echo 'selected'; } ?>>Only administrators</option>
                    </select>
                </div>
            </div>
    </div>
    <div class="copuloo-card">
        <div class="copuloo-form">
        <button type="submit" class="copuloo-button copuloo-button-primary">Save Settings</button>
        </div>
    </form>
<?php } ?>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {

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

    const warning = document.getElementById('copuloo_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>