<?php

require_once __DIR__ . '/database.php';
require_once __DIR__ . '/../services/notifications/NotificationService.php';

function notify_event(string $eventType, array $payload = array()): array
{
    try {
        $service = new NotificationService(db());
        return $service->notify($eventType, $payload);
    } catch (Throwable $e) {
        error_log('Notification error [' . $eventType . ']: ' . $e->getMessage());
        return array('success' => false, 'reason' => $e->getMessage());
    }
}

function notify_admins_event(string $eventType, array $payload = array()): array
{
    $payload['groups'] = array_values(array_unique(array_merge((array)($payload['groups'] ?? array()), array('system_admins'))));
    $payload['roles'] = array_values(array_unique(array_merge((array)($payload['roles'] ?? array()), array('admin'))));
    return notify_event($eventType, $payload);
}

function notify_group_event(string $eventType, array $groups, array $payload = array()): array
{
    $payload['groups'] = array_values(array_unique(array_merge((array)($payload['groups'] ?? array()), $groups)));
    return notify_event($eventType, $payload);
}

function notification_actor_user_id(): ?int
{
    if (function_exists('current_user_id')) {
        $id = (int)current_user_id();
        return $id > 0 ? $id : null;
    }

    if (isset($_SESSION['user']['id'])) {
        $id = (int)$_SESSION['user']['id'];
        return $id > 0 ? $id : null;
    }

    return null;
}

function notify_crm_user_event(string $eventType, ?int $userId, string $title, string $body, string $url, string $relatedType, int $relatedId, array $options = array()): array
{
    if (!$userId || $userId <= 0) {
        return array('success' => false, 'reason' => 'missing_user_id');
    }

    $payload = array_merge(array(
        'user_id' => $userId,
        'title' => $title,
        'body' => $body,
        'url' => $url,
        'module' => 'crm',
        'related_type' => $relatedType,
        'related_id' => $relatedId,
        'actor_user_id' => notification_actor_user_id(),
    ), $options);

    return notify_event($eventType, $payload);
}

function notify_crm_owner_or_admin_event(string $eventType, ?int $userId, string $title, string $body, string $url, string $relatedType, int $relatedId, array $options = array()): array
{
    $payload = array_merge(array(
        'title' => $title,
        'body' => $body,
        'url' => $url,
        'module' => 'crm',
        'related_type' => $relatedType,
        'related_id' => $relatedId,
        'actor_user_id' => notification_actor_user_id(),
    ), $options);

    if ($userId && $userId > 0) {
        $payload['user_id'] = $userId;
    } else {
        $payload['groups'] = array_values(array_unique(array_merge((array)($payload['groups'] ?? array()), array('system_admins'))));
        $payload['roles'] = array_values(array_unique(array_merge((array)($payload['roles'] ?? array()), array('admin'))));
    }

    return notify_event($eventType, $payload);
}

function notify_high_value_opportunity_event(int $opportunityId, string $title, string $customerName, float $expectedValue, ?int $ownerUserId = null, array $options = array()): array
{
    $threshold = defined('ICYLAB_NOTIFY_HIGH_VALUE_THRESHOLD') ? (float)ICYLAB_NOTIFY_HIGH_VALUE_THRESHOLD : 1000000.0;
    if ($opportunityId <= 0 || $expectedValue < $threshold) {
        return array('success' => false, 'reason' => 'below_threshold');
    }

    $payload = array_merge(array(
        'user_id' => $ownerUserId,
        'groups' => array('ceo', 'commercial_direction'),
        'title' => 'Oportunidad de alto valor: ' . $title,
        'body' => 'Cliente: ' . $customerName . "\nValor esperado: $" . number_format($expectedValue, 0, ',', '.') . "\nAccion recomendada: revisar prioridad, siguiente paso y probabilidad.",
        'url' => '/modules/crm/opportunity.php?id=' . $opportunityId,
        'module' => 'crm',
        'priority' => 'warning',
        'related_type' => 'opportunity',
        'related_id' => $opportunityId,
        'actor_user_id' => notification_actor_user_id(),
        'metadata' => array('expected_value' => $expectedValue),
        'dedupe_key' => 'opportunity.high_value:' . $opportunityId,
    ), $options);

    return notify_event('opportunity.high_value', $payload);
}

function notify_discount_exception_event(int $quoteId, string $quoteNumber, string $customerName, float $discountPercent, float $total, array $options = array()): array
{
    $threshold = defined('ICYLAB_NOTIFY_DISCOUNT_THRESHOLD') ? (float)ICYLAB_NOTIFY_DISCOUNT_THRESHOLD : 15.0;
    if ($quoteId <= 0 || $discountPercent <= $threshold) {
        return array('success' => false, 'reason' => 'below_threshold');
    }

    $payload = array_merge(array(
        'groups' => array('ceo', 'cfo'),
        'title' => 'Descuento sobre umbral: ' . $quoteNumber,
        'body' => 'Cliente: ' . $customerName . "\nCotizacion: " . $quoteNumber . "\nDescuento: " . number_format($discountPercent, 2, ',', '.') . "%\nTotal facturable: $" . number_format($total, 0, ',', '.') . "\nAccion recomendada: revisar autorizacion comercial y margen.",
        'url' => '/modules/crm/quote_view.php?id=' . $quoteId,
        'module' => 'crm',
        'priority' => 'warning',
        'related_type' => 'quote',
        'related_id' => $quoteId,
        'actor_user_id' => notification_actor_user_id(),
        'metadata' => array('discount_percent' => $discountPercent, 'total' => $total),
        'dedupe_key' => 'quote.discount_high:' . $quoteId . ':' . number_format($discountPercent, 2, '.', ''),
    ), $options);

    return notify_event('quote.discount_high', $payload);
}
