<?php

$to = "info.w3bmakers@gmail.com";
$subject = "Nová poptávka z webu W3bMakers";

header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    $name = htmlspecialchars(strip_tags(trim($_POST["name"] ?? '')));
    $email = filter_var(trim($_POST["email"] ?? ''), FILTER_SANITIZE_EMAIL);
    $type = htmlspecialchars(strip_tags(trim($_POST["project_type"] ?? '')));
    $message = htmlspecialchars(strip_tags(trim($_POST["message"] ?? '')));
    
    if (empty($name) || empty($email) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "Vyplňte prosím všechna povinná pole správně."]);
        exit;
    }
    
    $email_content = "Nová poptávka z webu:\n\n";
    $email_content .= "Jméno: $name\n";
    $email_content .= "E-mail: $email\n";
    $email_content .= "Typ projektu: $type\n\n";
    $email_content .= "Zpráva:\n$message\n";
  
    require 'phpmailer/Exception.php';
    require 'phpmailer/PHPMailer.php';
    require 'phpmailer/SMTP.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {

        $mail->isSMTP();
        $mail->Host       = 'smtp.resend.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'resend';

        $mail->Password   = 're_9a2WKA9d_JvxiHpyJFgJnYmWTtYAk4UVj';
        
        $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        $mail->setFrom('info@w3bmakers.cz', 'W3bMakers Web');
        $mail->addAddress($to);
        $mail->addReplyTo($email, $name);

        $mail->isHTML(false);
        $mail->Subject = $subject;
        $mail->Body    = $email_content;
        $mail->CharSet = 'UTF-8';

        $mail->send();
        http_response_code(200);
        echo json_encode(["status" => "success", "message" => "Zpráva byla úspěšně odeslána."]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(["status" => "error", "message" => "Chyba při odesílání e-mailu. Detail: {$mail->ErrorInfo}"]);
    }

} else {
    http_response_code(403);
    echo json_encode(["status" => "error", "message" => "Nepovolená metoda."]);
}
?>