<?php

if (!defined('ABSPATH')) { exit; }
?>
<div class="wrap aieo-erp-wrap" data-nonce="<?php echo esc_attr($nonce); ?>">
    <h1><?php esc_html_e('ERP Database', 'ai-eshop-optimizer'); ?></h1>
    <p class="description" style="max-width:840px;">
        <?php esc_html_e('Stored connections to external MariaDB databases — typically the ERP / physical-store database holding wp_s1erp_*, wp_product_sales_predictor, and a peer AI-eShop-Optimizer install. Other AIEO modules will use these connections to import sales data and compute cross-store metrics.', 'ai-eshop-optimizer'); ?>
    </p>

    <?php if (!$key_ok) : ?>
        <div class="notice notice-warning" style="margin-top:14px;">
            <p><strong><?php esc_html_e('Encryption key missing.', 'ai-eshop-optimizer'); ?></strong>
            <?php esc_html_e('Passwords cannot be stored until you add the AIEO_ERP_ENCRYPTION_KEY constant to your wp-config.php. Add the suggested line below (just above the "/* That\'s all, stop editing! */" line):', 'ai-eshop-optimizer'); ?></p>
            <pre style="background:#0f172a;color:#e2e8f0;padding:12px;border-radius:6px;overflow:auto;user-select:all;"><code>define( 'AIEO_ERP_ENCRYPTION_KEY', '<?php echo esc_html($suggested); ?>' );</code></pre>
            <p class="description">
                <?php esc_html_e('Treat this constant like a database password — keep it out of version control. If you rotate it later, every saved password will need to be re-entered.', 'ai-eshop-optimizer'); ?>
            </p>
        </div>
    <?php endif; ?>

    <h2 style="margin-top:24px;"><?php esc_html_e('Connections', 'ai-eshop-optimizer'); ?></h2>
    <table class="widefat striped" id="aieo-erp-connections-table">
        <thead>
            <tr>
                <th><?php esc_html_e('Name', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Host', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Database', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('User', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Default', 'ai-eshop-optimizer'); ?></th>
                <th><?php esc_html_e('Last test', 'ai-eshop-optimizer'); ?></th>
                <th style="width:280px;"><?php esc_html_e('Actions', 'ai-eshop-optimizer'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($connections)) : ?>
                <tr><td colspan="7"><em><?php esc_html_e('No connections yet. Add one below.', 'ai-eshop-optimizer'); ?></em></td></tr>
            <?php else : foreach ($connections as $c) :
                $last_status = !empty($c['last_test_ok']) ? '✓' : ($c['last_tested_at'] ? '✗' : '—');
                $last_when   = !empty($c['last_tested_at']) ? esc_html(mysql2date(get_option('date_format') . ' ' . get_option('time_format'), $c['last_tested_at'])) : '';
            ?>
                <tr data-connection-id="<?php echo (int) $c['id']; ?>">
                    <td><strong><?php echo esc_html($c['name']); ?></strong></td>
                    <td><code><?php echo esc_html($c['host']); ?>:<?php echo (int) $c['port']; ?></code></td>
                    <td><code><?php echo esc_html($c['db_name']); ?></code></td>
                    <td><code><?php echo esc_html($c['db_user']); ?></code></td>
                    <td><?php echo !empty($c['is_default']) ? '<span title="' . esc_attr__('default connection', 'ai-eshop-optimizer') . '">★</span>' : ''; ?></td>
                    <td><span class="aieo-erp-last-test"><?php echo esc_html($last_status . ' ' . $last_when); ?></span></td>
                    <td>
                        <button type="button" class="button button-small aieo-erp-test"><?php esc_html_e('Test', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="button button-small aieo-erp-edit"><?php esc_html_e('Edit', 'ai-eshop-optimizer'); ?></button>
                        <button type="button" class="button button-small button-link-delete aieo-erp-delete"><?php esc_html_e('Delete', 'ai-eshop-optimizer'); ?></button>
                    </td>
                </tr>
            <?php endforeach; endif; ?>
        </tbody>
    </table>

    <h2 style="margin-top:24px;"><span id="aieo-erp-form-title"><?php esc_html_e('Add a connection', 'ai-eshop-optimizer'); ?></span></h2>
    <form id="aieo-erp-form">
        <input type="hidden" name="id" value="0">
        <table class="form-table" role="presentation">
            <tbody>
                <tr>
                    <th scope="row"><label for="aieo-erp-name"><?php esc_html_e('Name', 'ai-eshop-optimizer'); ?></label></th>
                    <td><input type="text" id="aieo-erp-name" name="name" class="regular-text" placeholder="<?php esc_attr_e('e.g. Athens store ERP', 'ai-eshop-optimizer'); ?>" required></td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-host"><?php esc_html_e('Host', 'ai-eshop-optimizer'); ?></label></th>
                    <td>
                        <input type="text" id="aieo-erp-host" name="host" class="regular-text" placeholder="db.example.com" required>
                        <label for="aieo-erp-port" style="margin-left:10px;"><?php esc_html_e('Port', 'ai-eshop-optimizer'); ?></label>
                        <input type="number" id="aieo-erp-port" name="port" min="1" max="65535" value="3306" style="width:90px;">
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-db_name"><?php esc_html_e('Database', 'ai-eshop-optimizer'); ?></label></th>
                    <td><input type="text" id="aieo-erp-db_name" name="db_name" class="regular-text" required></td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-db_user"><?php esc_html_e('User', 'ai-eshop-optimizer'); ?></label></th>
                    <td><input type="text" id="aieo-erp-db_user" name="db_user" class="regular-text" autocomplete="off" required></td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-db_pass"><?php esc_html_e('Password', 'ai-eshop-optimizer'); ?></label></th>
                    <td>
                        <input type="password" id="aieo-erp-db_pass" name="db_pass" class="regular-text" autocomplete="new-password">
                        <p class="description"><?php esc_html_e('Encrypted at rest. Leave empty when editing to keep the stored password unchanged.', 'ai-eshop-optimizer'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-table_prefix"><?php esc_html_e('Table prefix', 'ai-eshop-optimizer'); ?></label></th>
                    <td>
                        <input type="text" id="aieo-erp-table_prefix" name="table_prefix" class="regular-text" value="wp_" style="width:140px;">
                        <p class="description"><?php esc_html_e('Used by helpers like $remote->prefix . "s1erp_temp_store_orders_table". Most installs use "wp_".', 'ai-eshop-optimizer'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-ssl_mode"><?php esc_html_e('SSL mode', 'ai-eshop-optimizer'); ?></label></th>
                    <td>
                        <select id="aieo-erp-ssl_mode" name="ssl_mode">
                            <option value="off"><?php esc_html_e('off — plaintext only (LAN/VPN)', 'ai-eshop-optimizer'); ?></option>
                            <option value="prefer" selected><?php esc_html_e('prefer — try TLS, accept plain', 'ai-eshop-optimizer'); ?></option>
                            <option value="require"><?php esc_html_e('require — refuse to connect without TLS', 'ai-eshop-optimizer'); ?></option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-is_default"><?php esc_html_e('Default', 'ai-eshop-optimizer'); ?></label></th>
                    <td>
                        <label><input type="checkbox" id="aieo-erp-is_default" name="is_default" value="1"> <?php esc_html_e('This is the default connection (used when no specific connection is requested).', 'ai-eshop-optimizer'); ?></label>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="aieo-erp-notes"><?php esc_html_e('Notes', 'ai-eshop-optimizer'); ?></label></th>
                    <td><textarea id="aieo-erp-notes" name="notes" class="large-text" rows="3" placeholder="<?php esc_attr_e('Free-text — purpose, contact person, etc.', 'ai-eshop-optimizer'); ?>"></textarea></td>
                </tr>
            </tbody>
        </table>
        <p class="submit">
            <button type="button" class="button button-secondary" id="aieo-erp-test-form"><?php esc_html_e('Test connection', 'ai-eshop-optimizer'); ?></button>
            <button type="submit" class="button button-primary" id="aieo-erp-save"<?php echo $key_ok ? '' : ' disabled'; ?>><?php esc_html_e('Save connection', 'ai-eshop-optimizer'); ?></button>
            <button type="button" class="button" id="aieo-erp-reset" style="display:none;"><?php esc_html_e('Cancel edit', 'ai-eshop-optimizer'); ?></button>
            <span id="aieo-erp-status" style="margin-left:12px;font-size:13px;color:#646970;"></span>
        </p>
    </form>
</div>

<script>
(function(){
    var wrap = document.querySelector('.aieo-erp-wrap'); if (!wrap) return;
    var nonce = wrap.getAttribute('data-nonce');
    var ajaxUrl = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';

    var form    = document.getElementById('aieo-erp-form');
    var status  = document.getElementById('aieo-erp-status');
    var title   = document.getElementById('aieo-erp-form-title');
    var resetBtn = document.getElementById('aieo-erp-reset');

    function setStatus(color, text){ status.style.color = color; status.textContent = text; }
    function post(action, data){
        var fd = new FormData();
        fd.set('action', action);
        fd.set('nonce', nonce);
        Object.keys(data || {}).forEach(function(k){ fd.set(k, data[k]); });
        return fetch(ajaxUrl, {method:'POST', credentials:'same-origin', body: fd}).then(function(r){return r.json();});
    }
    function readForm(){
        var fd = new FormData(form);
        var d  = {};
        fd.forEach(function(v, k){ d[k] = v; });
        d.is_default = form.querySelector('[name=is_default]').checked ? 1 : 0;
        return d;
    }
    function resetForm(){
        form.reset();
        form.querySelector('[name=id]').value = 0;
        title.textContent = '<?php echo esc_js(__('Add a connection', 'ai-eshop-optimizer')); ?>';
        resetBtn.style.display = 'none';
        setStatus('#646970', '');
    }

    // Save (or update) on submit.
    form.addEventListener('submit', function(e){
        e.preventDefault();
        setStatus('#646970', '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>');
        post('aieo_erp_save_connection', readForm()).then(function(j){
            if (j && j.success) {
                setStatus('#15803d', (j.data && j.data.message) || '<?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?>');
                setTimeout(function(){ location.reload(); }, 500);
            } else {
                setStatus('#b91c1c', (j && j.data && j.data.message) || '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>');
            }
        });
    });

    // Test from the form (works even before saving — useful first-time setup).
    document.getElementById('aieo-erp-test-form').addEventListener('click', function(){
        setStatus('#646970', '<?php echo esc_js(__('Testing…', 'ai-eshop-optimizer')); ?>');
        post('aieo_erp_test_connection', readForm()).then(function(j){
            if (j && j.success) {
                setStatus('#15803d', (j.data && j.data.message) || 'OK');
            } else {
                setStatus('#b91c1c', (j && j.data && j.data.message) || '<?php echo esc_js(__('Connection failed.', 'ai-eshop-optimizer')); ?>');
            }
        });
    });

    // Per-row Test / Edit / Delete.
    document.getElementById('aieo-erp-connections-table').addEventListener('click', function(e){
        var row = e.target.closest('tr[data-connection-id]'); if (!row) return;
        var id  = row.getAttribute('data-connection-id');

        if (e.target.classList.contains('aieo-erp-test')) {
            var span = row.querySelector('.aieo-erp-last-test');
            span.textContent = '…';
            post('aieo_erp_test_connection', {id: id}).then(function(j){
                if (j && j.success) {
                    span.textContent = '✓ ' + ((j.data && j.data.message) || '');
                    span.style.color = '#15803d';
                } else {
                    span.textContent = '✗ ' + ((j && j.data && j.data.message) || 'failed');
                    span.style.color = '#b91c1c';
                }
            });
            return;
        }

        if (e.target.classList.contains('aieo-erp-edit')) {
            // Pull the row's visible fields into the form. Password
            // intentionally NOT round-tripped — operator types it
            // again only if rotating it.
            form.querySelector('[name=id]').value = id;
            form.querySelector('[name=name]').value = row.cells[0].textContent.trim();
            var hostport = row.cells[1].textContent.trim().split(':');
            form.querySelector('[name=host]').value = hostport[0] || '';
            form.querySelector('[name=port]').value = hostport[1] || '3306';
            form.querySelector('[name=db_name]').value = row.cells[2].textContent.trim();
            form.querySelector('[name=db_user]').value = row.cells[3].textContent.trim();
            form.querySelector('[name=is_default]').checked = row.cells[4].textContent.trim() === '★';
            title.textContent = '<?php echo esc_js(__('Edit connection', 'ai-eshop-optimizer')); ?> — ' + form.querySelector('[name=name]').value;
            resetBtn.style.display = '';
            window.scrollTo({top: form.offsetTop - 60, behavior: 'smooth'});
            setStatus('#646970', '<?php echo esc_js(__('Editing — leave password empty to keep the stored one.', 'ai-eshop-optimizer')); ?>');
            return;
        }

        if (e.target.classList.contains('aieo-erp-delete')) {
            if (!confirm('<?php echo esc_js(__('Delete this connection? This does not affect the remote database — only the saved credentials here.', 'ai-eshop-optimizer')); ?>')) return;
            post('aieo_erp_delete_connection', {id: id}).then(function(j){
                if (j && j.success) { row.remove(); }
                else { alert((j && j.data && j.data.message) || 'delete failed'); }
            });
            return;
        }
    });

    resetBtn.addEventListener('click', resetForm);
})();
</script>
