<?php
namespace Components\Models;
use Components\Ui\Badge;

class CouponBatch extends BaseModel
{
    protected static string $table = 'TABLE_MAILBEEZ_COUPON_BATCHES';
    protected static string $primaryKey = 'batch_id';
    protected static ?string $metaColumn = 'metadata';

    /**
     * @return Coupon[]
     */
    public function coupons(): array
    {
        if (self::isDev()) return [];
        
        $batchId = (int)$this->batch_id;
        $couponTable = Coupon::table();
        $trackingTable = (string)\mh_cfg('TABLE_MAILBEEZ_TRACKING_COUPONS', 'mailbeez_tracking_coupons');
        
        $sql = "SELECT c.* FROM {$couponTable} c 
                JOIN {$trackingTable} t ON c.coupon_id = t.coupon_id 
                WHERE t.batch_id = {$batchId} 
                ORDER BY c.coupon_id DESC";
        
        $q = \mh_db_query($sql);
        $items = [];
        while ($row = \mh_db_fetch_array($q)) {
            $items[] = new Coupon($row);
        }
        \mh_db_free_result($q);
        
        return $items;
    }

    public function getStats(): array
    {
        if (self::isDev()) return ['total' => 0, 'redeemed' => 0, 'percent' => 0];

        $batchId = (int)$this->batch_id;
        $trackingTable = (string)\mh_cfg('TABLE_MAILBEEZ_TRACKING_COUPONS', 'mailbeez_tracking_coupons');
        
        $sql = "SELECT COUNT(*) as total, SUM(IF(redeemed > 0, 1, 0)) as redeemed 
                FROM {$trackingTable} 
                WHERE batch_id = {$batchId}";
        
        $q = \mh_db_query($sql);
        $res = \mh_db_fetch_array($q);
        \mh_db_free_result($q);
        
        $total = (int)($res['total'] ?? 0);
        $redeemed = (int)($res['redeemed'] ?? 0);
        $percent = $total > 0 ? round(($redeemed / $total) * 100, 1) : 0;
        
        return [
            'total' => $total,
            'redeemed' => $redeemed,
            'percent' => $percent
        ];
    }

    /**
     * Dynamic select options for batch_id (CouponBatch)
     * Returns rich option data including identity for CollectionIdentity rendering.
     *
     * @param bool $includeNone
     * @return array<int|string, array{label: string, identity: array}>
     */
    public static function listOptions(bool $includeNone = true): array
    {
        $options = [];
        if ($includeNone) {
            $options[0] = [
                'label' => (string)\mh_lng('UI_TEXT_NO_BATCH', 'No Series'),
                'identity' => [
                    'svg' => \Components\Base::SVG_MINUS,
                    'color' => 'gray',
                    'size' => 'sm',
                    'variant' => 'solid'
                ]
            ];
        }

        $all = self::all();

        foreach ($all as $batch) {
            $options[$batch->batch_id] = [
                'label' => $batch->batch_name,
                'identity' => self::getIdentityDataByType((string)$batch->batch_type)
            ];
        }

        return $options;
    }

    /**
     * @param string $type
     * @return array
     */
    public static function getIdentityDataByType(string $type): array
    {
        $types = self::getTypesData();
        return [
            'svg' => \Components\Base::SVG_OUTLINE_FOLDER,
            'color' => $types[$type]['token'] ?? 'gray',
            'size' => 'sm',
            'variant' => 'solid'
        ];
    }

    /**
     * @return array
     */
    private static function getTypesData(): array
    {
        return [
            'onsite' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_ONSITE', 'On-site'),
                'token' => 'orange',
            ],
            'offline' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_OFFLINE', 'Offline'),
                'token' => 'blue',
            ],
            'partner' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_PARTNER', 'Partner'),
                'token' => 'indigo',
            ],
            'support' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_SUPPORT', 'Support'),
                'token' => 'red',
            ],
            'influencer' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_INFLUENCER', 'Influencer'),
                'token' => 'purple',
            ],
            'loyalty' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_LOYALTY', 'Loyalty / VIP'),
                'token' => 'pink',
            ],
            'referral' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_REFERRAL', 'Referral Program'),
                'token' => 'teal',
            ],
            'social' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_SOCIAL', 'Social Media'),
                'token' => 'sky',
            ],
            'ads' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_ADS', 'Paid Ads'),
                'token' => 'amber',
            ],
            'export' => [
                'label' => (string)\mh_lng('UI_TEXT_BATCH_TYPE_EXPORT', 'Export'),
                'token' => 'green',
            ],
        ];
    }

    /**
     * @param bool $includeAll
     * @param string|null $emptyLabel
     * @return array
     */
    public static function getTypeOptions(bool $includeAll = false, ?string $emptyLabel = null): array
    {
        $options = [];
        if ($includeAll || $emptyLabel !== null) {
            $label = $emptyLabel ?? (string)\mh_lng('UI_TEXT_ALL_TYPES', 'All Types');
            $options[''] = ['label_html' => $label];
        }

        $types = self::getTypesData();

        foreach ($types as $key => $data) {
            $options[$key] = [
                'label' => $data['label'],
                'label_html' => self::getTypeBadge($key),
                'badge' => [
                    'type' => 'default',
                    'token' => $data['token'],
                ]
            ];
        }

        return $options;
    }

    /**
     * @param string $type
     * @return string HTML
     */
    public static function getTypeBadge(string $type): string
    {
        $types = self::getTypesData();

        if (!isset($types[$type])) {
            return Badge::render('default', $type);
        }

        return Badge::render('default', $types[$type]['label'], [
            'token' => $types[$type]['token'],
        ]);
    }
}
