<?php

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

class AIEO_DMM_Cancellation_Reasons_Data {

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

    
    private static $request_cache = null;

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

    
    public static function all() {
        if (self::$request_cache !== null) { return self::$request_cache; }
        $cached = wp_cache_get('aieo_cr_all', self::CACHE_GROUP);
        if (is_array($cached)) {
            self::$request_cache = $cached;
            return $cached;
        }
        global $wpdb;
        $rows = $wpdb->get_results(
            'SELECT id, slug, label, is_customer_visible, default_event_kind, sort_order, enabled
               FROM ' . self::table() . '
              ORDER BY sort_order ASC, label ASC',
            ARRAY_A
        );
        $rows = is_array($rows) ? $rows : array();
        $by_slug = array();
        foreach ($rows as $r) {
            $r['id']                  = (int)  $r['id'];
            $r['is_customer_visible'] = (int)  $r['is_customer_visible'];
            $r['sort_order']          = (int)  $r['sort_order'];
            $r['enabled']             = (int)  $r['enabled'];
            $r['default_event_kind']  = isset($r['default_event_kind']) && $r['default_event_kind'] !== null && $r['default_event_kind'] !== ''
                ? (int) $r['default_event_kind']
                : null;
            $by_slug[(string) $r['slug']] = $r;
        }
        wp_cache_set('aieo_cr_all', $by_slug, self::CACHE_GROUP, self::CACHE_TTL);
        self::$request_cache = $by_slug;
        return $by_slug;
    }

    
    public static function enabled() {
        $out = array();
        foreach (self::all() as $slug => $row) {
            if ((int) $row['enabled'] === 1) { $out[$slug] = $row; }
        }
        return $out;
    }

    
    public static function get($slug) {
        $slug = (string) $slug;
        if ($slug === '') { return null; }
        $all = self::all();
        return isset($all[$slug]) ? $all[$slug] : null;
    }

    
    public static function save($slug, array $patch) {
        global $wpdb;
        $slug = (string) $slug;
        if ($slug === '') { return false; }

        $clean = array(
            'slug' => preg_replace('/[^a-z0-9_]/', '_', strtolower($slug)),
        );
        if (array_key_exists('label', $patch)) {
            $clean['label'] = sanitize_text_field((string) $patch['label']);
        }
        if (array_key_exists('is_customer_visible', $patch)) {
            $clean['is_customer_visible'] = !empty($patch['is_customer_visible']) ? 1 : 0;
        }
        if (array_key_exists('sort_order', $patch)) {
            $clean['sort_order'] = (int) $patch['sort_order'];
        }
        if (array_key_exists('enabled', $patch)) {
            $clean['enabled'] = !empty($patch['enabled']) ? 1 : 0;
        }
        if (array_key_exists('default_event_kind', $patch)) {
            $v = $patch['default_event_kind'];
            $clean['default_event_kind'] = ($v === '' || $v === null || $v === '-')
                ? null
                : (in_array((int) $v, array(0, 1, 2, 3), true) ? (int) $v : null);
        }
        if (!isset($clean['label']) || $clean['label'] === '') {
            $clean['label'] = $clean['slug'];
        }

        $table = self::table();
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table} WHERE slug = %s LIMIT 1",
            $clean['slug']
        ));
        if ($existing) {
            $id = (int) $existing;
            unset($clean['slug']);
            $wpdb->update($table, $clean, array('id' => $id));
        } else {
            $wpdb->insert($table, $clean);
            $id = (int) $wpdb->insert_id;
        }
        self::flush_cache();
        return $id;
    }

    
    public static function disable($slug) {
        return self::save($slug, array('enabled' => 0));
    }

    public static function flush_cache() {
        self::$request_cache = null;
        wp_cache_delete('aieo_cr_all', self::CACHE_GROUP);
    }
}
