<?php
// Define recipient email
$to = "developerm4b@gmail.com, info@settlemitra.com"; // Replace with your Gmail address

// Get form values
$fullName = $_POST['fullName'] ?? '';
$email = $_POST['email'] ?? '';
$phone = $_POST['phone'] ?? '';
$jobPosition = $_POST['jobPosition'] ?? '';
$experience = $_POST['experience'] ?? '';
$expectedSalary = $_POST['expectedSalary'] ?? '';
$message = $_POST['message'] ?? '';

// Handle the file upload
if (isset($_FILES['resume']) && $_FILES['resume']['error'] == 0) {
    $file_tmp_name = $_FILES['resume']['tmp_name'];
    $file_name = $_FILES['resume']['name'];
    $file_size = $_FILES['resume']['size'];
    $file_type = $_FILES['resume']['type'];
    $handle = fopen($file_tmp_name, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $encoded_content = chunk_split(base64_encode($content));
} else {
    die("Resume file is missing or upload error occurred.");
}

// Boundary 
$boundary = md5("sanwebe");

// Email subject
$subject = "New Career Application: $fullName";

// Email headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: $fullName <$email>\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";

// Email body
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";

$body_plain = "
Full Name: $fullName
Email: $email
Phone: $phone
Job Position: $jobPosition
Experience: $experience
Expected Salary: $expectedSalary

Message:
$message
";

$body .= chunk_split(base64_encode($body_plain));

// Attachment
$body .= "--$boundary\r\n";
$body .= "Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "X-Attachment-Id: " . rand(1000, 99999) . "\r\n\r\n";
$body .= $encoded_content . "\r\n";
$body .= "--$boundary--";

// Send email
$sent = mail($to, $subject, $body, $headers);

if ($sent) {
    echo "<script>
        alert('Application sent successfully.');
        window.location.href = 'index.php';
    </script>";
} else {
    echo "<script>
        alert('Failed to send application. Please try again.');
        window.history.back();
    </script>";
}

?>
