<?php
session_start();

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/vendor/autoload.php';

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

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

// ✅ Collect & sanitize input
$name        = trim(htmlspecialchars($_POST['name'] ?? ''));
$phone       = trim(htmlspecialchars($_POST['phone'] ?? ''));
$email       = trim(htmlspecialchars($_POST['email'] ?? ''));
$college     = trim(htmlspecialchars($_POST['college'] ?? ''));
$project     = trim(htmlspecialchars($_POST['project'] ?? ''));
$description = nl2br(htmlspecialchars($_POST['description'] ?? ''));

// ✅ Basic validation
if ($name === '' || $email === '' || $phone === '') {
    echo json_encode([
        'status' => 'failed',
        'message' => 'Required fields are missing'
    ]);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode([
        'status' => 'failed',
        'message' => 'Invalid email format'
    ]);
    exit;
}

$mail = new PHPMailer(true);

try {
    // 🔧 SMTP CONFIG
    $mail->isSMTP();
    $mail->Host       = 'mail.clouddreamstech.in';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'info@clouddreamstech.in';
    $mail->Password   = 'y&Zvy.r2BFX8EQTn';

    // ✅ Recommended SMTP settings
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // 🔐 Sender & recipient
    $mail->setFrom('info@clouddreamstech.in', 'Ilampirai');
    $mail->addAddress('madhumithaclouddreams28@gmail.com', 'Project Team');

    // 📧 Email content
    $mail->isHTML(true);
    $mail->Subject = 'New Contact Form Submission';

    $mail->Body = "
        <html>
        <body style='font-family: Arial, sans-serif;'>
            <h3>New Contact Form Message</h3>
            <p><strong>Name:</strong> {$name}</p>
            <p><strong>Email:</strong> {$email}</p>
            <p><strong>Phone:</strong> {$phone}</p>
            <p><strong>College:</strong> {$college}</p>
            <p><strong>Project:</strong> {$project}</p>
            <p><strong>Description:</strong><br>{$description}</p>
        </body>
        </html>
    ";

    // 🧪 Enable this ONLY for debugging (optional)
    // $mail->SMTPDebug = 2;
    // $mail->Debugoutput = 'error_log';

    $mail->send();

    echo json_encode([
        'status' => 'success',
        'message' => 'Message sent successfully'
    ]);
} catch (Exception $e) {
    echo json_encode([
        'status' => 'failed',
        'message' => 'Mailer Error: ' . $mail->ErrorInfo
    ]);
}
