<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require './src/PHPMailer.php';
require './src/SMTP.php';
require './src/Exception.php';

if (isset($_POST['custom_token']) && $_POST['custom_token'] != '') {
    $response = array(
        'status' => 0,
        'message' => 'Form submission failed, please try again.'
    );

    // Attachment file information
    $file_name = $_FILES['cvfile']['name'];
    $file_size = $_FILES['cvfile']['size'];
    $file_type = $_FILES['cvfile']['type'];
    $file_tmp_name = $_FILES['cvfile']['tmp_name'];

    // Read the file content and encode it as base64
    $file_content = base64_encode(file_get_contents($file_tmp_name));

    $fname = isset($_POST['fname']) ? $_POST['fname'] : '';
    $lname = isset($_POST['lname']) ? $_POST['lname'] : '';
    $phone = isset($_POST['phone']) ? $_POST['phone'] : '';
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    //$address = isset($_POST['address']) ? $_POST['address'] : '';
    $cletter = isset($_POST['cletter']) ? $_POST['cletter'] : '';

    $message = "First Name: " . $fname . "\r\nLast Name: " . $lname . "\r\nPhone: " . $phone . "\r\nEmail: " . $email . "\r\nCV: Attached\r\nCover Letter: " . $cletter;

    $subject = "CV - " . $fname . " - Join Our Team MBJ Group";
    $fromname = "MBJ Group";
    $fromemail = 'info@mbjgroup.co.uk';
    $mailto = 'info@mbjgroup.co.uk';

    // Instantiate PHPMailer
    $mail = new PHPMailer(true);

    try {
        // Set up SMTP
        $mail->isSMTP();
        $mail->Host = 'smtp.hostinger.com';
        $mail->Port = 587;
        $mail->SMTPAuth = true;
        $mail->Username = 'info@mbjgroup.co.uk';
        $mail->Password = 'MyLetter@2025';
        $mail->SMTPSecure = 'STARTTLS';

        // Set up email content and headers
        $mail->setFrom($fromemail, $fromname);
        $mail->addAddress($mailto);
        $mail->addCC($email);
        $mail->Subject = $subject;
        $mail->Body = $message;

        // Attach the file
        $mail->addStringAttachment(base64_decode($file_content), $file_name);

        // Send the email
        $mail->send();

        $response['status'] = 1;
        $response['message'] = 'Application submitted successfully!';
    } catch (Exception $e) {
        $response['message'] = 'Message could not be sent. Error: ' . $mail->ErrorInfo;
    }

    echo json_encode($response);
} else {
    echo 'You don\'t have direct access to this page. You will be redirected to the home page in a few seconds.';
    ?>
    <meta http-equiv="refresh" content="5;url=/" />
<?php } ?>
