<?php

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

class AIEO_Exchanger_Imports {

    const MODES = array(
        'create_link_only',
        'create_with_term_meta',
        'create_no_term_meta',
        'update_only',
        'overwrite',
    );
    const MATCH_KEYS = array('barcode', 'sku');

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

    public static function list_all() {
        global $wpdb;
        $rows = $wpdb->get_results('SELECT * FROM ' . self::table() . ' ORDER BY id DESC', ARRAY_A);
        if (!is_array($rows)) { return array(); }
        foreach ($rows as &$r) { self::decode_row($r); }
        return $rows;
    }

    public static function get($id) {
        global $wpdb;
        $row = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . self::table() . ' WHERE id = %d', (int) $id), ARRAY_A);
        if (!$row) { return null; }
        self::decode_row($row);
        return $row;
    }

    public static function get_by_slug($slug) {
        global $wpdb;
        $row = $wpdb->get_row($wpdb->prepare('SELECT * FROM ' . self::table() . ' WHERE slug = %s', (string) $slug), ARRAY_A);
        if (!$row) { return null; }
        self::decode_row($row);
        return $row;
    }

    public static function save(array $data) {
        global $wpdb;
        $id = isset($data['id']) ? (int) $data['id'] : 0;
        $slug = sanitize_key((string) ($data['slug'] ?? ''));
        if ($slug === '') { return new WP_Error('invalid_slug', __('Slug is required.', 'ai-eshop-optimizer')); }

        $clash = (int) $wpdb->get_var($wpdb->prepare(
            'SELECT id FROM ' . self::table() . ' WHERE slug = %s AND id <> %d LIMIT 1',
            $slug, $id
        ));
        if ($clash) { return new WP_Error('duplicate_slug', __('Another import job already uses this slug.', 'ai-eshop-optimizer')); }

        $mode      = in_array($data['mode'] ?? '',      self::MODES,      true) ? (string) $data['mode']      : 'create_link_only';
        $match_key = in_array($data['match_key'] ?? '', self::MATCH_KEYS, true) ? (string) $data['match_key'] : 'sku';

        $row = array(
            'slug'           => $slug,
            'label'          => sanitize_text_field((string) ($data['label'] ?? '')),
            'enabled'        => !empty($data['enabled']) ? 1 : 0,
            'source_url'     => esc_url_raw((string) ($data['source_url'] ?? '')),
            'feed_token'     => sanitize_text_field((string) ($data['feed_token'] ?? '')),
            'match_key'      => $match_key,
            'mode'           => $mode,
            'schedule_cron'  => self::sanitize_schedule($data['schedule_cron'] ?? ''),
        );

        if ($id > 0) {
            $wpdb->update(self::table(), $row, array('id' => $id));
            return $id;
        }
        $wpdb->insert(self::table(), $row);
        return (int) $wpdb->insert_id;
    }

    public static function delete($id) {
        global $wpdb;
        $wpdb->delete(self::table(), array('id' => (int) $id));
    }

    public static function record_run_result($id, $status) {
        global $wpdb;
        $wpdb->update(self::table(), array(
            'last_run_at' => current_time('mysql', true),
            'last_status' => substr((string) $status, 0, 40),
        ), array('id' => (int) $id));
    }

    public static function update_cursor($id, array $cursor) {
        global $wpdb;
        $wpdb->update(self::table(), array('cursor_state' => wp_json_encode($cursor)), array('id' => (int) $id));
    }

    private static function decode_row(array &$row) {
        $row['enabled'] = (int) ($row['enabled'] ?? 0);
        $row['cursor_state'] = !empty($row['cursor_state']) ? (array) json_decode((string) $row['cursor_state'], true) : array();
    }

    private static function sanitize_schedule($s) {
        $s = sanitize_key((string) $s);
        $allowed = array('', 'hourly', 'twicedaily', 'daily', 'weekly');
        return in_array($s, $allowed, true) ? $s : '';
    }
}
