<?php
require_once '../inc/dbconn.php';
//require_once '../../vendor/autoload.php'; 

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Validate required fields
$required = ['name', 'email', 'subject', 'message', 'phone'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => "Please fill in all required fields"]);
        exit;
    }
}

// Sanitize and validate inputs
$name = htmlspecialchars(trim($_POST['name']));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$subject = htmlspecialchars(trim($_POST['subject']));
$message = htmlspecialchars(trim($_POST['message']));
$phone = htmlspecialchars(trim($_POST['phone']));

if (!$email) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address']);
    exit;
}

try {
    // Save to database
    $sql = "INSERT INTO contact_messages 
            (name, email, subject, message, phone, created_at, ip_address) 
            VALUES (:name, :email, :subject, :message, :phone, NOW(), :ip_address)";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':name' => $name,
        ':email' => $email,
        ':subject' => $subject,
        ':message' => $message,
        ':phone' => $phone,
        ':ip_address' => $_SERVER['REMOTE_ADDR'] ?? ''
    ]);
    
    $messageId = $pdo->lastInsertId();
    
    // Send confirmation email to user
    //$userMailSent = sendConfirmationEmail($email, $name, $subject, $messageId);
    
    // Send notification to admin (optional)
    //$adminMailSent = sendAdminNotification($name, $email, $phone, $subject, $message);
    
    echo json_encode([
        'success' => true, 
        'message' => 'Thank you for your message! We have received it and will get back to you soon.',
        'message_id' => $messageId
    ]);
    
} catch(PDOException $e) {
    error_log("Contact form error: " . $e->getMessage());
    echo json_encode([
        'success' => false, 
        'message' => 'An error occurred while submitting your message. Please try again later.'
    ]);
}

function sendConfirmationEmail($toEmail, $toName, $subject, $messageId) {
    try {
        $mail = new PHPMailer;
        
        // Configure your SMTP settings here
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com'; // Your SMTP host
        $mail->SMTPAuth = true;
        $mail->Username = 'your-email@gmail.com'; // Your email
        $mail->Password = 'your-password'; // Your email password or app password
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        
        // Email content
        $mail->setFrom('noreply@joysoundsacademy.com', 'Joy Sounds Academy');
        $mail->addAddress($toEmail, $toName);
        $mail->addReplyTo('info@joysoundsacademy.com', 'Joy Sounds Academy');
        
        $mail->isHTML(true);
        $mail->Subject = 'We Have Received Your Message - Joy Sounds Academy';
        
        $emailBody = "
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #7A1E2B; color: white; padding: 20px; text-align: center; }
                .content { padding: 30px; background-color: #f9f9f9; }
                .footer { background-color: #333; color: white; padding: 20px; text-align: center; font-size: 12px; }
                .message-box { background: white; padding: 20px; border-left: 4px solid #7A1E2B; margin: 20px 0; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1>Joy Sounds Academy</h1>
                </div>
                <div class='content'>
                    <h2>Thank You for Contacting Us!</h2>
                    <p>Dear $toName,</p>
                    <p>We have successfully received your message with the following details:</p>
                    
                    <div class='message-box'>
                        <p><strong>Reference ID:</strong> #$messageId</p>
                        <p><strong>Subject:</strong> $subject</p>
                        <p><strong>Message Received:</strong> " . date('F j, Y, g:i a') . "</p>
                    </div>
                    
                    <p>Our team will review your message and get back to you within 24-48 hours.</p>
                    <p>If you have any urgent inquiries, please call us at [Your Phone Number].</p>
                    
                    <p>Best regards,<br>
                    <strong>The Joy Sounds Academy Team</strong></p>
                </div>
                <div class='footer'>
                    <p>&copy; " . date('Y') . " Joy Sounds Academy. All rights reserved.</p>
                    <p>This is an automated message, please do not reply to this email.</p>
                </div>
            </div>
        </body>
        </html>
        ";
        
        $mail->Body = $emailBody;
        
        // Plain text version for non-HTML email clients
        $mail->AltBody = "Thank you for contacting Joy Sounds Academy!\n\n" .
                        "Dear $toName,\n\n" .
                        "We have received your message with the following details:\n" .
                        "Reference ID: #$messageId\n" .
                        "Subject: $subject\n" .
                        "Message Received: " . date('F j, Y, g:i a') . "\n\n" .
                        "Our team will review your message and get back to you within 24-48 hours.\n\n" .
                        "Best regards,\n" .
                        "The Joy Sounds Academy Team\n\n" .
                        "© " . date('Y') . " Joy Sounds Academy. All rights reserved.";
        
        return $mail->send();
        
    } catch (Exception $e) {
        error_log("Confirmation email error: " . $e->getMessage());
        return false;
    }
}

function sendAdminNotification($name, $email, $phone, $subject, $message) {
    // Similar function to send email to admin
    // Implement based on your needs
    return true;
}
?>