<?php
session_start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require './PHPMailer/src/Exception.php';
require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
if(isset($_POST['sendMailBtn'])){
    $to = $_POST['to_email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $attachment = $_FILES['attachment']['tmp_name'];
    $emailAttachment = null;
    if($attachment){
        $emailAttachment = 'upload/'. $_FILES['attachment']['name'];
         // Add file type validation
        
        $fileExtension = pathinfo($emailAttachment,PATHINFO_EXTENSION);
        if(!in_array($fileExtension, array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg'))){
            $_SESSION['error_message'] = "Invalid file type: Only pdf, doc, docx, jpg, png, jpeg are allowed";
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        }
       move_uploaded_file($attachment, $emailAttachment);
    }
    sendEmail($to, $subject, $message, $emailAttachment);
}
function sendEmail($to, $subject, $message, $emailAttachment) {
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host = 'smtp.gmail.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'jghomim@gmail.com';
        $mail->Password = 'msfhwacqnjnjhpps'; // <-- which we generated from step2
        $mail->SMTPSecure = 'Auto';
        $mail->Port = 587;
        $mail->setFrom('jghomim@gmail.com'); //<-- 2nd param is optional
        $mail->addAddress($to); //<-- 2nd param is optional
        $mail->isHTML(false); //<-- make it true if sending HTML content as message
        $mail->Subject = $subject;
        $mail->Body = $message;
        if($emailAttachment){
            $mail->addAttachment($emailAttachment);
        }
        $mail->send();
        $_SESSION['success_message'] = "Email Message has been sent successfully";
    }catch (Exception $e){
        $_SESSION['error_message'] =  "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
    header('Location: ' . $_SERVER['HTTP_REFERER']);
} 
?>