<?php

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

class AIEO_MOI_Vendor_Manager {

    
    public static function generate_webhook_token() {
        if (function_exists('random_bytes')) {
            return rtrim(strtr(base64_encode(random_bytes(24)), '+/', '-_'), '=');
        }
        return wp_generate_password(32, false);
    }

    
    public static function get($id) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$tbl} WHERE id = %d LIMIT 1",
            (int) $id
        ), ARRAY_A);
        return self::hydrate($row);
    }

    
    public static function get_by_slug($slug) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$tbl} WHERE slug = %s LIMIT 1",
            (string) $slug
        ), ARRAY_A);
        return self::hydrate($row);
    }

    
    public static function get_by_webhook_token($token) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$tbl} WHERE webhook_token = %s AND enabled = 1 LIMIT 1",
            (string) $token
        ), ARRAY_A);
        return self::hydrate($row);
    }

    
    public static function list_all() {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $rows = $wpdb->get_results(
            "SELECT * FROM {$tbl} ORDER BY enabled DESC, label ASC", ARRAY_A
        );
        return array_map(array(__CLASS__, 'hydrate'), is_array($rows) ? $rows : array());
    }

    
    public static function save(array $data) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];

        $slug = sanitize_key((string) ($data['slug'] ?? ''));
        if ($slug === '') { return new WP_Error('bad_slug', __('Vendor slug is required.', 'ai-eshop-optimizer')); }
        $provider_slug = sanitize_key((string) ($data['provider'] ?? ''));
        if ($provider_slug === '') { return new WP_Error('bad_provider', __('Provider type is required.', 'ai-eshop-optimizer')); }
        if (!AIEO_MOI_Provider_Registry::get($provider_slug)) {
            return new WP_Error('unknown_provider', __('Unknown provider type.', 'ai-eshop-optimizer'));
        }

        $row = array(
            'slug'                => $slug,
            'provider'            => $provider_slug,
            'label'               => isset($data['label']) ? sanitize_text_field((string) $data['label']) : ucfirst($slug),
            'credentials_json'    => wp_json_encode(isset($data['credentials']) && is_array($data['credentials']) ? $data['credentials'] : array()),
            'default_order_status'=> isset($data['default_order_status']) ? sanitize_key((string) $data['default_order_status']) : 'wc-on-hold',
            'sku_strategy'        => isset($data['sku_strategy']) && in_array($data['sku_strategy'], array('id','sku','custom_field'), true) ? $data['sku_strategy'] : 'sku',
            'sku_meta_key'        => isset($data['sku_meta_key']) ? sanitize_text_field((string) $data['sku_meta_key']) : null,
            'enabled'             => !empty($data['enabled']) ? 1 : 0,
            'updated_at'          => current_time('mysql', true),
        );

        $id = isset($data['id']) ? (int) $data['id'] : 0;
        if ($id > 0) {
            $wpdb->update($tbl, $row, array('id' => $id));
            return $id;
        }
        
        $row['webhook_token'] = self::generate_webhook_token();
        $row['created_at']    = current_time('mysql', true);
        $ok = $wpdb->insert($tbl, $row);
        if (!$ok) {
            return new WP_Error('db_insert_failed', __('Could not create vendor.', 'ai-eshop-optimizer'));
        }
        return (int) $wpdb->insert_id;
    }

    public static function delete($id) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $wpdb->delete($tbl, array('id' => (int) $id), array('%d'));
    }

    
    public static function rotate_webhook_token($id) {
        global $wpdb;
        $tbl = AIEO_MOI_Schema::tables()['vendors'];
        $token = self::generate_webhook_token();
        $wpdb->update($tbl, array('webhook_token' => $token, 'updated_at' => current_time('mysql', true)), array('id' => (int) $id));
        return $token;
    }

    
    public static function webhook_url(array $vendor) {
        return rest_url('moi/v1/webhook/' . rawurlencode($vendor['slug'])) . '?token=' . rawurlencode($vendor['webhook_token']);
    }

    
    public static function credentials(array $vendor) {
        if (empty($vendor['credentials_json'])) { return array(); }
        $decoded = json_decode((string) $vendor['credentials_json'], true);
        return is_array($decoded) ? $decoded : array();
    }

    
    private static function hydrate($row) {
        if (!is_array($row)) { return null; }
        $row['enabled'] = (int) $row['enabled'] === 1;
        $row['credentials'] = self::credentials($row);
        return $row;
    }
}
