<?php
/**
 * DBA_TIS_Admin — TIS Strategic Targets Admin Panel
 *
 * WordPress admin page for managing TIS strategic targets.
 * Grouped by bot, with AJAX add/edit/delete.
 *
 * @since 2.21.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_TIS_Admin {

    private static $instance = null;

    public static function get_instance() {
        if ( null === self::$instance ) self::$instance = new self();
        return self::$instance;
    }

    private function __construct() {
        add_action( 'admin_menu', array( $this, 'register_menu' ), 14 );
        add_action( 'wp_ajax_dba_tis_save_targets', array( $this, 'ajax_save_targets' ) );
        add_action( 'wp_ajax_dba_tis_reset_defaults', array( $this, 'ajax_reset_defaults' ) );
        add_action( 'wp_ajax_dba_tis_delete_target', array( $this, 'ajax_delete_target' ) );
    }

    public function register_menu() {
        add_submenu_page(
            'dba-settings',
            'TIS Strategic Targets',
            '🎯 TIS Targets',
            'manage_options',
            'dba-tis-targets',
            array( $this, 'render_page' )
        );
    }

    /* ══════════════════════════════════════════════════════════════
     *  AJAX HANDLERS
     * ══════════════════════════════════════════════════════════════ */

    public function ajax_save_targets() {
        check_ajax_referer( 'dba_tis_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );

        $raw = isset( $_POST['targets'] ) ? stripslashes( $_POST['targets'] ) : '[]';
        $targets = json_decode( $raw, true );
        if ( ! is_array( $targets ) ) wp_send_json_error( 'Invalid JSON' );

        // Sanitize each target
        $clean = array();
        foreach ( $targets as $t ) {
            if ( empty( $t['id'] ) || empty( $t['label'] ) || empty( $t['target_bot'] ) ) continue;
            $clean[] = array(
                'id'          => sanitize_key( $t['id'] ),
                'label'       => sanitize_text_field( $t['label'] ),
                'topic_slug'  => sanitize_key( $t['topic_slug'] ?? '' ),
                'keywords'    => array_map( 'sanitize_text_field', $t['keywords'] ?? array() ),
                'priority'    => in_array( $t['priority'], array( 'critical', 'high', 'medium', 'low' ) ) ? $t['priority'] : 'medium',
                'target_bot'  => sanitize_key( $t['target_bot'] ),
                'min_pages'   => max( 1, intval( $t['min_pages'] ?? 5 ) ),
                'description' => sanitize_text_field( $t['description'] ?? '' ),
            );
        }

        if ( empty( $clean ) ) {
            wp_send_json_error( 'No valid targets after sanitization' );
        }

        DBA_TIS_Recommender::save_targets( $clean );
        wp_send_json_success( array( 'count' => count( $clean ), 'message' => count( $clean ) . ' targets saved.' ) );
    }

    public function ajax_reset_defaults() {
        check_ajax_referer( 'dba_tis_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );
        delete_option( DBA_TIS_Recommender::TARGETS_KEY );
        $defaults = DBA_TIS_Recommender::get_default_targets();
        wp_send_json_success( array( 'count' => count( $defaults ), 'targets' => $defaults ) );
    }

    public function ajax_delete_target() {
        check_ajax_referer( 'dba_tis_admin_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied' );
        $id = sanitize_key( $_POST['target_id'] ?? '' );
        if ( empty( $id ) ) wp_send_json_error( 'No target ID' );
        DBA_TIS_Recommender::remove_target( $id );
        wp_send_json_success( array( 'deleted' => $id ) );
    }

    /* ══════════════════════════════════════════════════════════════
     *  RENDER PAGE
     * ══════════════════════════════════════════════════════════════ */

    public function render_page() {
        if ( ! class_exists( 'DBA_TIS_Recommender' ) ) {
            echo '<div class="wrap"><h1>TIS Targets</h1><p style="color:red;">DBA_TIS_Recommender not loaded.</p></div>';
            return;
        }

        $targets = DBA_TIS_Recommender::get_targets();
        $nonce   = wp_create_nonce( 'dba_tis_admin_nonce' );

        // Group by bot
        $bots = array();
        foreach ( $targets as $t ) {
            $bot = $t['target_bot'] ?? 'luxstrat';
            if ( ! isset( $bots[ $bot ] ) ) $bots[ $bot ] = array();
            $bots[ $bot ][] = $t;
        }

        $bot_labels = array(
            'luxstrat'          => '🇬🇧 LuxStrat — EN Luxembourg Structuring',
            'comfisc-fr'        => '🇫🇷 Comfisc FR — French Accounting & Tax',
            'luxstrat-intl-fr'  => '🇫🇷 LuxStrat Intl FR — French Luxembourg Structuring',
            'luxstrat-intl-de'  => '🇩🇪 LuxStrat Intl DE — German Luxembourg Structuring',
            'luxstrat-intl-pt'  => '🇵🇹 LuxStrat Intl PT — Portuguese Luxembourg Structuring',
            'geobot'            => '🌍 GeoBot — Country-Specific Investment',
            'startup-hub'       => '🚀 Startup Hub — US Startup Content',
            'latam'             => '🌎 LATAM — Latin America Business',
            'eeurope'           => '🏛️ Eastern Europe — CEE Investment',
            'newsbot'           => '📰 NewsBot — PE/Capital Markets News',
        );

        // Priority colors
        $prio_colors = array(
            'critical' => '#dc3232',
            'high'     => '#f56e28',
            'medium'   => '#dba617',
            'low'      => '#7c8993',
        );

        ?>
        <div class="wrap">
        <h1>🎯 TIS Strategic Targets</h1>
        <p>Manage strategic targets for all bots. TIS scans the site weekly and generates recommendations based on these targets.</p>
        <p><strong>Total targets:</strong> <?php echo count( $targets ); ?> across <?php echo count( $bots ); ?> bots</p>

        <div style="margin:16px 0;">
            <button class="button button-primary" id="dba-tis-save-all">💾 Save All Changes</button>
            <button class="button" id="dba-tis-add-target">➕ Add New Target</button>
            <button class="button" id="dba-tis-reset-defaults" style="color:#dc3232;">🔄 Reset to Defaults</button>
            <span id="dba-tis-status" style="margin-left:12px;font-weight:bold;"></span>
        </div>

        <?php foreach ( $bot_labels as $bot_id => $bot_label ) :
            $bot_targets = $bots[ $bot_id ] ?? array();
        ?>
        <div class="dba-bot-section" data-bot="<?php echo esc_attr( $bot_id ); ?>" style="background:#fff;border:1px solid #ccd0d4;border-radius:4px;margin:16px 0;padding:0;">
            <div style="background:#f1f1f1;padding:10px 16px;border-bottom:1px solid #ccd0d4;display:flex;align-items:center;cursor:pointer;" class="dba-bot-header" onclick="this.parentNode.querySelector('.dba-bot-body').classList.toggle('dba-collapsed')">
                <strong style="font-size:14px;"><?php echo esc_html( $bot_label ); ?></strong>
                <span style="margin-left:auto;background:#0073aa;color:#fff;padding:2px 8px;border-radius:10px;font-size:11px;"><?php echo count( $bot_targets ); ?> targets</span>
            </div>
            <div class="dba-bot-body" style="padding:12px 16px;">
            <?php if ( empty( $bot_targets ) ) : ?>
                <p style="color:#999;font-style:italic;">No targets yet. Click "Add New Target" to add one for this bot.</p>
            <?php else : ?>
                <table class="wp-list-table widefat striped" style="font-size:12px;">
                <thead>
                    <tr>
                        <th style="width:20%;">Label</th>
                        <th style="width:10%;">Topic Slug</th>
                        <th style="width:30%;">Keywords</th>
                        <th style="width:8%;">Priority</th>
                        <th style="width:6%;">Min Pages</th>
                        <th style="width:18%;">Description</th>
                        <th style="width:8%;">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ( $bot_targets as $t ) :
                    $pc = $prio_colors[ $t['priority'] ] ?? '#999';
                ?>
                    <tr data-id="<?php echo esc_attr( $t['id'] ); ?>">
                        <td><input type="text" class="dba-t-label" value="<?php echo esc_attr( $t['label'] ); ?>" style="width:100%;font-size:12px;"></td>
                        <td><input type="text" class="dba-t-slug" value="<?php echo esc_attr( $t['topic_slug'] ); ?>" style="width:100%;font-size:11px;font-family:monospace;"></td>
                        <td><textarea class="dba-t-kw" style="width:100%;height:60px;font-size:11px;"><?php echo esc_textarea( implode( "\n", $t['keywords'] ?? array() ) ); ?></textarea></td>
                        <td>
                            <select class="dba-t-prio" style="font-size:11px;">
                                <?php foreach ( array( 'critical', 'high', 'medium', 'low' ) as $p ) : ?>
                                <option value="<?php echo $p; ?>" <?php selected( $t['priority'], $p ); ?>><?php echo ucfirst( $p ); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <td><input type="number" class="dba-t-min" value="<?php echo intval( $t['min_pages'] ); ?>" min="1" max="50" style="width:50px;font-size:12px;"></td>
                        <td><input type="text" class="dba-t-desc" value="<?php echo esc_attr( $t['description'] ); ?>" style="width:100%;font-size:11px;"></td>
                        <td>
                            <button class="button button-small dba-delete-target" data-id="<?php echo esc_attr( $t['id'] ); ?>" style="color:#dc3232;">✕</button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                </table>
            <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Add Target Modal -->
        <div id="dba-tis-modal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:99999;">
            <div style="background:#fff;max-width:600px;margin:80px auto;padding:24px;border-radius:8px;">
                <h3>➕ Add New Target</h3>
                <table class="form-table" style="font-size:13px;">
                    <tr><th>Bot</th><td><select id="dba-new-bot" style="width:100%;">
                        <?php foreach ( $bot_labels as $bid => $bl ) : ?>
                        <option value="<?php echo esc_attr( $bid ); ?>"><?php echo esc_html( $bl ); ?></option>
                        <?php endforeach; ?>
                    </select></td></tr>
                    <tr><th>Label</th><td><input type="text" id="dba-new-label" style="width:100%;" placeholder="e.g. Luxembourg RAIF (FR)"></td></tr>
                    <tr><th>Topic Slug</th><td><input type="text" id="dba-new-slug" style="width:100%;font-family:monospace;" placeholder="e.g. raif"></td></tr>
                    <tr><th>Keywords (one per line)</th><td><textarea id="dba-new-kw" style="width:100%;height:80px;" placeholder="RAIF Luxembourg&#10;créer RAIF&#10;fonds RAIF"></textarea></td></tr>
                    <tr><th>Priority</th><td><select id="dba-new-prio">
                        <option value="critical">Critical</option>
                        <option value="high" selected>High</option>
                        <option value="medium">Medium</option>
                        <option value="low">Low</option>
                    </select></td></tr>
                    <tr><th>Min Pages</th><td><input type="number" id="dba-new-min" value="5" min="1" max="50"></td></tr>
                    <tr><th>Description</th><td><input type="text" id="dba-new-desc" style="width:100%;" placeholder="Why this target matters"></td></tr>
                </table>
                <div style="margin-top:16px;">
                    <button class="button button-primary" id="dba-modal-add">Add Target</button>
                    <button class="button" id="dba-modal-close">Cancel</button>
                </div>
            </div>
        </div>

        <style>
            .dba-collapsed { display: none !important; }
        </style>

        <script>
        (function(){
            var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
            var nonce = '<?php echo $nonce; ?>';
            var $status = document.getElementById('dba-tis-status');

            function setStatus(msg, color) {
                $status.textContent = msg;
                $status.style.color = color || '#0073aa';
                setTimeout(function(){ $status.textContent = ''; }, 5000);
            }

            // Collect all targets from the DOM
            function collectTargets() {
                var targets = [];
                document.querySelectorAll('.dba-bot-section').forEach(function(section) {
                    var bot = section.dataset.bot;
                    section.querySelectorAll('tr[data-id]').forEach(function(row) {
                        var kw = row.querySelector('.dba-t-kw').value.split('\n').map(function(k){ return k.trim(); }).filter(Boolean);
                        targets.push({
                            id: row.dataset.id,
                            label: row.querySelector('.dba-t-label').value,
                            topic_slug: row.querySelector('.dba-t-slug').value,
                            keywords: kw,
                            priority: row.querySelector('.dba-t-prio').value,
                            target_bot: bot,
                            min_pages: parseInt(row.querySelector('.dba-t-min').value) || 5,
                            description: row.querySelector('.dba-t-desc').value
                        });
                    });
                });
                return targets;
            }

            // Save all
            document.getElementById('dba-tis-save-all').addEventListener('click', function() {
                var targets = collectTargets();
                if (targets.length === 0) { setStatus('No targets to save!', '#dc3232'); return; }
                setStatus('Saving ' + targets.length + ' targets...', '#0073aa');

                var fd = new FormData();
                fd.append('action', 'dba_tis_save_targets');
                fd.append('nonce', nonce);
                fd.append('targets', JSON.stringify(targets));

                fetch(ajaxurl, { method: 'POST', body: fd })
                    .then(function(r){ return r.json(); })
                    .then(function(data){
                        if (data.success) {
                            setStatus('✅ ' + data.data.message, '#46b450');
                        } else {
                            setStatus('❌ ' + (data.data || 'Save failed'), '#dc3232');
                        }
                    })
                    .catch(function(){ setStatus('❌ Network error', '#dc3232'); });
            });

            // Reset defaults
            document.getElementById('dba-tis-reset-defaults').addEventListener('click', function() {
                if (!confirm('Reset ALL targets to factory defaults? Custom targets will be lost.')) return;
                setStatus('Resetting...', '#0073aa');

                var fd = new FormData();
                fd.append('action', 'dba_tis_reset_defaults');
                fd.append('nonce', nonce);

                fetch(ajaxurl, { method: 'POST', body: fd })
                    .then(function(r){ return r.json(); })
                    .then(function(data){
                        if (data.success) {
                            setStatus('✅ Reset to ' + data.data.count + ' defaults. Reloading...', '#46b450');
                            setTimeout(function(){ location.reload(); }, 1000);
                        } else {
                            setStatus('❌ Reset failed', '#dc3232');
                        }
                    });
            });

            // Delete target
            document.querySelectorAll('.dba-delete-target').forEach(function(btn) {
                btn.addEventListener('click', function() {
                    if (!confirm('Delete this target?')) return;
                    var row = btn.closest('tr');
                    var id = btn.dataset.id;

                    var fd = new FormData();
                    fd.append('action', 'dba_tis_delete_target');
                    fd.append('nonce', nonce);
                    fd.append('target_id', id);

                    fetch(ajaxurl, { method: 'POST', body: fd })
                        .then(function(r){ return r.json(); })
                        .then(function(data){
                            if (data.success) {
                                row.remove();
                                setStatus('✅ Target deleted', '#46b450');
                            }
                        });
                });
            });

            // Add target modal
            document.getElementById('dba-tis-add-target').addEventListener('click', function() {
                document.getElementById('dba-tis-modal').style.display = 'block';
            });
            document.getElementById('dba-modal-close').addEventListener('click', function() {
                document.getElementById('dba-tis-modal').style.display = 'none';
            });
            document.getElementById('dba-modal-add').addEventListener('click', function() {
                var bot = document.getElementById('dba-new-bot').value;
                var label = document.getElementById('dba-new-label').value.trim();
                var slug = document.getElementById('dba-new-slug').value.trim();
                var kw = document.getElementById('dba-new-kw').value.split('\n').map(function(k){ return k.trim(); }).filter(Boolean);
                var prio = document.getElementById('dba-new-prio').value;
                var min = parseInt(document.getElementById('dba-new-min').value) || 5;
                var desc = document.getElementById('dba-new-desc').value.trim();

                if (!label || !slug || kw.length === 0) {
                    alert('Label, Topic Slug, and at least 1 keyword are required.');
                    return;
                }

                var id = slug.replace(/[^a-z0-9_]/g, '') + '_' + bot.replace(/-/g, '_') + '_' + Date.now().toString(36);

                // Find the bot section and append a new row
                var section = document.querySelector('.dba-bot-section[data-bot="' + bot + '"]');
                var body = section.querySelector('.dba-bot-body');
                var table = body.querySelector('table');
                if (!table) {
                    // No table yet — create one
                    body.innerHTML = '<table class="wp-list-table widefat striped" style="font-size:12px;">'
                        + '<thead><tr><th style="width:20%;">Label</th><th style="width:10%;">Topic Slug</th>'
                        + '<th style="width:30%;">Keywords</th><th style="width:8%;">Priority</th>'
                        + '<th style="width:6%;">Min Pages</th><th style="width:18%;">Description</th>'
                        + '<th style="width:8%;">Actions</th></tr></thead><tbody></tbody></table>';
                    table = body.querySelector('table');
                }
                var tbody = table.querySelector('tbody');
                var tr = document.createElement('tr');
                tr.dataset.id = id;
                tr.innerHTML = '<td><input type="text" class="dba-t-label" value="' + label.replace(/"/g, '&quot;') + '" style="width:100%;font-size:12px;"></td>'
                    + '<td><input type="text" class="dba-t-slug" value="' + slug + '" style="width:100%;font-size:11px;font-family:monospace;"></td>'
                    + '<td><textarea class="dba-t-kw" style="width:100%;height:60px;font-size:11px;">' + kw.join('\n') + '</textarea></td>'
                    + '<td><select class="dba-t-prio" style="font-size:11px;">'
                    + '<option value="critical"' + (prio==='critical'?' selected':'') + '>Critical</option>'
                    + '<option value="high"' + (prio==='high'?' selected':'') + '>High</option>'
                    + '<option value="medium"' + (prio==='medium'?' selected':'') + '>Medium</option>'
                    + '<option value="low"' + (prio==='low'?' selected':'') + '>Low</option>'
                    + '</select></td>'
                    + '<td><input type="number" class="dba-t-min" value="' + min + '" min="1" max="50" style="width:50px;font-size:12px;"></td>'
                    + '<td><input type="text" class="dba-t-desc" value="' + desc.replace(/"/g, '&quot;') + '" style="width:100%;font-size:11px;"></td>'
                    + '<td><button class="button button-small dba-delete-target" data-id="' + id + '" style="color:#dc3232;">✕</button></td>';
                tbody.appendChild(tr);

                // Wire delete for new row
                tr.querySelector('.dba-delete-target').addEventListener('click', function() {
                    if (confirm('Delete this target?')) tr.remove();
                });

                // Update count badge
                var badge = section.querySelector('.dba-bot-header span');
                var count = table.querySelectorAll('tr[data-id]').length;
                badge.textContent = count + ' targets';

                // Close modal and clear
                document.getElementById('dba-tis-modal').style.display = 'none';
                document.getElementById('dba-new-label').value = '';
                document.getElementById('dba-new-slug').value = '';
                document.getElementById('dba-new-kw').value = '';
                document.getElementById('dba-new-desc').value = '';

                setStatus('✅ Target added (click Save to persist)', '#f56e28');
            });
        })();
        </script>
        </div>
        <?php
    }
}
