<?php
header('Content-Type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

$topic = trim($data['topic'] ?? '');
$email = trim($data['email'] ?? '');
$subject = trim($data['subject'] ?? '');
$message = trim($data['message'] ?? '');

if (!$topic || !$email || !$subject || !$message) {
    echo json_encode(['success' => false, 'message' => 'All fields are required']);
    exit;
}
 require('dbcon.php');
try {
    

    $stmt = $pdo->prepare("INSERT INTO live_chat (topic, email, subject, message, created_at) VALUES (?, ?, ?, ?, NOW())");
    $stmt->execute([$topic, $email, $subject, $message]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

// --- Send email notification ---
$to = 'support@amstapay.com';
$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

$email_subject = "Live Chat: $subject ($topic)";
$email_body = "You have received a new live chat message.\n\n";
$email_body .= "Topic: $topic\n";
$email_body .= "Email: $email\n";
$email_body .= "Subject: $subject\n";
$email_body .= "Message:\n$message\n";

mail($to, $email_subject, $email_body, $headers);

echo json_encode(['success' => true]);
