All files / components/forms register-form.tsx

32.35% Statements 22/68
32.35% Branches 11/34
37.5% Functions 3/8
33.33% Lines 22/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 3591x               1x   1x 5x                     5x 5x 5x   5x     2x     5x       5x 2x 2x 2x   2x 1x 1x     1x 1x 1x             5x                                                                                                                                                                                                                                                                                                             5x                                                                                                                                                                                                                                                                                                                
"use client";
import React, { useState } from "react";
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css"; // Import styles
import { Container } from "./container";
import { Button } from "@/components/ui/button";
 
 
const adminEmail = process.env.NEXT_PUBLIC_ADMIN_EMAIL || "amitnandileo@gmail.com";
 
export const RegisterForm = () => {
  const [formData, setFormData] = useState({
    firstname: "",
    lastname: "",
    email: "",
    phone: "",
    company: "",
    service: "",
    enquirytype: "",
    honeysecretpot: "", // Honeypot field
  });
 
  const [vcFile, setVcFile] = useState<File | null>(null);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState<string | null>(null);
 
  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  ) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };
 
  const handlePhoneChange = (value: string) => {
    setFormData({ ...formData, phone: value });
  };
 
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    Eif (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      const allowedTypes = ["application/pdf", "image/jpeg", "image/png"];
 
      if (!allowedTypes.includes(file.type)) {
        alert("Invalid file type. Please upload a PDF or image.");
        return;
      }
 
      Eif (file.size > 2 * 1024 * 1024) { // 2MB limit
        alert("File size exceeds 2MB. Please upload a smaller file.");
        return;
      }
 
      setVcFile(file);
    }
  };
 
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
 
    if (formData.honeysecretpot) {
      console.warn("Spam detected! Submission blocked.");
      return;
    }
 
    setLoading(true);
    let uploadedFileId = null;
 
    try {
      // **Step 1: Upload File First (If Exists)**
      if (vcFile) {
        const fileFormData = new FormData();
        fileFormData.append("files", vcFile);
 
        const fileResponse = await fetch(
          `${process.env.NEXT_PUBLIC_STRAPI_BASE_URL}/api/upload`,
          {
            method: "POST",
            body: fileFormData,
          }
        );
 
        if (!fileResponse.ok) {
          throw new Error("File upload failed.");
        }
 
        const fileData = await fileResponse.json();
        uploadedFileId = fileData[0].id; // Get uploaded file ID
        console.log("File uploaded successfully. Media ID:", uploadedFileId);
      }
 
      // **Step 2: Submit Form Data (with File ID)**
      const submissionData = {
        data: {
          firstname: formData.firstname,
          lastname: formData.lastname,
          email: formData.email,
          phone: formData.phone,
          company: formData.company,
          service: formData.service,
          enquirytype: formData.enquirytype,
          vcfile: uploadedFileId ? uploadedFileId : null, // Attach uploaded file ID if exists
        },
      };
 
      const response = await fetch(
        `${process.env.NEXT_PUBLIC_STRAPI_BASE_URL}/api/registration-form-submissions`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(submissionData),
        }
      );
 
      if (!response.ok) {
        throw new Error("Form submission failed.");
      }
 
      const responseData = await response.json();
      const submissionId = responseData.data.id;
      console.log("Form submission successful. ID:", submissionId);
 
      // **Step 3: Send Confirmation Email to User**
      const emailResponse = await fetch(`/api/email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          to: formData.email,
          subject: "Thank You for contacting Bitmutex",
          message: `Hi <b>${formData.firstname}</b>,<br><br>
            Thank you for registering with Bitmutex Technologies! We have received your details, expect a call from us.<br><br>
            In the meantime, feel free to download our brochure <a href="https://bitmutex.com/brochure">here</a>.<br><br>
            Best Regards,<br>
            Team Bitmutex`,
        }),
      });
 
      if (!emailResponse.ok) {
        throw new Error("Failed to send email to user.");
      }
 
      // **Step 4: Wait Before Sending Admin Email**
      await new Promise((resolve) => setTimeout(resolve, 2000));
 
      // **Step 5: Send Email Notification to Admin**
      let attachmentData = null;
      if (vcFile) {
        const reader = new FileReader();
        attachmentData = await new Promise((resolve) => {
          reader.readAsDataURL(vcFile);
          reader.onload = () => resolve(reader.result);
        });
      }
 
      const emailResponseAdmin = await fetch(`/api/email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          to: adminEmail,
          subject: "New Registration Form Submission (With CV Attachment)",
          message: `🚀 New Registration Form Submission with CV attached PFA. 🚀 <br>
                    📌 **First Name:** ${formData.firstname}<br>
                    📌 **Last Name:** ${formData.lastname}<br>
                    📌 **Email:** ${formData.email}<br>
                    📌 **Phone:** ${formData.phone}<br>
                    📌 **Company:** ${formData.company}<br>
                    📌 **Service Opted:** ${formData.service}<br>
                    📌 **Enquiry Type:** ${formData.enquirytype}<br>
                    🔍 Please review and take necessary action.<br>
                    Best Regards,<br> Bitmutex Bot 🤖`,
          attachments: vcFile
            ? [
              {
                filename: vcFile.name,
                content: attachmentData,
                encoding: "base64",
              },
            ]
            : [],
        }),
      });
 
      if (!emailResponseAdmin.ok) {
        throw new Error("Failed to send admin email with attachment.");
      }
 
      setSuccess("Registration Successful!");
 
      // **Step 6: Reset Form**
      setFormData({
        firstname: "",
        lastname: "",
        email: "",
        phone: "",
        company: "",
        service: "",
        enquirytype: "",
        honeysecretpot: "",
      });
      setVcFile(null);
    } catch (error) {
      console.error(error);
      setSuccess("Error submitting form.");
    }
 
    setLoading(false);
  };
 
  return (
    <Container className="h-full max-w-lg mx-auto flex flex-col items-center justify-center">
      <h1 className="text-xl font-heading font-bold md:text-4xl font-bold my-4 text-slate-800 dark:text-orange-400">Request a Quote</h1>
      <form className="w-full my-4" onSubmit={handleSubmit}>
        <div className="flex gap-4 mb-4">
          <input
            type="text"
            name="firstname"
            placeholder="First Name"
            value={formData.firstname}
            onChange={handleChange}
            required
            className="h-10 pl-4 w-1/2 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
          />
          <input
            type="text"
            name="lastname"
            placeholder="Last Name"
            value={formData.lastname}
            onChange={handleChange}
            required
            className="h-10 pl-4 w-1/2 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
          />
        </div>
        <input
          type="email"
          name="email"
          placeholder="Email"
          value={formData.email}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
        />
 
        <div className="mb-4">
          <PhoneInput
            country={"in"}
            value={formData.phone}
            onChange={handlePhoneChange}
            inputStyle={{
              width: "100%",
              height: "40px",
              borderRadius: "6px",
              border: "1px solid #333",
              paddingLeft: "50px",
              backgroundColor: "white",
              color: "black",
            }}
            buttonStyle={{
              borderRadius: "6px 0 0 6px",
              borderRight: "1px solid #333",
            }}
          />
        </div>
 
        <input
          type="text"
          name="company"
          placeholder="Company Name"
          value={formData.company}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
        />
        <label htmlFor="service" className="block text-sm font-medium text-gray-700 dark:text-slate-300">
          Service Opted
        </label>
        <select
          id="service"
          name="service"
          value={formData.service}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
        >
          <option value="" disabled>
            Select Service
          </option>
          <option value="Web">Web</option>
          <option value="Mobile">Mobile</option>
          <option value="Cross Platform">Cross Platform</option>
          <option value="Mobile">Mobile</option>
          <option value="Backend">Backend</option>
          <option value="Data Driven">Data Driven</option>
 
        </select>
 
        <label htmlFor="enquirytype" className="block text-sm font-medium text-gray-700 dark:text-slate-300">
          Enquiry Type
        </label>
        <select
          id="enquirytype"
          name="enquirytype"
          value={formData.enquirytype}
          onChange={handleChange}
          required
          className="h-10 pl-4 w-full mb-4 rounded-md text-sm bg-white border border-neutral-800 text-black placeholder-gray-500 outline-none focus:ring-2 focus:ring-neutral-800 dark:focus:ring-orange-300"
        >
          <option value="" disabled>
            Select Enquiry Type
          </option>
 
          <option value="New Proposal">New Proposal</option>
          <option value="Existing Project">Existing Project</option>
          <option value="Support">Support</option>
          <option value="Billing">Billing</option>
          <option value="Operations">Operations</option>
        </select>
 
        <div className="mb-4">
          <label htmlFor="file-upload" className="block text-sm font-medium text-gray-700 dark:text-slate-300 ">
            Upload Proposal/ Relevant Files(PDF/IMG)
          </label>
          <span className="sr-only">Upload a CV file</span> {/* Screen reader-friendly label */}
          <div className="relative mt-2">
            <input
              id="file-upload"
              type="file"
              accept=".pdf,.jpg,.jpeg,.png"
              onChange={handleFileChange}
              className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
            />
            <div className="flex items-center justify-between bg-gray-100 border border-gray-300 rounded-lg px-4 py-2 cursor-pointer hover:bg-gray-200 transition">
              <span className="text-sm text-gray-700">
                {vcFile ? vcFile.name : "Choose a file..."}
              </span>
              <span className="bg-neutral-800 text-white px-3 py-1 rounded-lg text-xs font-semibold">
                Browse
              </span>
            </div>
          </div>
        </div>
 
        {/* Honeypot Field */}
        <input
          type="text"
          name="honeysecretpot"
          value={formData.honeysecretpot}
          onChange={handleChange}
          className="hidden"
          autoComplete="off"
          aria-hidden="true"
        />
 
 
        <Button variant="default" type="submit" className="w-full py-3" disabled={loading}>
          <span className="text-sm">{loading ? "Submitting..." : "Submit"}</span>
        </Button>
      </form>
      {success && <p className="text-sm text-green-500">{success}</p>}
    </Container>
  );
};