<?php
namespace Components\Data\Live;

use Components\Data\Contracts\TemplateCouponProvider;
use Components\Data\Mock\MockTemplateCouponProvider;

/**
 * Live implementation that delegates to the legacy coupon engine
 * via couponbeez::_get_coupon_code_templates (example in couponbeez_ccgv).
 * Falls back to the mock provider when the legacy runtime isn't available.
 */

class LiveTemplateCouponProvider implements TemplateCouponProvider
{
    var $couponEngine = null;
    private function mock(): MockTemplateCouponProvider
    {
        return new MockTemplateCouponProvider();
    }

    /**
     * Try to bootstrap the legacy MailBeez runtime enough to access couponbeez.
     */
    private function loadCouponEngine(): bool
    {
        require_once(MH_DIR_CONFIG . 'config_coupon_engine/classes/couponbeez.php');
        if (!class_exists('couponbeez', true)) {
            return false;
        }

        $this->couponEngine = new \couponbeez();
        return true;
    }

    /**
     * Resolve a language id for legacy API calls.
     */
    private function resolveLanguageId(): int
    {
        // Prefer session when present
        if (isset($_SESSION['languages_id']) && (int)$_SESSION['languages_id'] > 0) {
            return (int)$_SESSION['languages_id'];
        }

        return 1;
    }

    /**
     * Fetch coupon templates via legacy couponbeez protected method using a small accessor.
     * @return array<int, array{id: mixed, text: string}>
     */
    private function fetchLegacyTemplates($include_empty = false): array
    {
        if (!$this->loadCouponEngine()) {
            return [];
        }
        try {
            $langId = $this->resolveLanguageId();
            $rows = $this->couponEngine->_get_coupon_code_templates($langId, $include_empty);
           return is_array($rows) ? $rows : [];
        } catch (\Throwable $e) {
            dd($e);
            return [];
        }
    }

    public function templates($include_empty = true): array
    {
        try {
            $rows = $this->fetchLegacyTemplates($include_empty);

            $counts = [];
            if (defined('TABLE_MAILBEEZ_TRACKING_COUPONS')) {
                $sql = "SELECT template_coupon_id, COUNT(*) as total FROM " . TABLE_MAILBEEZ_TRACKING_COUPONS . " GROUP BY template_coupon_id";
                $q = mh_db_query($sql);
                while ($row = mh_db_fetch_array($q)) {
                    $counts[(int)$row['template_coupon_id']] = (int)$row['total'];
                }
            }


            $items = [];
            foreach ($rows as $row) {
                if (!is_array($row)) { continue; }

                $id = $row['id'] ?? null;
                $code = $row['code'] ?? null;
                $name = $row['name'] ?? $row['text'] ?? '';
                $text = $id < 1 ? ($row['name'] ?? $row['text'] ?? '') : ($row['name'] ?? '') . ' (' . ($row['code'] ?? '') . ')';
                $type = $row['type'] ?? null;
                $amount = $row['amount'] ?? null;
                $typeLabel= $this->couponEngine->get_coupon_type_label($id);


                $items[] = [
                    'id' => $id,
                    'code' => $code,
                    'codeMain' => str_replace('template_', '', (string)$code),
                    'name' => $name,
                    'label' => $text,
                    'typeLabel' => $typeLabel,
                    'type' => $type,
                    'amount' => $amount,
                    'generated_count' => $counts[(int)$id] ?? 0,
                ];
            }

            // Stable sort by title
            usort($items, function ($a, $b) { return strcasecmp((string)$a['id'], (string)$b['id']); });
            return $items ?: $this->mock()->templates();
        } catch (\Throwable $e) {
            dd($e);
            return $this->mock()->templates();
        }
    }
}
