<?php

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

class AIEO_DMM_Campaigns {

    const CACHE_GROUP = 'aieo_dmm';
    const CACHE_TTL   = HOUR_IN_SECONDS;

    
    private static $slug_to_id_cache = null;

    public static function table() {
        global $wpdb;
        return $wpdb->prefix . 'aieo_dmm_campaigns';
    }

    
    public static function touch($slug, $channel_hint = null) {
        $slug = trim((string) $slug);
        if ($slug === '') { return null; }
        $slug = mb_substr($slug, 0, 120);

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        if (strpos($slug, '{{') !== false || strpos($slug, '}}') !== false) {
            return null;
        }
        if (strpos($slug, 'aieo_internal_') === 0) {
            return null;
        }
        $literal_placeholders = array(
            'campaign_name', 'campaign.name',
            '{campaign_name}', '[campaign_name]',
            '{campaign.name}', '[campaign.name]',
        );
        if (in_array(strtolower($slug), $literal_placeholders, true)) {
            return null;
        }

        
        if (self::$slug_to_id_cache !== null && isset(self::$slug_to_id_cache[$slug])) {
            return (int) self::$slug_to_id_cache[$slug];
        }
        $cached = wp_cache_get('aieo_camp:' . $slug, self::CACHE_GROUP);
        if (is_numeric($cached) && (int) $cached > 0) {
            self::$slug_to_id_cache[$slug] = (int) $cached;
            return (int) $cached;
        }

        global $wpdb;
        $tbl = self::table();

        
        $id = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$tbl} WHERE slug = %s LIMIT 1",
            $slug
        ));
        if ($id > 0) {
            wp_cache_set('aieo_camp:' . $slug, $id, self::CACHE_GROUP, self::CACHE_TTL);
            self::$slug_to_id_cache[$slug] = $id;
            return $id;
        }

        
        $now = current_time('mysql', true);
        $hint = $channel_hint ? mb_substr((string) $channel_hint, 0, 40) : null;
        $wpdb->insert($tbl, array(
            'slug'         => $slug,
            'label'        => $slug,                 
            'channel_hint' => $hint,
            'status'       => 'auto_draft',
            'created_at'   => $now,
            'updated_at'   => $now,
        ));
        $id = (int) $wpdb->insert_id;
        if ($id > 0) {
            wp_cache_set('aieo_camp:' . $slug, $id, self::CACHE_GROUP, self::CACHE_TTL);
            self::$slug_to_id_cache[$slug] = $id;
        }
        return $id ?: null;
    }

    
    public static function id_for_slug($slug) {
        $slug = trim((string) $slug);
        if ($slug === '') { return null; }
        if (self::$slug_to_id_cache !== null && isset(self::$slug_to_id_cache[$slug])) {
            return (int) self::$slug_to_id_cache[$slug];
        }
        global $wpdb;
        $id = (int) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM " . self::table() . " WHERE slug = %s LIMIT 1",
            $slug
        ));
        if ($id > 0) { self::$slug_to_id_cache[$slug] = $id; }
        return $id ?: null;
    }

    
    public static function get($id) {
        $id = (int) $id;
        if ($id <= 0) { return null; }
        global $wpdb;
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM " . self::table() . " WHERE id = %d LIMIT 1",
            $id
        ), ARRAY_A);
        return is_array($row) ? $row : null;
    }

    
    public static function save($id, array $patch) {
        global $wpdb;
        $id = (int) $id;
        if ($id <= 0) { return false; }

        $clean = array();
        if (array_key_exists('label', $patch))          { $clean['label']          = sanitize_text_field((string) $patch['label']); }
        if (array_key_exists('channel_hint', $patch))   { $clean['channel_hint']   = $patch['channel_hint'] !== '' ? sanitize_key((string) $patch['channel_hint']) : null; }
        if (array_key_exists('objective', $patch))      { $clean['objective']      = $patch['objective'] !== '' ? sanitize_key((string) $patch['objective']) : null; }
        if (array_key_exists('status', $patch))         {
            $allowed = array('auto_draft','draft','live','paused','archived');
            $s = sanitize_key((string) $patch['status']);
            $clean['status'] = in_array($s, $allowed, true) ? $s : 'live';
        }
        if (array_key_exists('start_at', $patch))       { $clean['start_at']       = $patch['start_at'] ?: null; }
        if (array_key_exists('end_at', $patch))         { $clean['end_at']         = $patch['end_at'] ?: null; }
        if (array_key_exists('budget_planned', $patch)) { $clean['budget_planned'] = is_numeric($patch['budget_planned']) ? (float) $patch['budget_planned'] : null; }
        if (array_key_exists('budget_spent', $patch))   { $clean['budget_spent']   = is_numeric($patch['budget_spent'])   ? (float) $patch['budget_spent']   : null; }
        if (array_key_exists('notes', $patch))          { $clean['notes']          = wp_kses_post((string) $patch['notes']); }
        if (empty($clean))                              { return true; }

        $wpdb->update(self::table(), $clean, array('id' => $id));

        
        $slug = (string) $wpdb->get_var($wpdb->prepare(
            "SELECT slug FROM " . self::table() . " WHERE id = %d",
            $id
        ));
        if ($slug !== '') {
            wp_cache_delete('aieo_camp:' . $slug, self::CACHE_GROUP);
            if (self::$slug_to_id_cache !== null) {
                unset(self::$slug_to_id_cache[$slug]);
            }
        }
        return true;
    }

    public static function flush_cache() {
        self::$slug_to_id_cache = null;
        
        
        
    }
}
