<?php
declare(strict_types=1);

/* ================= CONFIG & CORE ================= */
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';
require_once __DIR__ . '/../../core/Validator.php';

$db = Database::getInstance();

/* ================= METHOD CHECK ================= */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Response::error('Invalid request method', 405);
}

/* ================= INPUT ================= */
$data = json_decode(file_get_contents('php://input'), true);

/* ================= VALIDATION ================= */
Validator::required($data, ['email']);

$email = strtolower(trim($data['email']));
$name  = trim($data['name'] ?? null);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    Response::error('Invalid email address', 422);
}

/* ================= METADATA ================= */
$ipAddress   = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$userAgent  = substr($_SERVER['HTTP_USER_AGENT'] ?? null, 0, 512);
$referrer   = substr($_SERVER['HTTP_REFERER'] ?? null, 0, 512);
$sourcePage = substr($data['source_page_url'] ?? null, 0, 512);

/* ================= UTM (OPTIONAL) ================= */
$utmSource   = $data['utm_source'] ?? null;
$utmMedium   = $data['utm_medium'] ?? null;
$utmCampaign = $data['utm_campaign'] ?? null;

/* ================= DUPLICATE CHECK ================= */
$stmt = $db->prepare("
    SELECT id, is_active
    FROM website_subscribers
    WHERE email = :email
");
$stmt->execute(['email' => $email]);
$existing = $stmt->fetch();

if ($existing) {

    if ((int)$existing['is_active'] === 1) {
        Response::success('You are already subscribed');
    }

    /* Reactivate subscription */
    $stmt = $db->prepare("
        UPDATE website_subscribers
        SET
            is_active = 1,
            unsubscribed_at = NULL,
            subscribed_at = NOW()
        WHERE id = :id
    ");
    $stmt->execute(['id' => $existing['id']]);

    Response::success('Subscription reactivated successfully');
}

/* ================= INSERT ================= */
$stmt = $db->prepare("
    INSERT INTO website_subscribers (
        name,
        email,
        source_page_url,
        referrer_url,
        campaign,
        medium,
        source,
        ip_address,
        user_agent,
        consent_given,
        subscribed_at
    ) VALUES (
        :name,
        :email,
        :source_page,
        :referrer,
        :campaign,
        :medium,
        :source,
        :ip_address,
        :user_agent,
        1,
        NOW()
    )
");

$stmt->execute([
    'name'        => $name,
    'email'       => $email,
    'source_page' => $sourcePage,
    'referrer'    => $referrer,
    'campaign'    => $utmCampaign,
    'medium'      => $utmMedium,
    'source'      => $utmSource,
    'ip_address'  => $ipAddress,
    'user_agent'  => $userAgent
]);

Response::success('Subscribed successfully');
