<?php
/**
 * تزریق ویجت چت — پایه مشترک
 * قبل از require: $acc_widget_cfg = [ portal, site_name, welcome_msg, wizards_js, tabs, theme_color, launcher_icon ]
 */
if ( ! defined( 'ACC_URL' ) ) {
    define( 'ACC_URL', '/acc-engine/' );
}

$base = ACC_URL;
$api_base = rtrim( $base . 'api.php/acc/v1', '/' );

$defaults = [
    'api_base'      => $api_base,
    'nonce'         => '',
    'portal'        => 'service',
    'site_name'     => 'پشتیبانی آنلاین',
    'welcome_msg'   => 'سلام! چطور می‌تونم کمکتون کنم؟',
    'phone'         => '',
    'whatsapp'      => '',
    'telegram'      => '',
    'instagram'     => '',
    'poll_ms'       => 4000,
    'spa_slug'      => 'service',
    'wizards_js'    => 'assets/js/chat-widget/service-wizards.js',
    'tabs'          => [ 'home', 'services', 'track', 'chat', 'tech', 'contact' ],
    'theme_color'   => '#1e40af',
    'launcher_icon' => '💬',
    'wp_user'       => null,
];

$cfg = array_merge( $defaults, $acc_widget_cfg ?? [] );
$cfg['api_base'] = $cfg['api_base'] ?? $api_base;
/* spa_slug را از portal کپی نکن — باعث مخفی شدن اشتباه لانچر روی shop.php و … می‌شد */
if ( empty( $acc_widget_cfg['spa_slug'] ) ) {
    $cfg['spa_slug'] = 'erp-spa';
} else {
    $cfg['spa_slug'] = $acc_widget_cfg['spa_slug'];
}
echo "\n<!-- ACC Chat Widget [{$cfg['portal']}] -->\n";
echo '<link rel="stylesheet" href="' . htmlspecialchars( $base . 'assets/css/base/chat-widget.css?v=2', ENT_QUOTES ) . '" media="all">' . "\n";
if ( ! empty( $cfg['wizards_js'] ) ) {
    echo '<script src="' . htmlspecialchars( $base . ltrim( $cfg['wizards_js'], '/' ), ENT_QUOTES ) . '"></script>' . "\n";
}
if ( ! empty( $cfg['ai_js'] ) ) {
    echo '<script src="' . htmlspecialchars( $base . ltrim( $cfg['ai_js'], '/' ), ENT_QUOTES ) . '"></script>' . "\n";
}
echo '<script>window.ACC_CHAT_CFG = ' . json_encode( $cfg, JSON_UNESCAPED_UNICODE ) . ';</script>' . "\n";
echo '<script src="' . htmlspecialchars( $base . 'assets/js/chat-widget/widget.js?v=2', ENT_QUOTES ) . '"></script>' . "\n";
