<?php

declare(strict_types=1);

namespace Instinctor\Services;

use Instinctor\Core\Config;
use Instinctor\Core\DB;

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

/**
 * OneClickCheckoutService - Buy Now, skip cart functionality
 * @since 2.0.44
 */
class OneClickCheckoutService
{
    public static function isActive(): bool
    {
        $addons = Config::get('instinctor_active_addons', []);
        return in_array('one_click_checkout', $addons) || in_array('all_access', $addons);
    }
    
    /**
     * Get settings
     */
    public static function getSettings(): array
    {
        return [
            'enabled' => Config::get('instinctor_oneclick_enabled', true),
            'button_text' => Config::get('instinctor_oneclick_button_text', 'Buy Now'),
            'show_on_product' => Config::get('instinctor_oneclick_show_product', true),
            'show_on_archive' => Config::get('instinctor_oneclick_show_archive', false),
            'skip_cart' => Config::get('instinctor_oneclick_skip_cart', true),
            'save_payment_methods' => Config::get('instinctor_oneclick_save_payment', true),
        ];
    }
    
    /**
     * Save settings
     */
    public static function saveSettings(array $settings): void
    {
        Config::set('instinctor_oneclick_enabled', !empty($settings['enabled']));
        Config::set('instinctor_oneclick_button_text', sanitize_text_field($settings['button_text'] ?? 'Buy Now'));
        Config::set('instinctor_oneclick_show_product', !empty($settings['show_on_product']));
        Config::set('instinctor_oneclick_show_archive', !empty($settings['show_on_archive']));
        Config::set('instinctor_oneclick_skip_cart', !empty($settings['skip_cart']));
        Config::set('instinctor_oneclick_save_payment', !empty($settings['save_payment_methods']));
    }
    
    /**
     * Check if user has saved payment method
     */
    public static function hasSavedPaymentMethod(int $userId): bool
    {
        if (!$userId) return false;
        // On WP: read from wp user meta
        if (!defined('INSTINCTOR_ENV') || INSTINCTOR_ENV === 'wordpress') {
            $savedMethods = get_user_meta($userId, 'instinctor_saved_payment_methods', true);
            return !empty($savedMethods);
        }
        // Standalone: read from instinctor_users.meta JSON
        $row = \Instinctor\Core\DB::get_row(\Instinctor\Core\DB::prepare(
            'SELECT meta FROM ' . \Instinctor\Core\DB::prefix() . 'instinctor_users WHERE wp_user_id = %d LIMIT 1',
            $userId
        ));
        if (!$row) return false;
        $meta = json_decode(is_object($row) ? $row->meta : ($row['meta'] ?? '{}'), true) ?: [];
        return !empty($meta['saved_payment_methods']);
    }
}
