<?php
// Load the correct configuration based on tenant parameter
if (file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

// Retrieve ticket details from POST request
$title = mysqli_real_escape_string($admin_con, $_POST['title']);
$description = mysqli_real_escape_string($admin_con, $_POST['description']);
$priority = mysqli_real_escape_string($admin_con, $_POST['priority']);
$client_id = mysqli_real_escape_string($admin_con, $_POST['client_id']);
$attachmentName = null;  // Default to null if no file is uploaded

// Check if a file was uploaded
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
    $uploadDir = '../../../admin.enrep.co.uk/ticket_files/';
    $attachmentName = basename($_FILES['attachment']['name']);
    $uploadFilePath = $uploadDir . $attachmentName;

    // Move file to the ticket_files directory
    if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadFilePath)) {
        $attachmentName = null;  // Reset to null if upload fails
    }
}

// Insert ticket into the admin support_tickets table with just the filename
$query = "INSERT INTO support_tickets (client_id, title, description, priority, status, date_created, last_updated, attachment) 
          VALUES ('$client_id', '$title', '$description', '$priority', 'Open', NOW(), NOW(), " . ($attachmentName ? "'$attachmentName'" : "NULL") . ")";

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