<?php
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Validate and sanitize input data
$ticket_id = mysqli_real_escape_string($admin_con, $_POST['ticket_id']);
$message = mysqli_real_escape_string($admin_con, $_POST['replyContent']);
$client_id = $_POST['client_id'];
$attachment = null;

// Define upload directory for attachments
$uploadDir = '../../../admin.enrep.co.uk/ticket_files/';
if (!is_dir($uploadDir)) {
    if (mkdir($uploadDir, 0755, true)) {
        echo "Directory created: $uploadDir";
    } else {
        echo "Failed to create directory: $uploadDir";
        exit;
    }
}

// Handle file upload
if (isset($_FILES['replyAttachment']) && $_FILES['replyAttachment']['error'] === UPLOAD_ERR_OK) {
    $fileName = uniqid() . '_' . basename($_FILES['replyAttachment']['name']);
    $targetFilePath = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES['replyAttachment']['tmp_name'], $targetFilePath)) {
        $attachment = $fileName;
    } else {
        echo "Failed to move file to $targetFilePath";
        exit;
    }
}

// Insert the reply into the database
$query = "INSERT INTO support_ticket_replies (ticket_id, sender_type, message, attachment, date_sent) 
          VALUES ('$ticket_id', 'Client', '$message', '$attachment', NOW())";

if (mysqli_query($admin_con, $query)) {
    echo "success";
} else {
    echo "error: " . mysqli_error($admin_con);
}
?>