<?php

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

class AIEO_DMM_Need_Extras_Data {

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

    private static $request_cache = array();

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

    public static function managed_taxonomies() {
        return (array) apply_filters(
            'aieo_dmm_need_extras_taxonomies',
            array('pa_need')
        );
    }

    public static function get($taxonomy, $term_id) {
        $taxonomy = (string) $taxonomy;
        $term_id  = (int) $term_id;
        if ($taxonomy === '' || $term_id <= 0) { return self::defaults(); }

        $key = $taxonomy . ':' . $term_id;
        if (isset(self::$request_cache[$key])) { return self::$request_cache[$key]; }

        $cache_key = 'aieo_ne:' . $key;
        $cached = wp_cache_get($cache_key, self::CACHE_GROUP);
        if (is_array($cached)) {
            self::$request_cache[$key] = $cached;
            return $cached;
        }

        global $wpdb;
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM " . self::table() . " WHERE taxonomy = %s AND term_id = %d LIMIT 1",
            $taxonomy, $term_id
        ), ARRAY_A);
        $row = is_array($row) ? $row : array();

        $merged = self::defaults();
        foreach ($merged as $col => $default) {
            if (array_key_exists($col, $row) && $row[$col] !== null) {
                $merged[$col] = $row[$col];
            }
        }
        $merged['icon_image_id'] = $merged['icon_image_id'] ? (int) $merged['icon_image_id'] : null;
        $merged['hero_image_id'] = $merged['hero_image_id'] ? (int) $merged['hero_image_id'] : null;
        $merged['priority']      = (int) $merged['priority'];
        $merged['taxonomy'] = $taxonomy;
        $merged['term_id']  = $term_id;

        wp_cache_set($cache_key, $merged, self::CACHE_GROUP, self::CACHE_TTL);
        self::$request_cache[$key] = $merged;
        return $merged;
    }

    public static function save($taxonomy, $term_id, array $patch) {
        global $wpdb;
        $taxonomy = (string) $taxonomy;
        $term_id  = (int) $term_id;
        if ($taxonomy === '' || $term_id <= 0) { return false; }

        $clean = self::sanitize($patch);
        if (empty($clean)) { return true; }

        $clean['taxonomy']   = $taxonomy;
        $clean['term_id']    = $term_id;
        $clean['updated_at'] = current_time('mysql', true);

        $existing_id = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM " . self::table() . " WHERE taxonomy = %s AND term_id = %d LIMIT 1",
            $taxonomy, $term_id
        ));
        if ($existing_id) {
            $r = $wpdb->update(self::table(), $clean, array('id' => (int) $existing_id));
        } else {
            $clean['created_at'] = $clean['updated_at'];
            $r = $wpdb->insert(self::table(), $clean);
        }
        if ($r === false) { return false; }

        $key = $taxonomy . ':' . $term_id;
        unset(self::$request_cache[$key]);
        wp_cache_delete('aieo_ne:' . $key, self::CACHE_GROUP);
        return true;
    }

    public static function delete($taxonomy, $term_id) {
        global $wpdb;
        $taxonomy = (string) $taxonomy;
        $term_id  = (int) $term_id;
        if ($taxonomy === '' || $term_id <= 0) { return false; }
        $wpdb->delete(self::table(), array('taxonomy' => $taxonomy, 'term_id' => $term_id));
        $key = $taxonomy . ':' . $term_id;
        unset(self::$request_cache[$key]);
        wp_cache_delete('aieo_ne:' . $key, self::CACHE_GROUP);
        return true;
    }

    public static function defaults() {
        return array(
            'icon_image_id' => null,
            'hero_image_id' => null,
            'headline'      => '',
            'about_text'    => '',
            'priority'      => 0,
            'footer_text'   => '',
        );
    }

    private static function sanitize(array $patch) {
        $out = array();
        if (array_key_exists('icon_image_id', $patch)) {
            $v = (int) $patch['icon_image_id'];
            $out['icon_image_id'] = $v > 0 ? $v : null;
        }
        if (array_key_exists('hero_image_id', $patch)) {
            $v = (int) $patch['hero_image_id'];
            $out['hero_image_id'] = $v > 0 ? $v : null;
        }
        if (array_key_exists('headline', $patch)) {
            $out['headline'] = sanitize_text_field((string) $patch['headline']);
        }
        if (array_key_exists('about_text', $patch)) {
            $out['about_text'] = wp_kses_post((string) $patch['about_text']);
        }
        if (array_key_exists('priority', $patch)) {
            $out['priority'] = (int) $patch['priority'];
        }
        if (array_key_exists('footer_text', $patch)) {
            $out['footer_text'] = wp_kses_post((string) $patch['footer_text']);
        }
        return $out;
    }

    public static function flush_request_cache() {
        self::$request_cache = array();
    }

    public static function bootstrap() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        add_action('delete_term', array(__CLASS__, 'on_delete_term'), 10, 3);
    }

    public static function on_delete_term($term_id, $tt_id, $taxonomy) {
        if (in_array((string) $taxonomy, self::managed_taxonomies(), true)) {
            self::delete((string) $taxonomy, (int) $term_id);
        }
    }
}
