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

require_once 'db_config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

// Handling multipart/form-data
$userName = strip_tags(trim($_POST['name'] ?? ''));
$emailPrefix = strip_tags(trim($_POST['email_prefix'] ?? 'user'));
$description = strip_tags(trim($_POST['description'] ?? ''));
$stepIds = isset($_POST['steps']) ? json_decode($_POST['steps'], true) : [];

$userEmail = $emailPrefix . '@' . $sender_domain;

if (empty($userName)) {
    http_response_code(400);
    echo json_encode(["success" => false, "message" => "Imię i nazwisko są wymagane."]);
    exit;
}

try {
    $pdo = getDatabaseConnection();

    // Fetch labels for the selected path
    $labels_en = [];
    $ticketType = 'REQ'; // Default

    if (!empty($stepIds)) {
        $placeholders = implode(',', array_fill(0, count($stepIds), '?'));
        $stmt = $pdo->prepare("SELECT label_en, ticket_type FROM wizard_steps WHERE id IN ($placeholders) ORDER BY FIELD(id, $placeholders)");
        $params = array_merge($stepIds, $stepIds);
        $stmt->execute($params);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($results as $row) {
            $labels_en[] = $row['label_en'];
            if (!empty($row['ticket_type'])) {
                $ticketType = $row['ticket_type'];
            }
        }
    }

    $pathString = implode(' -> ', $labels_en);
    $recipient = $recipient_email;

    // Subject must not contain newlines
    $subjectText = "[$ticketType] $pathString";
    $subjectEncoded = "=?UTF-8?B?" . base64_encode($subjectText) . "?=";

    // Boundary for multipart email
    $boundary = md5(time());

    // Email headers
    $email_headers = "MIME-Version: 1.0" . "\r\n";
    $email_headers .= "Content-Type: multipart/mixed; boundary=\"" . $boundary . "\"" . "\r\n";
    $email_headers .= "From: =?UTF-8?B?" . base64_encode($userName) . "?= <$userEmail>" . "\r\n";
    $email_headers .= "Reply-To: $userEmail" . "\r\n";
    $email_headers .= "X-Mailer: PHP/" . phpversion();

    // Email Body Construction
    $email_content = "Please forward this $ticketType to the INS PL Local IT resolver group.\n\n";
    $email_content .= "Ticket Type: [$ticketType]\n";
    $email_content .= "From: $userName ($userEmail)\n";
    $email_content .= "Category Path: $pathString\n\n";
    $email_content .= "Description:\n$description\n\n";
    $email_content .= "Notification: This message was generated by the $company_name ticketing system.\n";

    // Build the message
    $message = "--" . $boundary . "\r\n";
    $message .= "Content-Type: text/plain; charset=\"UTF-8\"" . "\r\n";
    $message .= "Content-Transfer-Encoding: 8bit" . "\r\n\r\n";
    $message .= $email_content . "\r\n";

    // Attachment logic for multiple files
    if (isset($_FILES['attachments'])) {
        $files = $_FILES['attachments'];
        $count = count($files['name']);

        for ($i = 0; $i < $count; $i++) {
            if ($files['error'][$i] == UPLOAD_ERR_OK) {
                $tmpPath = $files['tmp_name'][$i];
                $fileType = $files['type'][$i];
                $fileName = $files['name'][$i];

                $content = file_get_contents($tmpPath);
                $content = chunk_split(base64_encode($content));

                $message .= "--" . $boundary . "\r\n";
                $message .= "Content-Type: " . $fileType . "; name=\"" . $fileName . "\"" . "\r\n";
                $message .= "Content-Disposition: attachment; filename=\"" . $fileName . "\"" . "\r\n";
                $message .= "Content-Transfer-Encoding: base64" . "\r\n\r\n";
                $message .= $content . "\r\n";
            }
        }
    }

    $message .= "--" . $boundary . "--";

    // Send email
    if (mail($recipient, $subjectEncoded, $message, $email_headers)) {
        http_response_code(200);
        echo json_encode(["success" => true, "message" => "Zgłoszenie wysłane!"]);
    } else {
        http_response_code(500);
        echo json_encode(["success" => false, "message" => "Błąd wysyłania wiadomości."]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>