<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $to = "manojbafna@buildunique.in";
    $subject = "New Project Inquiry - BuildUnique";

    // Sanitize inputs
    $name = trim($_POST["name"] ?? '');
    $email = trim($_POST["email"] ?? '');
    $phone = trim($_POST["phone"] ?? '');
    $message = trim($_POST["message"] ?? '');

    // Validation
    if ($name === '' || $email === '' || $phone === '' || $message === '') {
        http_response_code(400);
        echo "All required fields must be filled.";
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Invalid email address.";
        exit;
    }

    // Email body
    $body = "📩 New project inquiry from BuildUnique Website:\n\n";
    $body .= "👤 Name: $name\n";
    $body .= "📧 Email: $email\n";
    $body .= "📞 Phone: $phone\n";
    $body .= "📝 Message:\n$message\n";

    // ✅ Handle File Upload
    if (!empty($_FILES["attachment"]["name"])) {
        $allowedTypes = [
            'jpg','jpeg','png','pdf','doc','docx','xls','xlsx','dwg','zip','rar'
        ];
        $maxSize = 1024 * 1024 * 1024; // 1GB in bytes

        $fileName = $_FILES["attachment"]["name"];
        $fileSize = $_FILES["attachment"]["size"];
        $fileTmp  = $_FILES["attachment"]["tmp_name"];
        $fileExt  = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (!in_array($fileExt, $allowedTypes)) {
            http_response_code(400);
            echo "File type not allowed. Allowed: jpg, png, pdf, docx, xlsx, dwg, zip, rar.";
            exit;
        }

        if ($fileSize > $maxSize) {
            http_response_code(400);
            echo "File too large. Max allowed size is 1GB.";
            exit;
        }

        $uploadDir = __DIR__ . "/uploads/";
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $newName = time() . "_" . preg_replace("/[^a-zA-Z0-9\._-]/", "_", $fileName);
        $targetPath = $uploadDir . $newName;

        if (move_uploaded_file($fileTmp, $targetPath)) {
            $fileUrl = "https://" . $_SERVER['HTTP_HOST'] . "/uploads/" . $newName;
            $body .= "\n📎 Attachment: $fileUrl\n";
        } else {
            $body .= "\n⚠️ Attachment upload failed.\n";
        }
    }

    // Headers
    $headers = "From: BuildUnique <no-reply@" . $_SERVER['SERVER_NAME'] . ">\r\n";
    $headers .= "Reply-To: $email\r\n";

    // Send mail
    if (mail($to, $subject, $body, $headers)) {
        echo "success";
    } else {
        http_response_code(500);
        echo "Mail not sent. Check server mail configuration.";
    }
}
?>
