<?php

namespace Unlockafe_addons\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

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

/**
 * Database CRUD Widget
 *
 * @since 1.0.0
 */
class Database_List extends Widget_Base
{
    public function get_name()
    {
        return 'unlockafe-database-list';
    }

    public function get_title()
    {
        return esc_html__('Database CRUD', 'unlock-addons-for-elementor');
    }

    public function get_icon()
    {
        return 'eicon-database ulicon';
    }

    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    public function get_keywords()
    {
        return ['database', 'table', 'list', 'data', 'api'];
    }

    public function get_script_depends()
    {
        return ['unlockafe-database-list-script'];
    }

    public function get_style_depends()
    {
        return ['unlockafe-database-list-style'];
    }

    protected function register_controls()
    {
        // Content Section
        $this->start_controls_section(
            'content_section',
            [
                'label' => esc_html__('Content', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        // Commented out - Table list and fields sections
        /*
        $this->add_control(
            'show_tables',
            [
                'label' => esc_html__('Show Tables', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_fields',
            [
                'label' => esc_html__('Show Fields', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'default' => 'yes',
            ]
        );
        */

        $this->add_control(
            'table_name',
            [
                'label' => esc_html__('Table Name', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '',
                'placeholder' => esc_html__('Enter table name', 'unlock-addons-for-elementor'),
                'description' => esc_html__('Enter the database table name to display data', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'items_per_page',
            [
                'label' => esc_html__('Items Per Page', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'default' => 10,
                'min' => 1,
                'max' => 100,
            ]
        );

        $this->add_control(
            'show_api_keys',
            [
                'label' => esc_html__('Show API Keys', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_api_docs',
            [
                'label' => esc_html__('Show API Documentation', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'unlock-addons-for-elementor'),
                'label_off' => esc_html__('No', 'unlock-addons-for-elementor'),
                'default' => 'yes',
                'separator' => 'before',
            ]
        );

        $this->end_controls_section();

        // Style Section
        $this->start_controls_section(
            'style_section',
            [
                'label' => esc_html__('Style', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'typography',
                'selector' => '{{WRAPPER}} .unlockafe-database-list',
            ]
        );

        $this->add_control(
            'text_color',
            [
                'label' => esc_html__('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-database-list' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'table_bg_color',
            [
                'label' => esc_html__('Table Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#ffffff',
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-database-list table' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'table_border',
                'selector' => '{{WRAPPER}} .unlockafe-database-list table, {{WRAPPER}} .unlockafe-database-list table td, {{WRAPPER}} .unlockafe-database-list table th',
            ]
        );

        $this->end_controls_section();
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $widget_id = 'unlockafe-db-list-' . $this->get_id();
        
        // Check if we're in Elementor editor or preview mode
        $is_editor_mode = \Elementor\Plugin::$instance->editor->is_edit_mode();
        $is_preview_mode = \Elementor\Plugin::$instance->preview->is_preview_mode();
        
        // Localize script for JavaScript
        wp_localize_script('unlockafe-database-list-script', 'unlockafeDatabaseList', [
            'restUrl' => rest_url('unlockafe-addons/v1/'),
            'nonce' => wp_create_nonce('wp_rest'),
        ]);
        
        ?>
        <div class="unlockafe-database-list" id="<?php echo esc_attr($widget_id); ?>" 
             data-table-name="<?php echo esc_attr($settings['table_name']); ?>"
             data-items-per-page="<?php echo esc_attr($settings['items_per_page']); ?>"
             data-show-api-keys="<?php echo esc_attr($settings['show_api_keys']); ?>"
             data-show-api-docs="<?php echo esc_attr($settings['show_api_docs']); ?>">
            <div class="db-list-container">
                <?php // Commented out - Database table and fields sections ?>
                <?php /*
                <?php if ($settings['show_tables'] === 'yes'): ?>
                    <div class="db-tables-section">
                        <h3><?php echo esc_html__('Database Tables', 'unlock-addons-for-elementor'); ?></h3>
                        <div class="db-tables-list">
                            <p class="loading-message"><?php echo esc_html__('Loading tables...', 'unlock-addons-for-elementor'); ?></p>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($settings['show_fields'] === 'yes'): ?>
                    <div class="db-fields-section">
                        <h3><?php echo esc_html__('Table Fields', 'unlock-addons-for-elementor'); ?></h3>
                        <div class="db-fields-list">
                            <p><?php echo esc_html__('Select a table to view fields', 'unlock-addons-for-elementor'); ?></p>
                        </div>
                    </div>
                <?php endif; ?>
                */ ?>
                <?php if ($settings['show_api_keys'] === 'yes'): ?>
                    <div class="db-api-keys-section">
                        <h3><?php echo esc_html__('API Keys', 'unlock-addons-for-elementor'); ?></h3>
                        <div class="db-api-keys-list">
                            <button type="button" class="generate-api-key-btn"><?php echo esc_html__('Generate New API Key', 'unlock-addons-for-elementor'); ?></button>
                            <div class="api-keys-container">
                                <p class="loading-message"><?php echo esc_html__('Loading API keys...', 'unlock-addons-for-elementor'); ?></p>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if ($settings['show_api_docs'] === 'yes'): ?>
                    <div class="db-api-docs-section">
                        <h3><?php echo esc_html__('API Documentation', 'unlock-addons-for-elementor'); ?></h3>
                        <div class="api-docs-content">
                            <div class="api-endpoint">
                                <h4>1. Store Data</h4>
                                <p><strong>Endpoint:</strong> POST <?php echo esc_url(rest_url('unlockafe-addons/v1/database/store')); ?></p>
                                <p><strong>Parameters:</strong></p>
                                <ul>
                                    <li><code>api_key</code> - Your API key (required, can be passed as URL parameter or in JSON body)</li>
                                    <li><code>table</code> - Table name (required)</li>
                                    <li><code>data</code> - Object with column-value pairs (required)</li>
                                </ul>
                                <pre class="api-code">POST <?php echo esc_url(rest_url('unlockafe-addons/v1/database/store')); ?>?api_key=YOUR_API_KEY
Content-Type: application/json

{
  "table": "your_table_name",
  "data": {
    "column1": "value1",
    "column2": "value2"
  }
}</pre>
                            </div>
                            
                            <div class="api-endpoint">
                                <h4>2. Get Data</h4>
                                <p><strong>Endpoint:</strong> GET <?php echo esc_url(rest_url('unlockafe-addons/v1/database/get')); ?></p>
                                <p><strong>Parameters:</strong></p>
                                <ul>
                                    <li><code>api_key</code> - Your API key (required, passed as URL parameter)</li>
                                    <li><code>table</code> - Table name (required)</li>
                                    <li><code>where</code> - JSON string with conditions (optional)</li>
                                    <li><code>limit</code> - Number of records (default: 100)</li>
                                    <li><code>offset</code> - Offset for pagination (default: 0)</li>
                                </ul>
                                <pre class="api-code">GET <?php echo esc_url(rest_url('unlockafe-addons/v1/database/get')); ?>?api_key=YOUR_API_KEY&table=your_table_name&where={"id":"123"}&limit=10</pre>
                            </div>
                            
                            <div class="api-endpoint">
                                <h4>3. Update Data</h4>
                                <p><strong>Endpoint:</strong> POST <?php echo esc_url(rest_url('unlockafe-addons/v1/database/update')); ?></p>
                                <p><strong>Parameters:</strong></p>
                                <ul>
                                    <li><code>api_key</code> - Your API key (required, can be passed as URL parameter or in JSON body)</li>
                                    <li><code>table</code> - Table name (required)</li>
                                    <li><code>data</code> - Object with column-value pairs to update (required)</li>
                                    <li><code>where</code> - Object with conditions to identify rows to update (required)</li>
                                </ul>
                                <pre class="api-code">POST <?php echo esc_url(rest_url('unlockafe-addons/v1/database/update')); ?>?api_key=YOUR_API_KEY
Content-Type: application/json

{
  "table": "your_table_name",
  "data": {
    "column1": "new_value1",
    "column2": "new_value2"
  },
  "where": {
    "id": "123"
  }
}</pre>
                            </div>
                            
                            <div class="api-endpoint">
                                <h4>4. Delete Data</h4>
                                <p><strong>Endpoint:</strong> DELETE <?php echo esc_url(rest_url('unlockafe-addons/v1/database/delete')); ?></p>
                                <p><strong>Parameters:</strong></p>
                                <ul>
                                    <li><code>api_key</code> - Your API key (required, can be passed as URL parameter or in JSON body)</li>
                                    <li><code>table</code> - Table name (required)</li>
                                    <li><code>where</code> - Object with conditions to identify rows to delete (required)</li>
                                </ul>
                                <pre class="api-code">DELETE <?php echo esc_url(rest_url('unlockafe-addons/v1/database/delete')); ?>?api_key=YOUR_API_KEY
Content-Type: application/json

{
  "table": "your_table_name",
  "where": {
    "id": "123"
  }
}</pre>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        
        // Add inline script for initialization
        if ($is_editor_mode || $is_preview_mode || !$is_editor_mode) {
            ?>
            <script type="text/javascript">
            (function() {
                function initDatabaseList() {
                    if (typeof jQuery === 'undefined') {
                        setTimeout(initDatabaseList, 100);
                        return;
                    }
                    
                    var $ = jQuery;
                    var $widget = $('#<?php echo esc_js($widget_id); ?>');
                    
                    if ($widget.length === 0) {
                        setTimeout(initDatabaseList, 100);
                        return;
                    }
                    
                    // Load database list
                    if ($widget.data('show-tables') === 'yes') {
                        loadDatabaseTables();
                    }
                    
                    if ($widget.data('show-api-keys') === 'yes') {
                        setTimeout(function() {
                            loadApiKeys();
                        }, 200);
                    }
                    
                    // Handle table click to show fields
                    $widget.on('click', '.db-table-item', function() {
                        var tableName = $(this).data('table');
                        if (tableName && $widget.data('show-fields') === 'yes') {
                            loadTableFields(tableName);
                        }
                    });
                    
                    // Handle API key generation
                    $widget.on('click', '.generate-api-key-btn', function() {
                        generateApiKey();
                    });
                    
                    // Define REST URL and nonce at the top level
                    var restUrl = '<?php echo esc_url(rest_url('unlockafe-addons/v1/')); ?>';
                    var restNonce = '<?php echo wp_create_nonce('wp_rest'); ?>';
                    
                    // Ensure restUrl is properly defined
                    if (!restUrl || restUrl === 'undefined' || restUrl.indexOf('undefined') !== -1) {
                        restUrl = '<?php echo esc_url(rest_url('unlockafe-addons/v1/')); ?>';
                    }
                    
                    function loadDatabaseTables() {
                        $.ajax({
                            url: restUrl + 'database/list',
                            method: 'GET',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', restNonce);
                            },
                            success: function(response) {
                                if (response.success && response.tables) {
                                    var html = '<ul class="db-tables-ul">';
                                    response.tables.forEach(function(table) {
                                        html += '<li class="db-table-item" data-table="' + table.name + '">';
                                        html += '<strong>' + table.name + '</strong>';
                                        html += '<span class="field-count">' + table.columns.length + ' fields</span>';
                                        html += '</li>';
                                    });
                                    html += '</ul>';
                                    $widget.find('.db-tables-list').html(html);
                                }
                            },
                            error: function() {
                                $widget.find('.db-tables-list').html('<p class="error"><?php echo esc_js(__('Failed to load tables', 'unlock-addons-for-elementor')); ?></p>');
                            }
                        });
                    }
                    
                    function loadTableFields(tableName) {
                        $.ajax({
                            url: restUrl + 'database/list',
                            method: 'GET',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', restNonce);
                            },
                            success: function(response) {
                                if (response.success && response.tables) {
                                    var table = response.tables.find(function(t) {
                                        return t.name === tableName;
                                    });
                                    
                                    if (table) {
                                        var html = '<table class="fields-table"><thead><tr>';
                                        html += '<th><?php echo esc_js(__('Field', 'unlock-addons-for-elementor')); ?></th>';
                                        html += '<th><?php echo esc_js(__('Type', 'unlock-addons-for-elementor')); ?></th>';
                                        html += '<th><?php echo esc_js(__('Null', 'unlock-addons-for-elementor')); ?></th>';
                                        html += '<th><?php echo esc_js(__('Key', 'unlock-addons-for-elementor')); ?></th>';
                                        html += '</tr></thead><tbody>';
                                        
                                        table.columns.forEach(function(col) {
                                            html += '<tr>';
                                            html += '<td><strong>' + col.field + '</strong></td>';
                                            html += '<td>' + col.type + '</td>';
                                            html += '<td>' + col.null + '</td>';
                                            html += '<td>' + (col.key || '-') + '</td>';
                                            html += '</tr>';
                                        });
                                        
                                        html += '</tbody></table>';
                                        $widget.find('.db-fields-list').html(html);
                                    }
                                }
                            }
                        });
                    }
                    
                    function loadApiKeys() {
                        $.ajax({
                            url: restUrl + 'database/api-keys',
                            method: 'GET',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', restNonce);
                            },
                            success: function(response) {
                                if (response.success && response.keys) {
                                    if (response.keys.length === 0) {
                                        $widget.find('.api-keys-container').html('<p><?php echo esc_js(__('No API keys found. Generate one using the button above.', 'unlock-addons-for-elementor')); ?></p>');
                                    } else {
                                        var html = '';
                                        response.keys.forEach(function(keyData) {
                                            // Get full key from stored keys (we need to fetch it from server)
                                            var fullKey = keyData.full_key || keyData.masked_key;
                                            html += '<div class="api-key-item" data-api-key="' + (keyData.full_key || '') + '">';
                                            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
                                            html += '<strong>' + (keyData.name || 'Unnamed Key') + '</strong>';
                                            html += '<button type="button" class="delete-api-key-btn" data-api-key="' + (keyData.full_key || '') + '" title="<?php echo esc_js(__('Delete', 'unlock-addons-for-elementor')); ?>">×</button>';
                                            html += '</div>';
                                            html += '<div class="api-key-value" data-full-key="' + (keyData.full_key || '') + '">' + (keyData.full_key || keyData.masked_key) + '</div>';
                                            html += '<div style="margin-top:8px;">';
                                            html += '<button type="button" class="copy-api-key-btn" data-copy="' + (keyData.full_key || keyData.masked_key) + '"><?php echo esc_js(__('Copy API Key', 'unlock-addons-for-elementor')); ?></button>';
                                            html += '<span class="copy-status" style="margin-left:10px;font-size:12px;color:#10b981;display:none;"><?php echo esc_js(__('Copied!', 'unlock-addons-for-elementor')); ?></span>';
                                            html += '</div>';
                                            html += '<p style="margin-top: 8px; font-size: 12px; color: #6b7280;">';
                                            html += 'Status: ' + (keyData.active ? 'Active' : 'Inactive');
                                            if (keyData.created) {
                                                html += ' | Created: ' + keyData.created;
                                            }
                                            html += '</p>';
                                            html += '</div>';
                                        });
                                        $widget.find('.api-keys-container').html(html);
                                    }
                                }
                            },
                            error: function() {
                                $widget.find('.api-keys-container').html('<p class="error"><?php echo esc_js(__('Failed to load API keys', 'unlock-addons-for-elementor')); ?></p>');
                            }
                        });
                    }
                    
                    function generateApiKey() {
                        var keyName = prompt('<?php echo esc_js(__('Enter a name for this API key:', 'unlock-addons-for-elementor')); ?>');
                        if (!keyName || keyName.trim() === '') {
                            alert('<?php echo esc_js(__('Name is required', 'unlock-addons-for-elementor')); ?>');
                            return;
                        }
                        
                        $.ajax({
                            url: restUrl + 'database/generate-key',
                            method: 'POST',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', restNonce);
                                xhr.setRequestHeader('Content-Type', 'application/json');
                            },
                            data: JSON.stringify({name: keyName.trim()}),
                            success: function(response) {
                                if (response.success) {
                                    // Show newly generated key with Copy and Delete buttons
                                    var html = '';
                                    html += '<div class="api-key-item" data-api-key="' + response.api_key + '">';
                                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
                                    html += '<strong>' + (response.name || 'Unnamed Key') + '</strong>';
                                    html += '<button type="button" class="delete-api-key-btn" data-api-key="' + response.api_key + '" title="<?php echo esc_js(__('Delete', 'unlock-addons-for-elementor')); ?>">×</button>';
                                    html += '</div>';
                                    html += '<div class="api-key-value" data-full-key="' + response.api_key + '">' + response.api_key + '</div>';
                                    html += '<div style="margin-top:8px;">';
                                    html += '<button type="button" class="copy-api-key-btn" data-copy="' + response.api_key + '"><?php echo esc_js(__('Copy API Key', 'unlock-addons-for-elementor')); ?></button>';
                                    html += '<span class="copy-status" style="margin-left:10px;font-size:12px;color:#10b981;display:none;"><?php echo esc_js(__('Copied!', 'unlock-addons-for-elementor')); ?></span>';
                                    html += '</div>';
                                    html += '<p style="margin-top: 8px; font-size: 12px; color: #6b7280;"><?php echo esc_js(__('Copy this key now. It will be shown in the list below.', 'unlock-addons-for-elementor')); ?></p>';
                                    html += '</div>';
                                    
                                    $widget.find('.api-keys-container').prepend(html);
                                    
                                    // Refresh list after a short delay
                                    setTimeout(function(){ loadApiKeys(); }, 500);
                                }
                            },
                            error: function() {
                                alert('<?php echo esc_js(__('Failed to generate API key', 'unlock-addons-for-elementor')); ?>');
                            }
                        });
                    }
                    
                    function deleteApiKey(apiKey) {
                        if (!confirm('<?php echo esc_js(__('Are you sure you want to delete this API key?', 'unlock-addons-for-elementor')); ?>')) {
                            return;
                        }
                        
                        $.ajax({
                            url: restUrl + 'database/api-keys/delete',
                            method: 'DELETE',
                            beforeSend: function(xhr) {
                                xhr.setRequestHeader('X-WP-Nonce', restNonce);
                                xhr.setRequestHeader('Content-Type', 'application/json');
                            },
                            data: JSON.stringify({api_key: apiKey}),
                            success: function(response) {
                                if (response.success) {
                                    // Remove the item from DOM
                                    $widget.find('.api-key-item[data-api-key="' + apiKey + '"]').fadeOut(300, function() {
                                        $(this).remove();
                                        // Reload list if empty
                                        if ($widget.find('.api-key-item').length === 0) {
                                            loadApiKeys();
                                        }
                                    });
                                }
                            },
                            error: function() {
                                alert('<?php echo esc_js(__('Failed to delete API key', 'unlock-addons-for-elementor')); ?>');
                            }
                        });
                    }
                    
                    // Delete API key handler
                    $widget.on('click', '.delete-api-key-btn', function() {
                        var apiKey = $(this).data('api-key') || $(this).attr('data-api-key');
                        if (apiKey) {
                            deleteApiKey(apiKey);
                        }
                    });

                    // Copy API key handler
                    $widget.on('click', '.copy-api-key-btn', function() {
                        var $btn = $(this);
                        var key = $btn.attr('data-copy') || '';
                        var $status = $btn.siblings('.copy-status');
                        if (!key) return;

                        function showCopied() {
                            if ($status.length) {
                                $status.stop(true, true).show();
                                setTimeout(function(){ $status.fadeOut(200); }, 1200);
                            }
                        }

                        if (navigator.clipboard && window.isSecureContext) {
                            navigator.clipboard.writeText(key).then(showCopied).catch(function() {
                                // fallback
                                var $tmp = $('<textarea>').val(key).appendTo('body').select();
                                try { document.execCommand('copy'); } catch(e) {}
                                $tmp.remove();
                                showCopied();
                            });
                        } else {
                            // fallback for non-secure contexts / older browsers
                            var $tmp2 = $('<textarea>').val(key).appendTo('body').select();
                            try { document.execCommand('copy'); } catch(e) {}
                            $tmp2.remove();
                            showCopied();
                        }
                    });
                }
                
                // Start initialization
                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', function() {
                        setTimeout(initDatabaseList, 100);
                    });
                } else {
                    setTimeout(initDatabaseList, 100);
                }
            })();
            </script>
            <?php
        }
    }
}
