<?php
// enviar.php

// Configurações
header('Content-Type: application/json; charset=utf-8');

// Proteção CSRF (adicione em produção)
// session_start();

// Configurações de email
$destinatario = "contato@interacaosocial.com.br"; // ALTERE PARA SEU EMAIL
$assunto_email = "Novo Contato - iGold3D";

// Validação e sanitização
function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

// Verifica se é POST
if (¨D_SERVER["REQUEST_METHOD"] != "POST") {
    echo json_encode([
        'success' => false,
        'message' => 'Método não permitido.'
    ]);
    exit;
}

// Recebe e sanitiza os dados
$nome = isset(¨D_POST['nome']) ? sanitizeInput(¨D_POST['nome']) : '';
$email = isset(¨D_POST['email']) ? sanitizeInput(¨D_POST['email']) : '';
$telefone = isset(¨D_POST['telefone']) ? sanitizeInput(¨D_POST['telefone']) : '';
$assunto = isset(¨D_POST['assunto']) ? sanitizeInput(¨D_POST['assunto']) : '';
$mensagem = isset(¨D_POST['mensagem']) ? sanitizeInput(¨D_POST['mensagem']) : '';

// Validações
$errors = [];

if (empty($nome)) {
    $errors[] = "Nome é obrigatório.";
}

if (empty($email)) {
    $errors[] = "Email é obrigatório.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Email inválido.";
}

if (empty($telefone)) {
    $errors[] = "Telefone é obrigatório.";
}

if (empty($assunto)) {
    $errors[] = "Assunto é obrigatório.";
}

if (empty($mensagem)) {
    $errors[] = "Mensagem é obrigatória.";
}

// Se houver erros, retorna
if (!empty($errors)) {
    echo json_encode([
        'success' => false,
        'message' => implode(' ', $errors)
    ]);
    exit;
}

// Monta o corpo do email em HTML
$corpo_email = "
<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: linear-gradient(135deg, #D4AF37, #B8941F); color: white; padding: 30px; text-align: center; border-radius: 10px 10px 0 0; }
        .content { background: #f9f9f9; padding: 30px; border-radius: 0 0 10px 10px; }
        .field { margin-bottom: 20px; padding: 15px; background: white; border-left: 4px solid #D4AF37; }
        .field-label { font-weight: bold; color: #D4AF37; margin-bottom: 5px; }
        .field-value { color: #333; }
        .footer { text-align: center; margin-top: 30px; padding: 20px; color: #666; font-size: 12px; }
    </style>
</head>
<body>
    <div class='container'>
        <div class='header'>
            <h1>💎 Novo Contato - iGold3D</h1>
        </div>
        <div class='content'>
            <div class='field'>
                <div class='field-label'>Nome:</div>
                <div class='field-value'>$nome</div>
            </div>
            <div class='field'>
                <div class='field-label'>Email:</div>
                <div class='field-value'>$email</div>
            </div>
            <div class='field'>
                <div class='field-label'>Telefone:</div>
                <div class='field-value'>$telefone</div>
            </div>
            <div class='field'>
                <div class='field-label'>Assunto:</div>
                <div class='field-value'>$assunto</div>
            </div>
            <div class='field'>
                <div class='field-label'>Mensagem:</div>
                <div class='field-value'>" . nl2br($mensagem) . "</div>
            </div>
        </div>
        <div class='footer'>
            <p>Esta é uma mensagem automática do formulário de contato da iGold3D</p>
            <p>Data: " . date('d/m/Y H:i:s') . "</p>
        </div>
    </div>
</body>
</html>
";

// Headers do email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: noreply@igold3d.com" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// Envia o email
$email_enviado = mail($destinatario, $assunto_email, $corpo_email, $headers);
//$email_enviado = true; // Força o sucesso para teste local

if ($email_enviado) {
// if ($email_enviado !== false) {
    // Log de sucesso (opcional)
    $log_file = 'contatos_log.txt';
    $log_message = date('Y-m-d H:i:s') . " - Contato de: $nome ($email)\n";
    file_put_contents($log_file, $log_message, FILE_APPEND);

    echo json_encode([
        'success' => true,
        'message' => 'Mensagem enviada com sucesso! Entraremos em contato em breve.'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Erro ao enviar mensagem. Por favor, tente novamente ou entre em contato diretamente pelo WhatsApp.'
    ]);
}
?>