<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

try {
    require realpath(dirname(__FILE__) . '/../helper_functions/data_request.php');
    $ticketType = [
        'Task' => 'Task',
        'New Feature' => 'New Feature',
        'Bug' => 'Bug'
    ];

    $priorities = [
        'Normal' => 'Normal',
        'Major' => 'Major',
        'Minor' => 'Minor'
    ];

    $categories = [
        'Website' => 'Website',
        'Construction' => 'Construction',
    ];

    $ticketStatuses = [
        'Open' => 'Open',
        'In Progress' => 'In Progress',
        'Blocked' => 'Blocked',
        'Closed' => 'Closed',
    ];

    $users = fetchData('users');
    $properties = fetchData('properties');

    if (isset($_GET['id'])) {
        $itemId = $_GET['id'];
        $TicketData = fetchDataWithId('support_tickets', $itemId);
        $TicketData = (object) $TicketData;
        if ($TicketData !== false) {
            if ($TicketData->owner) {
                $ownerData = fetchDataWithId('users', $TicketData->owner);
                $TicketData->ownerData = (object) $ownerData;
            }
            if ($TicketData->property) {
                $propertyData = fetchDataWithId('properties', $TicketData->property);
                $TicketData->propertyData = (object) $propertyData;
            }
        }

        $ticketId = $itemId;
        $sql = "SELECT c.id AS comment_id, c.comment, c.createdAt, u.id AS user_id, CONCAT(u.firstname, ' ', u.lastname) AS created_by_name, u.email AS created_by_email, st.id AS ticket_id, st.subject AS ticket_subject, st.status AS ticket_status, st.type AS ticket_type, st.category AS ticket_category, st.priority AS ticket_priority FROM ticketComments c LEFT JOIN users u ON c.createdBy = u.id LEFT JOIN support_tickets st ON c.ticketId = st.id WHERE c.ticketId = :ticketId;";
        $params = [':ticketId' => $ticketId];
        $commentsData = fetchDataWithJoins($sql, $params);
        $commentsData = array_reverse($commentsData);
    }
} catch (Exception $e) {
    echo "Server error in tickets essentials";
}
