<?php

require_once __DIR__ . '/../config/database.php';

/*
|--------------------------------------------------------------------------
| UserAlertService
|--------------------------------------------------------------------------
| Compatibility service for the user-facing "My Alerts" page.
|
| OLD system used: user_alerts
| NEW institutional system uses: institutional_alerts
|--------------------------------------------------------------------------
*/

class UserAlertService
{
    public static function getUserAlerts($userId)
    {
        try {
            $stmt = db()->prepare("
                SELECT
                    id,
                    user_id,
                    setup_key,
                    symbol,
                    timeframe,
                    style,
                    side,
                    scenario_status,
                    entry_price,
                    entry_low,
                    entry_high,
                    stop_loss,
                    tp1,
                    tp2,
                    tp3,
                    alert_trigger_price,
                    liquidity_sweep_level,
                    structure_trigger,
                    telegram_enabled,
                    email_enabled,
                    lifecycle_stage,
                    is_active,
                    last_checked_at,
                    auto_expire_enabled,
                    expires_at,
                    expired_at,
                    expiration_reason,
                    triggered_at,
                    last_sent_at,
                    send_count,
                    created_at,
                    updated_at
                FROM institutional_alerts
                WHERE user_id = ?
                ORDER BY created_at DESC, id DESC
            ");
            $stmt->execute([(int)$userId]);

            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }

    public static function getActiveAlerts()
    {
        try {
            $stmt = db()->query("
                SELECT *
                FROM institutional_alerts
                WHERE is_active = 1
                  AND triggered_at IS NULL
                ORDER BY created_at ASC
            ");

            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            return [];
        }
    }

    public static function toggleAlert($alertId, $userId)
    {
        try {
            $stmt = db()->prepare("
                UPDATE institutional_alerts
                SET is_active = CASE WHEN is_active = 1 THEN 0 ELSE 1 END,
                    updated_at = NOW()
                WHERE id = ?
                  AND user_id = ?
            ");

            return $stmt->execute([(int)$alertId, (int)$userId]);
        } catch (Throwable $e) {
            return false;
        }
    }

    public static function deleteAlert($alertId, $userId)
    {
        try {
            $stmt = db()->prepare("
                DELETE FROM institutional_alerts
                WHERE id = ?
                  AND user_id = ?
            ");

            return $stmt->execute([(int)$alertId, (int)$userId]);
        } catch (Throwable $e) {
            return false;
        }
    }

    public static function generateAlertKey($symbol, $timeframe, $plan)
    {
        return md5(
            $symbol . '|' .
            $timeframe . '|' .
            ($plan['direction'] ?? $plan['side'] ?? '') . '|' .
            ($plan['entry_low'] ?? '') . '|' .
            ($plan['entry_high'] ?? '') . '|' .
            ($plan['stop_loss'] ?? '') . '|' .
            ($plan['tp1'] ?? '')
        );
    }

    public static function shouldSendAlert($alert, $newKey)
    {
        return ($alert['last_alert_key'] ?? '') !== $newKey;
    }

    public static function updateAlertKey($alertId, $newKey)
    {
        try {
            $columns = db()->query("SHOW COLUMNS FROM institutional_alerts")->fetchAll(PDO::FETCH_COLUMN);

            if (!in_array('last_alert_key', $columns, true)) {
                return true;
            }

            $stmt = db()->prepare("
                UPDATE institutional_alerts
                SET last_alert_key = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            return $stmt->execute([$newKey, (int)$alertId]);
        } catch (Throwable $e) {
            return true;
        }
    }
}
