<?php
/* ═══════════════════════════════════════════════════
   QELNIX — contact.php
   Agent signup form handler
═══════════════════════════════════════════════════ */

require_once __DIR__ . '/config.php';

// CORS
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(405, 'Method not allowed');
}

// ── Parse body ──
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    respond(400, 'Invalid JSON');
}

// ── Validate ──
$email = filter_var(trim($data['email'] ?? ''), FILTER_VALIDATE_EMAIL);
if (!$email) {
    respond(422, 'Email non valida');
}

$name = htmlspecialchars(strip_tags(trim($data['name'] ?? '')), ENT_QUOTES, 'UTF-8');
$type = in_array($data['type'] ?? '', ['agent_signup', 'contact']) ? $data['type'] : 'agent_signup';

// ── Rate limit (file-based) ──
$ip       = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
$cacheDir = __DIR__ . '/../cache/';
if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);

$cacheFile = $cacheDir . 'rl_' . md5($ip) . '.json';
$rlData    = file_exists($cacheFile) ? json_decode(file_get_contents($cacheFile), true) : ['count' => 0, 'window_start' => time()];

if (time() - $rlData['window_start'] > RATE_WINDOW) {
    $rlData = ['count' => 0, 'window_start' => time()];
}

if ($rlData['count'] >= RATE_LIMIT) {
    respond(429, 'Troppe richieste. Riprova tra un\'ora.');
}

$rlData['count']++;
file_put_contents($cacheFile, json_encode($rlData));

// ── Log submission ──
$logDir  = __DIR__ . '/../logs/';
if (!is_dir($logDir)) mkdir($logDir, 0755, true);

$logLine = json_encode([
    'ts'    => date('c'),
    'email' => $email,
    'name'  => $name,
    'type'  => $type,
    'ip'    => $ip,
]) . PHP_EOL;

file_put_contents($logDir . 'signups.log', $logLine, FILE_APPEND | LOCK_EX);

// ── Send notification email ──
$subject = $type === 'agent_signup'
    ? '[QELNIX] Nuova richiesta agente: ' . $email
    : '[QELNIX] Nuovo contatto: ' . $email;

$body = buildEmailBody($email, $name, $type, $ip);

// Attempt PHP mail (replace with PHPMailer/SMTP in production)
$sent = mail(
    NOTIFY_EMAIL,
    $subject,
    $body,
    implode("\r\n", [
        'From: ' . SMTP_FROM,
        'Reply-To: ' . $email,
        'Content-Type: text/html; charset=UTF-8',
        'X-Mailer: QELNIX/1.0'
    ])
);

// ── Auto-reply to user ──
$replyBody = buildAutoReply($email, $name);
mail($email, 'Benvenuto in QELNIX — Richiesta ricevuta', $replyBody, implode("\r\n", [
    'From: ' . SMTP_FROM,
    'Content-Type: text/html; charset=UTF-8',
]));

respond(200, 'Richiesta inviata con successo', ['sent' => $sent]);

// ── Helpers ──
function respond(int $code, string $message, array $extra = []): void {
    http_response_code($code);
    echo json_encode(array_merge(['status' => $code < 400 ? 'ok' : 'error', 'message' => $message], $extra));
    exit;
}

function buildEmailBody(string $email, string $name, string $type, string $ip): string {
    $date = date('d/m/Y H:i:s');
    $typeLabel = $type === 'agent_signup' ? 'Richiesta Agente' : 'Contatto';
    return <<<HTML
<!DOCTYPE html>
<html><body style="font-family:sans-serif;background:#020c1b;color:#fff;padding:40px;">
<h2 style="color:#00d4ff;">QELNIX — Nuova {$typeLabel}</h2>
<table style="border-collapse:collapse;width:100%;">
  <tr><td style="padding:8px;color:#aaa;">Email</td><td style="padding:8px;">{$email}</td></tr>
  <tr><td style="padding:8px;color:#aaa;">Nome</td><td style="padding:8px;">{$name}</td></tr>
  <tr><td style="padding:8px;color:#aaa;">Tipo</td><td style="padding:8px;">{$typeLabel}</td></tr>
  <tr><td style="padding:8px;color:#aaa;">IP</td><td style="padding:8px;">{$ip}</td></tr>
  <tr><td style="padding:8px;color:#aaa;">Data</td><td style="padding:8px;">{$date}</td></tr>
</table>
</body></html>
HTML;
}

function buildAutoReply(string $email, string $name): string {
    $greeting = $name ? "Ciao {$name}," : "Ciao,";
    return <<<HTML
<!DOCTYPE html>
<html><body style="font-family:sans-serif;background:#020c1b;color:#fff;padding:40px;max-width:600px;margin:0 auto;">
<img src="https://qelnix.com/assets/logo.png" alt="QELNIX" style="height:40px;margin-bottom:32px;" />
<h2 style="color:#00d4ff;">Richiesta ricevuta ✓</h2>
<p style="color:rgba(255,255,255,0.65);line-height:1.75;">{$greeting}<br><br>
Grazie per il tuo interesse in QELNIX. La tua richiesta è stata ricevuta con successo.<br><br>
Il nostro team ti contatterà entro <strong style="color:#fff;">24–48 ore</strong> per illustrarti tutte le opportunità di collaborazione disponibili nella tua città.<br><br>
Nel frattempo puoi esplorare la nostra brochure per conoscere meglio i prodotti e il modello di guadagno.
</p>
<p style="color:rgba(255,255,255,0.4);font-size:13px;margin-top:40px;border-top:1px solid rgba(255,255,255,0.08);padding-top:24px;">
© QELNIX · Energia Condivisa, Futuro Condiviso
</p>
</body></html>
HTML;
}
