<?php

declare(strict_types=1);

use GalpaoImperial\Api\Database;
use GalpaoImperial\Api\HttpException;
use function GalpaoImperial\Api\corsPreflight;
use function GalpaoImperial\Api\ensureMethod;
use function GalpaoImperial\Api\jsonBody;
use function GalpaoImperial\Api\jsonResponse;

corsPreflight($method);
$section = $segments[1] ?? '';

if ($section !== 'click') {
    throw new HttpException(404, 'Recurso de promotor não encontrado.');
}

ensureMethod('POST', $method);
$payload = jsonBody();
$code = trim((string) ($payload['code'] ?? ''));
if ($code === '') {
    throw new HttpException(422, 'Código do promotor não informado.');
}

$pdo = Database::connection();
$pdo->exec("CREATE TABLE IF NOT EXISTS promoter_clicks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    promoter_id INT NOT NULL,
    code VARCHAR(40) NOT NULL,
    landing_url VARCHAR(1000) DEFAULT NULL,
    referrer_url VARCHAR(1000) DEFAULT NULL,
    ip_address VARCHAR(80) DEFAULT NULL,
    user_agent VARCHAR(500) DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    KEY idx_promoter_clicks_promoter_id (promoter_id),
    KEY idx_promoter_clicks_code (code)
)");

$promoterStmt = $pdo->prepare('SELECT id, code, is_active FROM promoters WHERE code = :code LIMIT 1');
$promoterStmt->execute(['code' => $code]);
$promoter = $promoterStmt->fetch();

if (!$promoter || !(bool) ($promoter['is_active'] ?? false)) {
    jsonResponse(['success' => true, 'data' => ['tracked' => false, 'reason' => 'promoter_not_found']]);
}

$userAgent = substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 500);
$ipAddress = substr((string) ($_SERVER['REMOTE_ADDR'] ?? ''), 0, 80);
$landingUrl = substr((string) ($payload['landingUrl'] ?? ''), 0, 1000);
$referrer = substr((string) ($payload['referrer'] ?? ''), 0, 1000);

$columnRows = $pdo->query('SHOW COLUMNS FROM promoter_clicks')->fetchAll() ?: [];
$columns = array_map(static fn (array $row): string => (string) $row['Field'], $columnRows);
$has = static fn (string $column): bool => in_array($column, $columns, true);

$insertColumns = ['promoter_id', 'code'];
$params = [
    'promoter_id' => (int) $promoter['id'],
    'code' => $code,
];

foreach ([
    'landing_url' => $landingUrl !== '' ? $landingUrl : null,
    'referrer_url' => $referrer !== '' ? $referrer : null,
    'referrer' => $referrer !== '' ? $referrer : null,
    'ip_address' => $ipAddress !== '' ? $ipAddress : null,
    'user_agent' => $userAgent !== '' ? $userAgent : null,
] as $column => $value) {
    if ($has($column)) {
        $insertColumns[] = $column;
        $params[$column] = $value;
    }
}
if ($has('created_at')) {
    $insertColumns[] = 'created_at';
}

$placeholders = array_map(static fn (string $column): string => $column === 'created_at' ? 'NOW()' : ':' . $column, $insertColumns);
$stmt = $pdo->prepare('INSERT INTO promoter_clicks (' . implode(', ', $insertColumns) . ') VALUES (' . implode(', ', $placeholders) . ')');
$stmt->execute($params);

jsonResponse(['success' => true, 'data' => ['tracked' => true, 'code' => $code]]);
