<?php
header('Content-Type: application/json');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

include 'config.php';
require 'vendor/autoload.php'; 

$email = mysqli_real_escape_string($conn, $_POST['email']);
$query = "
    SELECT users.id, users.username, users.email, document_status.status, document_status.document_id 
    FROM users 
    JOIN document_status ON users.id = document_status.employee_id  
    WHERE users.email = '$email'
";

$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);


if ($user && $user['status'] == 'Submitted') {

$mail = new PHPMailer(true);

try {

    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';  
    $mail->SMTPAuth   = true;
    $mail->Username   = 'prabhakaran.cirs@gmail.com'; 
    $mail->Password   = 'rvlgkmpmyugdswqp';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
    $mail->Port       = 587; 
    $mail->CharSet = 'UTF-8';
    $mail->Encoding = 'base64';

    
    $mail->setFrom('prabhakaran.cirs@gmail.com', 'Your Name');
    $mail->addAddress($_POST['email'], $_POST['username']);
    
    // Email subject and body
    $mail->Subject = $_POST['status'];
    $mail->Body    = 'You have agreed our company policies';
    $mail->IsHTML(true);

    // Generate PDF file
    $documentPath = "generated_docs/document_{$_POST['document_id']}.pdf";
    exec("php generate_pdf.php {$_POST['document_id']} {$_POST['user_id']} $documentPath");

    // Attach PDF if exists
    if (file_exists($documentPath)) {
        $mail->addAttachment($documentPath);
    } else {
        throw new Exception("PDF file not found: $documentPath");
    }

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

   
    echo json_encode([
        "status" => 200,
        "message" => "Email sent successfully"
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        "status" => 500,
        "message" => "Email failed: " . $e->getMessage()
    ]);
}

}else{
    echo json_encode([
        "status" => 404,
        "message" => "User not found or document not submitted"
    ]);
}
?>
