<?php
/**
 * Paradise Pools Bot - config.php
 *
 * ✅ Best practice: لا تضع التوكنات والباسورد داخل الكود.
 * استخدم Environment Variables (ملف .env أو إعدادات السيرفر).
 *
 * ملاحظة:
 * - أرقام واتساب في Cloud API تكون بدون + وبدون مسافات (E.164 digits only)
 *   مثال: 201094945225
 */

// Minimal .env loader (بدون أي مكتبات خارجية)
$dotenvPath = __DIR__ . '/.env';
if (is_file($dotenvPath) && is_readable($dotenvPath)) {
    $lines = file($dotenvPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        $line = trim($line);
       if ($line === '' || substr($line, 0, 1) === '#') continue;
        $eqPos = strpos($line, '=');
        if ($eqPos === false) continue;
        $k = trim(substr($line, 0, $eqPos));
        $v = trim(substr($line, $eqPos + 1));
        // Remove wrapping quotes if present (e.g., KEY="value" or KEY='value')
$v = trim($v);
if (strlen($v) >= 2) {
    $first = $v[0];
    $last  = $v[strlen($v) - 1];
    if (($first === '"' && $last === '"') || ($first === "'" && $last === "'")) {
        $v = substr($v, 1, -1);
    }
}

        if ($k !== '' && getenv($k) === false) {
            putenv($k . '=' . $v);
        }
    }
}

$env = function(string $key, $default = '') {
    $v = getenv($key);
    if ($v === false || $v === null || $v === '') return $default;
    return $v;
};
$envBool = function(string $key, bool $default = false) use ($env): bool {
    $v = strtolower(trim((string)$env($key, $default ? '1' : '0')));
    return in_array($v, ['1', 'true', 'yes', 'on'], true);
};
$envList = function(string $key, string $default = '') use ($env): array {
    $raw = (string)$env($key, $default);
    if ($raw === '') return [];
    $items = array_map('trim', explode(',', $raw));
    return array_values(array_filter($items, fn($x) => $x !== ''));
};

// نفس رقم الإدارة = رقم المعاينة (حسب طلبك)
$ADMIN_NUMBER_E164   = preg_replace('/\D+/', '', (string)$env('PARADISE_ADMIN_NUMBER', '201094945225'));
$PREVIEW_NUMBER_TEXT = trim((string)$env('PARADISE_PREVIEW_NUMBER_DISPLAY', '+20 10 94945225'));

// Meta/WhatsApp/Messenger settings
$VERIFY_TOKEN        = (string)$env('META_VERIFY_TOKEN', 'smartlogic2024');
$WHATSAPP_TOKEN      = (string)$env('META_WHATSAPP_TOKEN', '');
$PHONE_NUMBER_ID     = (string)$env('META_PHONE_NUMBER_ID', '');
$PAGE_ACCESS_TOKEN   = (string)$env('META_PAGE_ACCESS_TOKEN', ''); // used for Messenger + IG + comments
$IG_USER_ID          = (string)$env('META_IG_USER_ID', '');         // optional (recommended for IG private replies)
$META_API_VERSION    = (string)$env('META_API_VERSION', 'v22.0');

// OpenAI
$OPENAI_KEYS_RAW     = (string)$env('OPENAI_API_KEYS', '');
$OPENAI_KEYS = array_values(array_filter(array_map('trim', explode(',', $OPENAI_KEYS_RAW))));

$forwardMediaTypes = $envList('FORWARD_MEDIA_TYPES', 'image,video,document');
if (empty($forwardMediaTypes)) {
    $forwardMediaTypes = ['image', 'video', 'document'];
}

$websiteBase = rtrim((string)$env('PARADISE_WEBSITE', 'https://paradisegroup-eg.com'), '/');
$publicBaseUrl = trim((string)$env('PARADISE_PUBLIC_BASE_URL', ''));
$websiteGroundingUrls = $envList('WEBSITE_GROUNDING_URLS', '');
if (empty($websiteGroundingUrls)) {
    $websiteGroundingUrls = [
        $websiteBase . '/services',
        $websiteBase . '/contact',
        $websiteBase . '/pages/about',
    ];
}

