<?php
declare(strict_types=1);

namespace Instinctor\Services;

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


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

/**
 * ProductBadgeService - Product badges (New, Sale, Best Seller, etc.)
 * @since 2.0.44
 */
class ProductBadgeService
{
    public static function isActive(): bool
    {
        return true; // Product badges are always-on core feature
    }
    
    /**
     * Get badges for product
     */
    public static function getBadges(int $productId): array
    {
        if (!self::isActive()) {
            return [];
        }
        
        $table = DB::prefix() . 'instinctor_products';
        
        $product = DB::get_row(
            DB::prepare("SELECT * FROM {$table} WHERE id = %d", $productId),
            'ARRAY_A'
        );
        
        if (!$product) {
            return [];
        }
        
        $badges = [];
        $settings = self::getSettings();
        
        // Custom badge
        if (!empty($product['custom_badge'])) {
            $badges[] = [
                'type' => 'custom',
                'text' => $product['custom_badge'],
                'color' => $product['custom_badge_color'] ?? '#1d2327',
            ];
        }
        
        // Auto "New" badge
        if ($settings['auto_new'] && $product['created_at']) {
            $daysOld = (time() - strtotime($product['created_at'])) / DAY_IN_SECONDS;
            if ($daysOld <= $settings['new_days']) {
                $badges[] = [
                    'type' => 'new',
                    'text' => $settings['new_text'],
                    'color' => '#22863a',
                ];
            }
        }
        
        // Sale badge
        if ($settings['auto_sale'] && $product['sale_price'] && $product['sale_price'] < $product['price']) {
            $percent = round((1 - $product['sale_price'] / $product['price']) * 100);
            $badges[] = [
                'type' => 'sale',
                'text' => $settings['sale_percent'] ? "-{$percent}%" : $settings['sale_text'],
                'color' => '#dc2626',
            ];
        }
        
        // Low stock badge
        if ($settings['auto_low_stock'] && $product['stock_quantity'] !== null) {
            if ($product['stock_quantity'] > 0 && $product['stock_quantity'] <= $settings['low_stock_threshold']) {
                $badges[] = [
                    'type' => 'low_stock',
                    'text' => sprintf($settings['low_stock_text'], $product['stock_quantity']),
                    'color' => '#f59e0b',
                ];
            }
        }
        
        // Best seller badge (check if flagged)
        if (!empty($product['is_bestseller'])) {
            $badges[] = [
                'type' => 'bestseller',
                'text' => $settings['bestseller_text'],
                'color' => '#7c3aed',
            ];
        }
        
        return $badges;
    }
    
    /**
     * Get badge settings
     */
    public static function getSettings(): array
    {
        return [
            'auto_new' => Config::get('instinctor_badge_auto_new', true),
            'new_days' => Config::get('instinctor_badge_new_days', 14),
            'new_text' => Config::get('instinctor_badge_new_text', 'New'),
            'auto_sale' => Config::get('instinctor_badge_auto_sale', true),
            'sale_text' => Config::get('instinctor_badge_sale_text', 'Sale'),
            'sale_percent' => Config::get('instinctor_badge_sale_percent', true),
            'auto_low_stock' => Config::get('instinctor_badge_auto_low_stock', true),
            'low_stock_threshold' => Config::get('instinctor_badge_low_stock_threshold', 5),
            'low_stock_text' => Config::get('instinctor_badge_low_stock_text', 'Only %d left'),
            'bestseller_text' => Config::get('instinctor_badge_bestseller_text', 'Best Seller'),
        ];
    }
    
    /**
     * Save settings
     */
    public static function saveSettings(array $settings): void
    {
        foreach ($settings as $key => $value) {
            Config::set('instinctor_badge_' . $key, $value);
        }
    }
    
    /**
     * Render badges HTML
     */
    public static function renderBadges(int $productId): string
    {
        $badges = self::getBadges($productId);
        
        if (empty($badges)) {
            return '';
        }
        
        $html = '<div class="instinctor-product-badges">';
        foreach ($badges as $badge) {
            $html .= sprintf(
                '<span class="instinctor-badge instinctor-badge-%s" style="background-color:%s;">%s</span>',
                esc_attr($badge['type']),
                esc_attr($badge['color']),
                esc_html($badge['text'])
            );
        }
        $html .= '</div>';
        
        return $html;
    }
    
    /**
     * Get badge CSS
     */
    public static function getBadgeCSS(): string
    {
        return '
        .instinctor-product-badges {
            position: absolute;
            top: 10px;
            left: 10px;
            display: flex;
            flex-direction: column;
            gap: 5px;
            z-index: 10;
        }
        .instinctor-badge {
            display: inline-block;
            padding: 4px 10px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            color: #fff;
            border-radius: 3px;
            letter-spacing: 0.5px;
        }
        ';
    }
}
