<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/mail/MailService.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $message = $_POST['message'] ?? '';

    if (empty($name) || empty($email) || empty($message)) {
        die("Please fill in all required fields.");
    }

    try {
        $db = db();
        $stmt = $db->prepare("INSERT INTO leads (name, email, phone, message) VALUES (?, ?, ?, ?)");
        $stmt->execute([$name, $email, $phone, $message]);

        // Send Email
        $mail_to = getenv('MAIL_TO') ?: null;
        $subject = "New Lead from " . $name;
        $content = "Name: $name\nEmail: $email\nPhone: $phone\nMessage: $message";
        MailService::sendMail($mail_to, $subject, nl2br($content), $content);

        // Telegram Notification (Placeholder for actual API call)
        // If telegram bot token and chat id are set in env, we could use curl to send message
        
        echo "<script>alert('提交成功！我们将尽快与您联系。'); window.location.href='/';</script>";
    } catch (PDOException $e) {
        error_log("Database error: " . $e->getMessage());
        echo "<script>alert('系统繁忙，请稍后再试。'); window.history.back();</script>";
    }
} else {
    header("Location: /contact.php");
    exit;
}