// ======== Configuration ========
$config = [
    'dirs' => ['logs', 'customers', 'chats', 'cache', 'imports', 'customers_media'],

    // Webhook verification
    'verify_token'        => $VERIFY_TOKEN,

    // WhatsApp Cloud API
    'whatsapp_token'      => $WHATSAPP_TOKEN,
    'phone_number_id'     => $PHONE_NUMBER_ID,
    // Some legacy keys in code use whatsapp_phone_id as alternative
    'whatsapp_phone_id'   => $PHONE_NUMBER_ID,

    // Messenger / IG / Comments (Page Access Token)
    'messenger_token'     => $PAGE_ACCESS_TOKEN,
    'facebook_token'      => $PAGE_ACCESS_TOKEN,

    // API versioning
    'meta_api_version'    => $META_API_VERSION,
    'ig_user_id'          => $IG_USER_ID,

    // Performance & AI tuning
    'max_history'         => 80,
    'ai_model'            => (string)$env('OPENAI_MODEL', 'gpt-4o-mini'),
    'ai_max_tokens'       => (int)$env('OPENAI_MAX_TOKENS', '400'),
    'ai_temperature'      => (float)$env('OPENAI_TEMPERATURE', '0.3'),
    'ai_max_history'      => (int)$env('OPENAI_MAX_HISTORY', '16'),
    'ai_cache_ttl'        => (int)$env('OPENAI_CACHE_TTL', '1800'), // seconds
    'max_notes'           => 150,
    'api_timeout'         => (int)$env('HTTP_API_TIMEOUT', '30'),
    'whatsapp_timeout'    => (int)$env('WHATSAPP_TIMEOUT', '25'),
    'messenger_timeout'   => (int)$env('MESSENGER_TIMEOUT', '8'),

    // Rate limits
    'rate_limit_seconds'  => 3,
    'duplicate_threshold' => 8,
    'cache_ttl'           => 300,

    // Media / voice
    'ai_transcribe_model' => 'whisper-1',

    // ✅ Admin + preview (same number)
    'admin_notify_number'    => $ADMIN_NUMBER_E164,
    'admin_notify_numbers'   => [$ADMIN_NUMBER_E164],
    'sales_manager_number'   => $ADMIN_NUMBER_E164,
    'sales_notify_numbers'   => [$ADMIN_NUMBER_E164],

    // text that appears to customers
    'preview_number_display' => $PREVIEW_NUMBER_TEXT,
    // WhatsApp destination for forwarded previews (digits only)
    'preview_whatsapp_number' => $ADMIN_NUMBER_E164,

    // Admin notifications
    'notify_admin_on_every_interaction' => true,
    'admin_notify_rate_limit_seconds'   => (int)$env('ADMIN_NOTIFY_RATE_LIMIT_SECONDS', '60'),

    // Auto-forward previews (images) to admin
    'forward_media_to_admin' => true,
    'forward_media_types'    => $forwardMediaTypes,
    'forward_video_frames_to_admin' => false,

    // Ensure customer replies always include the preview line
    'ensure_preview_line' => true,

    // If sending fails due to 24-hour session rules, use an approved WhatsApp template (optional)
    'whatsapp_alert_template' => (string)$env('WHATSAPP_ALERT_TEMPLATE', ''),
    'whatsapp_media_alert_template' => (string)$env('WHATSAPP_MEDIA_ALERT_TEMPLATE', ''),
    'template_language'       => (string)$env('WHATSAPP_TEMPLATE_LANG', 'ar'),

    // Messenger identity unification: ask for WhatsApp number then map PSID -> WA number
    'messenger_require_wa_phone' => $envBool('MESSENGER_REQUIRE_WA_PHONE', true),
    'messenger_wa_capture_platforms' => $envList('MESSENGER_WA_CAPTURE_PLATFORMS', 'messenger'),

    // Website grounding
    'company_website' => $websiteBase,
    'public_base_url' => $publicBaseUrl,
    'website_grounding_urls' => $websiteGroundingUrls,
    'website_use_sitemap' => $envBool('WEBSITE_GROUNDING_USE_SITEMAP', true),
    'website_sitemap_ttl' => (int)$env('WEBSITE_GROUNDING_SITEMAP_TTL', '43200'),
    'website_facts_max_sources' => (int)$env('WEBSITE_FACTS_MAX_SOURCES', '6'),
    'website_facts_min_sources' => (int)$env('WEBSITE_FACTS_MIN_SOURCES', '3'),
    'website_sitemap_candidate_limit' => (int)$env('WEBSITE_SITEMAP_CANDIDATE_LIMIT', '12'),
];

// OpenAI Tokens with rotation (comma-separated via env)
$openaiTokens = $OPENAI_KEYS;
