<?php

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

class AIEO_DMM_Supplier_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_supplier_extras';
    }

    
    public static function managed_taxonomies() {
        return (array) apply_filters(
            'aieo_dmm_supplier_extras_taxonomies',
            array('supplier')
        );
    }

    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_se:' . $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['lead_time_days']         = ($merged['lead_time_days']         === null || $merged['lead_time_days']         === '') ? null : (int)   $merged['lead_time_days'];
        $merged['payment_terms_days']     = ($merged['payment_terms_days']     === null || $merged['payment_terms_days']     === '') ? null : (int)   $merged['payment_terms_days'];
        $merged['special_discount_pct']   = (float) $merged['special_discount_pct'];
        $merged['supplier_owner_user_id'] = $merged['supplier_owner_user_id'] ? (int) $merged['supplier_owner_user_id'] : null;
        $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_se:' . $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_se:' . $key, self::CACHE_GROUP);
        return true;
    }

    public static function defaults() {
        return array(
            'email'                   => '',
            'lead_time_days'          => null,
            'payment_terms_days'      => null,
            'special_discount_pct'    => 0.0,
            'supplier_owner_user_id'  => null,
            'notes'                   => '',
        );
    }

    private static function sanitize(array $patch) {
        $out = array();
        if (array_key_exists('email', $patch)) {
            $email = sanitize_email((string) $patch['email']);
            $out['email'] = ($email !== '' && strlen($email) <= 190) ? $email : null;
        }
        if (array_key_exists('lead_time_days', $patch)) {
            $v = $patch['lead_time_days'];
            $out['lead_time_days'] = ($v === null || $v === '') ? null : max(0, (int) $v);
        }
        if (array_key_exists('payment_terms_days', $patch)) {
            $v = $patch['payment_terms_days'];
            $out['payment_terms_days'] = ($v === null || $v === '') ? null : max(0, (int) $v);
        }
        if (array_key_exists('special_discount_pct', $patch)) {
            $v = (float) $patch['special_discount_pct'];
            if ($v < 0)   { $v = 0; }
            if ($v > 100) { $v = 100; }
            $out['special_discount_pct'] = $v;
        }
        if (array_key_exists('supplier_owner_user_id', $patch)) {
            $v = (int) $patch['supplier_owner_user_id'];
            $out['supplier_owner_user_id'] = $v > 0 ? $v : null;
        }
        if (array_key_exists('notes', $patch)) {
            $out['notes'] = wp_kses_post((string) $patch['notes']);
        }
        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);
        }
    }
}
