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

function ticketResponse($success, $message)
{
    echo json_encode([
        'success' => $success,
        'message' => $message,
    ]);
    exit;
}

function ticketAttachmentMimeType($filePath)
{
    if (function_exists('mime_content_type')) {
        $mimeType = mime_content_type($filePath);
        if ($mimeType) {
            return $mimeType;
        }
    }

    $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
    $mimeTypes = [
        'jpg' => 'image/jpeg',
        'jpeg' => 'image/jpeg',
        'png' => 'image/png',
        'gif' => 'image/gif',
        'webp' => 'image/webp',
        'pdf' => 'application/pdf',
        'txt' => 'text/plain',
        'csv' => 'text/csv',
        'doc' => 'application/msword',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls' => 'application/vnd.ms-excel',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'zip' => 'application/zip',
    ];

    return $mimeTypes[$extension] ?? 'application/octet-stream';
}

$tenant = $_REQUEST['tenant'] ?? '';

// Load the correct configuration based on tenant parameter
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if ((!isset($admin_con) || !$admin_con) && file_exists('T:/files/db_connect.php')) {
    ob_start();
    require_once 'T:/files/db_connect.php';
    ob_end_clean();
}
if ((!isset($admin_con) || !$admin_con) && file_exists(__DIR__ . '/../../../admin.enrep.co.uk/files/db_connect.php')) {
    ob_start();
    require_once __DIR__ . '/../../../admin.enrep.co.uk/files/db_connect.php';
    ob_end_clean();
}

if (!isset($admin_con) || !$admin_con) {
    ticketResponse(false, "Admin database connection is unavailable.");
}

if (!isset($con) || !$con) {
    ticketResponse(false, "Tenant database connection is unavailable.");
}

// Retrieve ticket details from POST request
$title = trim($_POST['title'] ?? '');
$description = trim($_POST['description'] ?? '');
$priority = trim($_POST['priority'] ?? 'low');
$client_id = (int)($_POST['client_id'] ?? 0);
$attachmentName = null;
$uploadFilePath = '';

if ($title === '' || $description === '' || $client_id <= 0) {
    ticketResponse(false, "Missing required ticket details.");
}

function getTicketUploadDir()
{
    $candidates = [
        'T:/ticket_files/',
        __DIR__ . '/../../../admin.enrep.co.uk/ticket_files/',
    ];

    foreach ($candidates as $dir) {
        if (is_dir($dir)) {
            return rtrim($dir, '/\\') . DIRECTORY_SEPARATOR;
        }
    }

    foreach ($candidates as $dir) {
        if (mkdir($dir, 0755, true)) {
            return rtrim($dir, '/\\') . DIRECTORY_SEPARATOR;
        }
    }

    return null;
}

// Check if a file was uploaded
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
    if ($_FILES['attachment']['error'] !== UPLOAD_ERR_OK) {
        ticketResponse(false, "Attachment upload failed.");
    }

    $uploadDir = getTicketUploadDir();
    if ($uploadDir === null) {
        ticketResponse(false, "Ticket attachment folder is unavailable.");
    }

    $safeName = preg_replace('/[^A-Za-z0-9._-]/', '_', basename($_FILES['attachment']['name']));
    $attachmentName = uniqid('', true) . '_' . $safeName;
    $uploadFilePath = $uploadDir . $attachmentName;

    if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadFilePath)) {
        ticketResponse(false, "Could not save attachment.");
    }
}

// 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 (?, ?, ?, ?, 'Open', NOW(), NOW(), ?)";
$stmt = $admin_con->prepare($query);
if (!$stmt) {
    ticketResponse(false, $admin_con->error);
}
$stmt->bind_param('issss', $client_id, $title, $description, $priority, $attachmentName);

if ($stmt->execute()) {
     $ticketId = $stmt->insert_id;
     $stmt->close();
     
     /*
|--------------------------------------------------------------------------
| Send notification email
|--------------------------------------------------------------------------
*/
$clientName = 'Unknown';


    $res = mysqli_query($con, "SELECT client_id FROM subscription_params WHERE id=1");
    $row = mysqli_fetch_assoc($res);
        if (!empty($row['client_id'])) {
            $client_id = $row['client_id'];
           }
    



    $res = mysqli_query($con, "SELECT company FROM company WHERE id=1");
    $row = mysqli_fetch_assoc($res);
        if (!empty($row['company'])) {
            $clientName = $row['company'];
        }
    


$notifyEmail = 'support@enrep.co.uk';
$ticketUrl = "https://admin.enrep.co.uk/support_ticket_detail.php?ticket_id=" . $ticketId;
$subject = 'New Support Ticket #' . $ticketId . ' - ' . $title;

$bodyText  = "A new support ticket has been created.\r\n\r\n";
$bodyText .= "Ticket ID: " . $ticketId . "\r\n";
$bodyText .= "Client ID: " . $client_id . "\r\n";
$bodyText .= "Client Name: " . $clientName . "\r\n";
$bodyText .= "Priority: " . $priority . "\r\n";
$bodyText .= "Title: " . $title . "\r\n\r\n";
$bodyText .= "Description:\r\n" . $description . "\r\n\r\n";
$bodyText .= "View Ticket:\r\n" . $ticketUrl . "\r\n\r\n";

if ($attachmentName !== null) {
    $bodyText .= "Attachment: " . $attachmentName . "\r\n";
}

$headers = "From: EnRep Support <no-reply@enrep.co.uk>\r\n";
$headers .= "Reply-To: no-reply@enrep.co.uk\r\n";
$headers .= "MIME-Version: 1.0\r\n";

if ($attachmentName !== null && $uploadFilePath !== '' && file_exists($uploadFilePath)) {
    $fileData = file_get_contents($uploadFilePath);
    $fileDataEncoded = chunk_split(base64_encode($fileData));
    $mimeType = ticketAttachmentMimeType($uploadFilePath);

    $boundary = md5((string)time());

    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $boundary . "\"\r\n";

    $message  = "--" . $boundary . "\r\n";
    $message .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
    $message .= $bodyText . "\r\n";

    $message .= "--" . $boundary . "\r\n";
    $message .= "Content-Type: " . $mimeType . "; name=\"" . $attachmentName . "\"\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n";
    $message .= "Content-Disposition: attachment; filename=\"" . $attachmentName . "\"\r\n\r\n";
    $message .= $fileDataEncoded . "\r\n";
    $message .= "--" . $boundary . "--";
} else {
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $message = $bodyText;
}

@mail($notifyEmail, $subject, $message, $headers);

    ticketResponse(true, "Ticket created successfully.");
} else {
    $error = $stmt->error;
    $stmt->close();
    ticketResponse(false, $error);
}

