<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_DMM_Campaigns_Admin extends AIEO_DMM_Module_Base {

    public function get_id()       { return 'campaigns'; }
    public function get_label()    { return __('Advertising campaigns', 'ai-eshop-optimizer'); }
    public function get_priority() { return 20; } 
    public function get_group()    { return 'attribution'; }

    public function register_hooks() {
        add_action('wp_ajax_aieo_dmm_campaign_save', array($this, 'ajax_save'));
    }

    public function render_subtab() {
        $base_url = admin_url('admin.php?page=' . AIEO_DMM::MENU_SLUG . '&dmm_tab=' . $this->get_id());
        $edit_id  = isset($_GET['campaign_id']) ? (int) $_GET['campaign_id'] : 0;

        echo '<div class="aieo-dmm-section">';
        echo '<h2>' . esc_html__('Advertising campaigns', 'ai-eshop-optimizer') . '</h2>';
        echo '<p class="description">' . esc_html__('Auto-created on first sight of a new utm_campaign value. Fresh rows arrive in the &#8220;auto_draft&#8221; status &mdash; promote to live after enriching the metadata.', 'ai-eshop-optimizer') . '</p>';

        if ($edit_id > 0) {
            $this->render_edit($edit_id, $base_url);
        } else {
            $this->render_list($base_url);
        }
        echo '</div>';
    }

    
    
    

    private function render_list($base_url) {
        global $wpdb;
        $tbl  = $wpdb->prefix . 'aieo_dmm_campaigns';
        $sess = $wpdb->prefix . 'aieo_sessions_statics';
        $os   = $wpdb->prefix . 'aieo_order_stats';      
        $led  = $wpdb->prefix . 'aieo_attribution_cost'; 

        $status = isset($_GET['status']) ? sanitize_key((string) $_GET['status']) : '';
        $allowed_status = array('auto_draft', 'draft', 'live', 'paused', 'archived');
        $where = '';
        if (in_array($status, $allowed_status, true)) {
            $where = $wpdb->prepare('WHERE c.status = %s', $status);
        }

        
        $counts = $wpdb->get_results(
            "SELECT status, COUNT(*) AS n FROM {$tbl} GROUP BY status",
            ARRAY_A
        );
        $count_map = array();
        foreach ((array) $counts as $r) { $count_map[(string) $r['status']] = (int) $r['n']; }

        echo '<p style="margin:6px 0 14px;">';
        $total_all = array_sum($count_map);
        $tabs = array(
            
            ''           => sprintf(__('All (%d)', 'ai-eshop-optimizer'), $total_all),
            
            'auto_draft' => sprintf(__('Auto-draft (%d)', 'ai-eshop-optimizer'), (int) ($count_map['auto_draft'] ?? 0)),
            
            'live'       => sprintf(__('Live (%d)', 'ai-eshop-optimizer'),       (int) ($count_map['live'] ?? 0)),
            
            'paused'     => sprintf(__('Paused (%d)', 'ai-eshop-optimizer'),     (int) ($count_map['paused'] ?? 0)),
            
            'archived'   => sprintf(__('Archived (%d)', 'ai-eshop-optimizer'),   (int) ($count_map['archived'] ?? 0)),
        );
        $first = true;
        foreach ($tabs as $slug => $label) {
            if (!$first) { echo ' <span style="color:#9ca3af;">|</span> '; }
            $first = false;
            $url = $slug === '' ? $base_url : $base_url . '&status=' . urlencode($slug);
            $is_active = ($status === $slug) || ($status === '' && $slug === '');
            $style = $is_active ? 'font-weight:600;color:#111827;text-decoration:none;' : '';
            echo '<a href="' . esc_url($url) . '" style="' . esc_attr($style) . '">' . esc_html($label) . '</a>';
        }
        echo '</p>';

        
        
        $sessions_present = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $sess)) === $sess);
        $os_present       = ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $os)) === $os);

        
        
        
        
        
        
        
        
        
        $CO = 'COLLATE utf8mb4_unicode_520_ci';
        $rows_sql = "SELECT c.*,
                            sess.sessions    AS sessions,
                            sess.last_seen   AS last_seen,
                            os.orders        AS orders,
                            os.revenue       AS revenue,
                            os.cancels       AS cancels,
                            os.revenue_lost  AS revenue_lost,
                            led.ledger_spent AS ledger_spent
                       FROM {$tbl} c
                  LEFT JOIN (
                       SELECT entry_campaign_id,
                              COUNT(*)        AS sessions,
                              MAX(updated_at) AS last_seen
                         FROM {$sess}
                        WHERE entry_campaign_id IS NOT NULL
                        GROUP BY entry_campaign_id
                  ) sess ON sess.entry_campaign_id = c.id
                  LEFT JOIN (
                       SELECT REPLACE(orderutmcampaign,'+',' ') AS cname,
                              COUNT(*)                                                       AS orders,
                              COALESCE(SUM(orderspend),0)                                    AS revenue,
                              SUM(CASE WHEN orderstatus='cancelled' THEN 1 ELSE 0 END)       AS cancels,
                              COALESCE(SUM(CASE WHEN orderstatus='cancelled' THEN orderspend ELSE 0 END),0) AS revenue_lost
                         FROM {$os}
                        WHERE orderutmcampaign IS NOT NULL AND orderutmcampaign <> ''
                        GROUP BY REPLACE(orderutmcampaign,'+',' ')
                  ) os ON os.cname {$CO} = REPLACE(c.slug,'+',' ') {$CO}
                  LEFT JOIN (
                       SELECT REPLACE(dimension_value,'+',' ') AS cname,
                              COALESCE(SUM(amount),0) AS ledger_spent
                         FROM {$led}
                        WHERE dimension_type = 'campaign'
                        GROUP BY REPLACE(dimension_value,'+',' ')
                  ) led ON led.cname {$CO} = REPLACE(c.slug,'+',' ') {$CO}
                  {$where}
                  ORDER BY (os.revenue IS NULL OR os.revenue = 0), os.revenue DESC, sess.last_seen DESC, c.id DESC
                  LIMIT 500";
        if (!$sessions_present || !$os_present) {
            
            $rows_sql = "SELECT c.*, NULL AS sessions, NULL AS last_seen, NULL AS orders, NULL AS revenue,
                                NULL AS cancels, NULL AS revenue_lost, NULL AS ledger_spent
                           FROM {$tbl} c {$where}
                          ORDER BY c.updated_at DESC LIMIT 500";
        }
        $rows = $wpdb->get_results($rows_sql, ARRAY_A);

        if (empty($rows)) {
            echo '<p>' . esc_html__('No campaigns yet. They will appear here automatically the first time a visitor lands with a utm_campaign URL parameter.', 'ai-eshop-optimizer') . '</p>';
            return;
        }

        echo '<table class="wp-list-table widefat striped" style="font-size:12px;"><thead><tr>';
        echo '<th>' . esc_html__('Slug', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Label', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Status', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Channel', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Sessions', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Orders', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Revenue (€)', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Spent (€)', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('ROAS', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Cancels', 'ai-eshop-optimizer') . '</th>';
        echo '<th>' . esc_html__('Last seen', 'ai-eshop-optimizer') . '</th>';
        echo '<th></th></tr></thead><tbody>';

        foreach ($rows as $r) {
            $sessions = (int) ($r['sessions'] ?? 0);
            $orders   = (int) ($r['orders'] ?? 0);
            $revenue  = (float) ($r['revenue'] ?? 0);
            
            
            $ledger_spent = isset($r['ledger_spent']) && $r['ledger_spent'] !== null ? (float) $r['ledger_spent'] : 0.0;
            $manual_spent = isset($r['budget_spent']) && $r['budget_spent'] !== null && $r['budget_spent'] !== '' ? (float) $r['budget_spent'] : null;
            $spent    = $ledger_spent > 0 ? $ledger_spent : $manual_spent;
            $roas     = ($spent && $spent > 0) ? round($revenue / $spent, 2) : null;
            $cancels  = (int) ($r['cancels'] ?? 0);
            $cancel_rate = $orders > 0 ? round($cancels / max($orders, 1) * 100, 1) : 0;
            $status_color = array(
                'auto_draft' => '#ca8a04',
                'draft'      => '#6b7280',
                'live'       => '#16a34a',
                'paused'     => '#dc2626',
                'archived'   => '#9ca3af',
            );
            $sc = $status_color[(string) $r['status']] ?? '#374151';
            echo '<tr>';
            echo '<td><code style="font-size:11px;">' . esc_html((string) $r['slug']) . '</code></td>';
            echo '<td>' . esc_html((string) $r['label']) . '</td>';
            echo '<td><span style="font-weight:600;color:' . esc_attr($sc) . ';">' . esc_html((string) $r['status']) . '</span></td>';
            echo '<td>' . esc_html((string) ($r['channel_hint'] ?? '—')) . '</td>';
            echo '<td>' . esc_html(number_format_i18n($sessions)) . '</td>';
            echo '<td>' . esc_html(number_format_i18n($orders)) . '</td>';
            echo '<td>' . esc_html(number_format_i18n($revenue, 2)) . '</td>';
            echo '<td>' . ($spent !== null ? esc_html(number_format_i18n($spent, 2)) : '—') . '</td>';
            echo '<td>' . ($roas !== null ? esc_html(number_format_i18n($roas, 2)) . '×' : '—') . '</td>';
            echo '<td>' . ($cancels > 0 ? esc_html($cancels . ' (' . $cancel_rate . '%)') : '—') . '</td>';
            echo '<td>' . esc_html((string) ($r['last_seen'] ?? '—')) . '</td>';
            echo '<td><a class="button button-small" href="' . esc_url($base_url . '&campaign_id=' . (int) $r['id']) . '">' . esc_html__('Edit', 'ai-eshop-optimizer') . '</a></td>';
            echo '</tr>';
        }
        echo '</tbody></table>';
    }

    
    
    

    private function render_edit($id, $base_url) {
        $row = AIEO_DMM_Campaigns::get($id);
        if (!$row) {
            echo '<p>' . esc_html__('Campaign not found.', 'ai-eshop-optimizer') . '</p>';
            echo '<p><a href="' . esc_url($base_url) . '">&larr; ' . esc_html__('Back to list', 'ai-eshop-optimizer') . '</a></p>';
            return;
        }

        $nonce = wp_create_nonce(AIEO_DMM::NONCE_ACTION);
        $ajax  = admin_url('admin-ajax.php');
        $statuses = array('auto_draft', 'draft', 'live', 'paused', 'archived');
        $objectives = array('' => '—', 'acquisition' => 'Acquisition', 'retention' => 'Retention', 'win_back' => 'Win-back', 'brand' => 'Brand');

        echo '<p><a href="' . esc_url($base_url) . '">&larr; ' . esc_html__('Back to list', 'ai-eshop-optimizer') . '</a></p>';
        echo '<div class="aieo-dmm-card">';
        echo '<h3>' . esc_html((string) $row['label']) . ' <code style="font-size:12px;font-weight:normal;color:#6b7280;">' . esc_html((string) $row['slug']) . '</code></h3>';

        echo '<form id="aieo-camp-form">';
        echo '<input type="hidden" name="id" value="' . (int) $row['id'] . '">';

        echo '<table class="form-table"><tbody>';
        echo '<tr><th><label for="aieo-camp-label">' . esc_html__('Label', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="text" class="regular-text" id="aieo-camp-label" name="label" value="' . esc_attr((string) $row['label']) . '"></td></tr>';

        echo '<tr><th><label for="aieo-camp-status">' . esc_html__('Status', 'ai-eshop-optimizer') . '</label></th><td><select id="aieo-camp-status" name="status">';
        foreach ($statuses as $s) {
            echo '<option value="' . esc_attr($s) . '" ' . selected((string) $row['status'], $s, false) . '>' . esc_html($s) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th><label for="aieo-camp-objective">' . esc_html__('Objective', 'ai-eshop-optimizer') . '</label></th><td><select id="aieo-camp-objective" name="objective">';
        foreach ($objectives as $key => $label) {
            echo '<option value="' . esc_attr($key) . '" ' . selected((string) ($row['objective'] ?? ''), $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th><label for="aieo-camp-channel">' . esc_html__('Channel hint', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="text" class="regular-text" id="aieo-camp-channel" name="channel_hint" value="' . esc_attr((string) ($row['channel_hint'] ?? '')) . '" placeholder="e.g. paid_google, paid_facebook, newsletter"></td></tr>';

        echo '<tr><th><label for="aieo-camp-start">' . esc_html__('Start date', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="date" id="aieo-camp-start" name="start_at" value="' . esc_attr(substr((string) ($row['start_at'] ?? ''), 0, 10)) . '"></td></tr>';

        echo '<tr><th><label for="aieo-camp-end">' . esc_html__('End date', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="date" id="aieo-camp-end" name="end_at" value="' . esc_attr(substr((string) ($row['end_at'] ?? ''), 0, 10)) . '"></td></tr>';

        echo '<tr><th><label for="aieo-camp-bp">' . esc_html__('Budget planned (€)', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="number" step="0.01" min="0" id="aieo-camp-bp" name="budget_planned" value="' . esc_attr((string) ($row['budget_planned'] ?? '')) . '"></td></tr>';

        echo '<tr><th><label for="aieo-camp-bs">' . esc_html__('Budget spent (€)', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><input type="number" step="0.01" min="0" id="aieo-camp-bs" name="budget_spent" value="' . esc_attr((string) ($row['budget_spent'] ?? '')) . '"> <span class="description">' . esc_html__('Used as the denominator for ROAS.', 'ai-eshop-optimizer') . '</span></td></tr>';

        echo '<tr><th><label for="aieo-camp-notes">' . esc_html__('Notes', 'ai-eshop-optimizer') . '</label></th>';
        echo '<td><textarea id="aieo-camp-notes" name="notes" rows="3" class="large-text">' . esc_textarea((string) ($row['notes'] ?? '')) . '</textarea></td></tr>';

        echo '</tbody></table>';
        echo '<p><button type="button" class="button button-primary" id="aieo-camp-save">' . esc_html__('Save', 'ai-eshop-optimizer') . '</button> '
           . '<span class="description" id="aieo-camp-msg" style="margin-left:8px;"></span></p>';
        echo '</form>';
        echo '</div>';

        ?>
        <script>
        (function(){
            var NONCE = <?php echo wp_json_encode($nonce); ?>;
            var AJAX  = <?php echo wp_json_encode($ajax); ?>;
            var btn = document.getElementById('aieo-camp-save');
            var msg = document.getElementById('aieo-camp-msg');
            btn.addEventListener('click', function(){
                var fd = new FormData(document.getElementById('aieo-camp-form'));
                fd.append('action', 'aieo_dmm_campaign_save');
                fd.append('nonce', NONCE);
                msg.textContent = '<?php echo esc_js(__('Saving…', 'ai-eshop-optimizer')); ?>';
                fetch(AJAX, {method:'POST',credentials:'same-origin',body:fd}).then(function(r){return r.json();}).then(function(j){
                    if (j && j.success) { msg.textContent = '<?php echo esc_js(__('Saved.', 'ai-eshop-optimizer')); ?>'; }
                    else { msg.textContent = (j && j.data && j.data.message) || '<?php echo esc_js(__('Save failed.', 'ai-eshop-optimizer')); ?>'; }
                });
            });
        })();
        </script>
        <?php
    }

    
    
    

    public function ajax_save() {
        AIEO_DMM::verify_ajax_request();
        $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
        if ($id <= 0) { wp_send_json_error(array('message' => __('Missing id.', 'ai-eshop-optimizer'))); }

        $patch = array();
        foreach (array('label', 'status', 'objective', 'channel_hint', 'start_at', 'end_at', 'budget_planned', 'budget_spent', 'notes') as $field) {
            if (isset($_POST[$field])) {
                $patch[$field] = wp_unslash($_POST[$field]);
            }
        }
        AIEO_DMM_Campaigns::save($id, $patch);
        wp_send_json_success();
    }
}
