<?php

class WhatsappTrackingService
{
    protected PDO $db;
    protected array $config = [];

    public function __construct()
    {
        $this->db = db();

        $stmt = $this->db->prepare("
            SELECT config
            FROM tracking_integrations
            WHERE provider = 'whatsapp'
              AND is_active = 1
            LIMIT 1
        ");
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            return;
        }

        $this->config = json_decode($row['config'], true) ?: [];
    }

    /**
     * Generate WhatsApp link + store source in session
     */
    public function generateLink(): string
    {
        if (empty($this->config['phone'])) {
            return '#';
        }

        $source = $_GET['utm_source'] ?? 'direct';

        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }

        $_SESSION['whatsapp_source'] = $source;

        $text  = $this->config['message'] ?? '';
        $phone = preg_replace('/[^0-9]/', '', $this->config['phone']);

        return 'https://wa.me/' . $phone . '?text=' . urlencode($text);
    }

    /**
     * Attach WhatsApp source into order extra
     */
    public function attachSourceToOrder(array &$extra): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }

        if (!empty($_SESSION['whatsapp_source'])) {
            $extra['whatsapp'] = [
                'source' => $_SESSION['whatsapp_source']
            ];

            unset($_SESSION['whatsapp_source']);
        }
    }
}
