<?php
/**
 * Security Settings Section
 * Access Token Generation and Management
 * 
 * @package PSSG_Sync_Sheet
 * @since 1.1.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly  

use PSSG_Sync_Sheet\App\Service\Request_Log;

// Get current access key
$current_access_key = Request_Log::get_access_key();
$has_access_key = !empty($current_access_key);


?>
<table class="pssg-table security-settings" id="pssg-security-settings-table">
    <thead>
        <tr>
            <th class="pssg-inside">
                <div class="pssg-table-header-inside">
                    <h3>
                        <i class="pssg_icon-lock"></i>
                        <?php echo esc_html__( 'Security Settings', 'product-sync-master-sheet' ); ?>
                    </h3>
                </div>
            </th>
            <th>
                <div class="pssg-table-header-right-side"></div>
            </th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td>
                <div class="pssg-form-control pssg-access-key-section">
                    <div class="form-label col-lg-4">
                        <label for="pssg_access_key">
                            <i class="pssg_icon-key"></i>
                            <?php echo esc_html__( 'Access Token', 'product-sync-master-sheet' ); ?>
                        </label>
                        <p class="description">
                            <?php echo esc_html__( 'This key is required for Google Sheet to communicate with your WooCommerce store securely.', 'product-sync-master-sheet' ); ?>
                        </p>
                    </div>
                    <div class="form-field col-lg-8">
                        <div class="pssg-access-key-wrapper">
                            <?php if ( $has_access_key ) : ?>
                                <div class="pssg-access-key-display">
                                    <input type="text" 
                                           id="pssg_access_key_display" 
                                           class="pssg-access-key-input" 
                                           value="<?php echo esc_attr( $current_access_key ); ?>" 
                                           readonly 
                                           onclick="this.select();">
                                    <button type="button" 
                                            id="pssg-copy-access-key" 
                                            class="pssg-btn pssg-btn-small pssg-has-icon"
                                            title="<?php echo esc_attr__( 'Copy Access Token', 'product-sync-master-sheet' ); ?>">
                                        <span><i class="pssg_icon-floppy"></i></span>
                                        <strong><?php echo esc_html__( 'Copy', 'product-sync-master-sheet' ); ?></strong>
                                    </button>
                                </div>
                                
                                <!-- AppsScript Copy Button -->
                                <div class="pssg-appscript-copy-section">
                                    <a id="pssg-appscript-copy-button-security" class="pssg-btn pssg-has-icon primary" data-has-access-key="yes">
                                        <span><i class="pssg_icon-note"></i></span>
                                        <strong class="sync-btn-txt"><?php echo esc_html__( 'Copy AppsScript', 'product-sync-master-sheet' ); ?> <i>V<?php echo esc_html( PSSG_APPS_SCRIPT_VERSION ); ?></i></strong>
                                    </a>
                                    <p class="script-copy-msg-security"></p>
                                    <p class="pssg-appscript-help">
                                        <i class="pssg_icon-info-circled"></i>
                                        <?php echo esc_html__( 'Copy this AppsScript and paste it in your Google Sheet Extensions > Apps Script.', 'product-sync-master-sheet' ); ?>
                                    </p>
                                </div>
                                
                                <div class="pssg-access-key-actions">
                                    <button type="button" 
                                            id="pssg-regenerate-access-key" 
                                            class="pssg-btn pssg-btn-small pssg-has-icon warning"
                                            data-nonce="<?php echo esc_attr( wp_create_nonce( 'pssg_access_key_action' ) ); ?>">
                                        <span><i class="pssg_icon-arrows-cw"></i></span>
                                        <strong><?php echo esc_html__( 'Regenerate Token', 'product-sync-master-sheet' ); ?></strong>
                                    </button>
                                    <p class="pssg-key-warning">
                                        <i class="pssg_icon-attention"></i>
                                        <?php echo esc_html__( 'Warning: Regenerating the token will invalidate the current one. You will need to update the AppsScript in your Google Sheet.', 'product-sync-master-sheet' ); ?>
                                    </p>
                                </div>
                            <?php else : ?>
                                <div class="pssg-no-access-key">
                                    <p class="pssg-generate-key-message">
                                        <i class="pssg_icon-attention" style="color: #d63031;"></i>
                                        <?php echo esc_html__( 'No Access Token generated yet. Generate one to secure your API endpoints.', 'product-sync-master-sheet' ); ?>
                                    </p>
                                    <button type="button" 
                                            id="pssg-generate-access-key" 
                                            class="pssg-btn pssg-has-icon primary"
                                            data-nonce="<?php echo esc_attr( wp_create_nonce( 'pssg_access_key_action' ) ); ?>">
                                        <span><i class="pssg_icon-key"></i></span>
                                        <strong><?php echo esc_html__( 'Generate Access Token', 'product-sync-master-sheet' ); ?></strong>
                                    </button>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="pssg-access-key-status" id="pssg-access-key-status"></div>
                    </div>
                </div>
            </td>
            <td>
                <div class="pssg-access-key-description">
                    <p>
                        <?php echo esc_html__( 'The Access Token is a unique key that authenticates requests from your Google Sheet to your WooCommerce store. It ensures that only authorized requests can access your product data.', 'product-sync-master-sheet' ); ?>
                    </p>
                    <p>
                        <?php echo esc_html__( 'Keep this token secure and do not share it publicly. If you believe your token has been compromised, regenerate it immediately.', 'product-sync-master-sheet' ); ?>
                    </p>
                </div>
        </tr>

        <tr>
            <td colspan="2">
                <div class="pssg-security-info-box">
                    <h4><i class="pssg_icon-info-circled"></i> <?php echo esc_html__( 'How Access Token Works', 'product-sync-master-sheet' ); ?></h4>
                    <ul>
                        <li><?php echo esc_html__( '1. Generate an Access Token from this settings page.', 'product-sync-master-sheet' ); ?></li>
                        <li><?php echo esc_html__( '2. The Access Token will be automatically included when you copy the AppsScript code.', 'product-sync-master-sheet' ); ?></li>
                        <li><?php echo esc_html__( '3. Every request from Google Sheet to your website will include this token for authentication.', 'product-sync-master-sheet' ); ?></li>
                        <li><?php echo esc_html__( '4. Requests without a valid Access Token will be rejected.', 'product-sync-master-sheet' ); ?></li>
                    </ul>
                    <p class="pssg-important-note">
                        <strong><?php echo esc_html__( 'Important:', 'product-sync-master-sheet' ); ?></strong>
                        <?php echo esc_html__( 'After generating or regenerating the Access Token, you must copy the new AppsScript code and update it in your Google Sheet.', 'product-sync-master-sheet' ); ?>
                    </p>
                </div>
            </td>
        </tr>

    </tbody>
</table>

<?php
// Include AppsScript code for copy button
$sheet_name = get_option('pssg_saved_data', [])['sheet_name'] ?? '';
?>
<textarea id="appscript-code-area-security" style="display: none;visibility:hidden;height:0;width:0;">
<?php 
$website_routespace = 'pssg_gsheet_sync/v1/product';
$website_routespace_multiple = 'pssg_gsheet_sync/v1/multiples';
$replacements = [
    'pssg_namespace_route' => $website_routespace,
    'multiple_product_route' => $website_routespace_multiple,
    'pssg_json_website' => trailingslashit( get_rest_url() )
];
$script_file = PSSG_BASE_DIR . 'assets/js/script.js';
if( is_file( $script_file ) ){
    $code = pssg_file_get_content( $script_file );
    $code = preg_replace('/\/\/(.+?)\n/', '', $code);
    $code = preg_replace('/\/\*.*?\*\//s', '', $code);
    $code = preg_replace('/^\s*[\r\n]/m', '', $code);
    $code = str_replace( array_keys($replacements), array_values($replacements), $code );
    $appsV = 'var AppsScriptVersion = "' . PSSG_APPS_SCRIPT_VERSION . '";';
    $appsAccessKey = 'var AppsScriptAccessKey = "' . esc_js( $current_access_key ) . '";';
    $extraCode = $appsV . $appsAccessKey;
    $code = $extraCode . $code;
    $code = 'var YourSheetTabName = "' . sanitize_text_field( $sheet_name ) . '";' . $code;
    echo esc_js( $code );
}
?>
</textarea>

<script>
jQuery(document).ready(function($) {
    // AppsScript copy button in security settings
    $(document.body).on('click', '#pssg-appscript-copy-button-security', function(e) {
        e.preventDefault();
        var msgBox = $('.script-copy-msg-security');
        var contentToCopy = document.getElementById('appscript-code-area-security');
        
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(contentToCopy.textContent)
                .then(function () {
                    msgBox.text('AppsScript copied! Now paste it in your Google Sheet.').addClass('success');
                    setTimeout(function(){
                        msgBox.text("");
                    }, 3000);
                })
                .catch(function (err) {
                    msgBox.text('Unable to copy. Please try again.').addClass('error');
                    console.log(err);
                });
        } else {
            // Fallback for older browsers
            var textArea = document.createElement("textarea");
            textArea.value = contentToCopy.textContent;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            msgBox.text('AppsScript copied! Now paste it in your Google Sheet.').addClass('success');
            setTimeout(function(){
                msgBox.text("");
            }, 3000);
        }
    });
});
</script>

<style>
.pssg-access-key-section {
    padding: 20px;
    background: #f9f9f9;
    border-radius: 8px;
}
.pssg-access-key-wrapper {
    margin-bottom: 15px;
}
.pssg-access-key-display {
    display: flex;
    gap: 10px;
    align-items: center;
    margin-bottom: 15px;
}
.pssg-access-key-input {
    flex: 1;
    padding: 10px 15px;
    font-family: monospace;
    font-size: 14px;
    background: #fff;
    border: 2px solid #ddd;
    border-radius: 5px;
    cursor: pointer;
}
.pssg-access-key-input:focus {
    border-color: #0073aa;
    outline: none;
}
.pssg-appscript-copy-section {
    margin: 20px 0;
    padding: 15px;
    background: #f0f8ff;
    border-radius: 8px;
    border: 1px solid #b8daff;
}
.pssg-appscript-copy-section .pssg-btn {
    margin-bottom: 10px;
}
.pssg-appscript-help {
    margin: 0;
    color: #666;
    font-size: 13px;
}
.script-copy-msg-security {
    margin: 5px 0;
    color: #28a745;
    font-weight: 500;
}
.pssg-access-key-actions {
    margin-top: 15px;
}
.pssg-key-warning {
    margin-top: 10px;
    color: #856404;
    background: #fff3cd;
    padding: 10px 15px;
    border-radius: 5px;
    border-left: 4px solid #ffc107;
}
.pssg-no-access-key {
    text-align: center;
    padding: 30px;
    background: #fff;
    border: 2px dashed #ddd;
    border-radius: 8px;
}
.pssg-generate-key-message {
    font-size: 16px;
    margin-bottom: 20px;
}
.pssg-security-info-box {
    background: #e8f4fd;
    padding: 20px;
    border-radius: 8px;
    border-left: 4px solid #0073aa;
}
.pssg-security-info-box h4 {
    margin: 0 0 15px 0;
    color: #0073aa;
}
.pssg-security-info-box ul {
    margin: 0 0 15px 20px;
    padding: 0;
}
.pssg-security-info-box li {
    margin-bottom: 8px;
}
.pssg-important-note {
    margin: 0;
    padding: 10px 15px;
    background: #fff;
    border-radius: 5px;
}
.pssg-btn.warning {
    background: #f0ad4e;
    border-color: #eea236;
    color: #fff;
}
.pssg-btn.warning:hover {
    background: #ec971f;
}
.pssg-btn.primary {
    background: #0073aa;
    border-color: #006799;
    color: #fff;
}
.pssg-btn.primary:hover {
    background: #005a87;
}
.pssg-access-key-status {
    margin-top: 10px;
}
.pssg-access-key-status.success {
    color: #28a745;
}
.pssg-access-key-status.error {
    color: #dc3545;
}
</style>
