<?php
include('connection.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $subject = $_POST["subject"];
  $message = $_POST["message"];
  $currentDateTime = date('Y-m-d H:i:s');
  $targetDirectory = "uploads/";
  $targetFile = $targetDirectory . basename($_FILES["attachment"]["name"]);
  $status = isset($_POST["status"]) ? $_POST["status"] : '';

  if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFile)) {
    $subject = mysqli_real_escape_string($conn, $subject);
    $message = mysqli_real_escape_string($conn, $message);
    $filename = basename($targetFile); // Extract the file name
    $filename = mysqli_real_escape_string($conn, $filename); // Sanitize the file name
    $query = "INSERT INTO compose (subject, message, attachment, date_time, status) VALUES ('$subject', '$message', '$filename', '$currentDateTime', '$status')";

    if (mysqli_query($conn, $query)) {
      // Insertion was successful
      $response = array("status" => "success", "action" => $status);
    } else {
      // Insertion failed
      $response = array("status" => "error");
    }

    // Return the JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
  } else {
    // File upload failed
    error_log("File upload failed: " . $_FILES["attachment"]["error"]);
    $response = array("status" => "error_upload");
    // Return the JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}
}

mysqli_close($conn);
?>
