<?php
require_once('config.php');

// Retrieve the client ID from `subscription_params`
$client_id_query = mysqli_query($con, "SELECT client_id FROM subscription_params LIMIT 1");
$client_data = mysqli_fetch_assoc($client_id_query);
$client_id = $client_data['client_id'] ?? null;

// Retrieve the ticket ID from the URL parameters
$ticket_id = isset($_GET['ticket_id']) ? mysqli_real_escape_string($admin_con, $_GET['ticket_id']) : '';

if (empty($client_id) || empty($ticket_id)) {
    echo "<p>Missing client ID or ticket ID. Please check the configuration.</p>";
    exit();
}

// Fetch the ticket details for this client
$ticket_query = "SELECT * FROM support_tickets WHERE id = '$ticket_id' AND client_id = '$client_id'";
$ticket_result = mysqli_query($admin_con, $ticket_query);

if (!$ticket_result || mysqli_num_rows($ticket_result) == 0) {
    echo "<p>Ticket not found or access denied.</p>";
    exit();
}

$ticket = mysqli_fetch_assoc($ticket_result);
?>

<div class="container">
    <h4 class="mb-4"><a class="me-2 btn btn-info btn-sm p-0" href="index.php?t=includes/support&p=support_tickets.php"><i class="fad fa-chevron-left"></i> Back</a> Ticket #<?= str_pad($ticket['id'], 6, '0', STR_PAD_LEFT); ?> -
        <?= htmlspecialchars($ticket['title']); ?></h4>

    <!-- Ticket Details -->
    <div class="card shadow-sm mb-4">
        <div class="card-header bg-primary text-white">
            <span class="mb-0">Ticket Details </span><span class="float-end"><strong>Status:</strong> <span
                      class="badge <?= $ticket['status'] === 'In Progress' ? 'bg-warning' : ($ticket['status'] === 'completed' ? 'bg-danger' : 'bg-success') ?>"><?= ucfirst($ticket['status']); ?></span></span>
        </div>
        <div class="card-body">

            <p><strong>Priority:</strong> <?= ucfirst($ticket['priority']); ?></p>
            <p><strong>Created on:</strong> <?= date("d/m/Y H:i", strtotime($ticket['date_created'])); ?></p>
            <p><strong>Last updated:</strong> <?= date("d/m/Y H:i", strtotime($ticket['last_updated'])); ?></p>
            <hr>
            <p><?= nl2br(htmlspecialchars($ticket['description'])); ?></p>
            <!-- Ticket Attachments -->
            <?php if (!empty($ticket['attachment'])): 
            $filePath = ADMIN_URL . "/ticket_files/" . htmlspecialchars($ticket['attachment']);
            $fileExtension = pathinfo($ticket['attachment'], PATHINFO_EXTENSION);
            $isImage = in_array(strtolower($fileExtension), ['jpg', 'jpeg', 'png', 'gif']);
        ?>
            <p><strong>Attachment:</strong></p>
            <?php if ($isImage): ?>
            <!-- Display image thumbnail -->
            <a href="<?= $filePath ?>" target="_blank">
                <img src="<?= $filePath ?>" alt="attachment" style="width: 100px; height: auto; border-radius: 4px; margin-bottom: 10px;">
            </a>
            <?php else: ?>
            <!-- Display file icon with download link -->
            <a href="<?= $filePath ?>" target="_blank" class="d-flex align-items-center">
                <i class="fad fa-file-alt fa-2x me-2"></i> <?= basename($ticket['attachment']); ?>
            </a>
            <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- Replies Section -->
    <h5>Replies</h5>
    <div id="repliesSection" class="mb-4">
        <?php
        // Fetch replies associated with this ticket
        $replies_query = "SELECT * FROM support_ticket_replies WHERE ticket_id = '$ticket_id' ORDER BY date_sent DESC";
        $replies_result = mysqli_query($admin_con, $replies_query);

        while ($reply = mysqli_fetch_assoc($replies_result)): ?>
        <div class="card mb-2 shadow-2-strong">
            <div class="p-2 <?= $reply['sender_type'] === 'Admin' ? 'bg-dark text-white' : 'bg-secondary text-white' ?>">
                <strong><?= ucfirst($reply['sender_type']); ?>:</strong><small class="float-end"><?= date("d/m/Y H:i", strtotime($reply['date_sent'])); ?></small>
            </div>
            <div class="card-body">

                <p><?= nl2br(htmlspecialchars($reply['message'])); ?></p>
                <?php if ($reply['attachment']): 
                
                $urlPath = ADMIN_URL . "/ticket_files/" . htmlspecialchars($reply['attachment']);
                $fileExtension = pathinfo($reply['attachment'], PATHINFO_EXTENSION);
                $isImage = in_array(strtolower($fileExtension), ['jpg', 'jpeg', 'png', 'gif']);
            ?>
                <p><strong>Attachment:</strong></p>

                <?php if ($isImage): ?>
                <!-- Image thumbnail with download on click -->
                <a href="<?= $urlPath ?>" target="_blank">
                    <img src="<?= $urlPath ?>" alt="attachment" style="width: 100px; height: auto; border-radius: 4px; margin-bottom: 10px;">
                </a>
                <?php else: ?>
                <!-- File icon with filename and download on click -->
                <a href="<?= $urlPath ?>" target="_blank" class="d-flex align-items-center">
                    <i class="fad fa-file-alt fa-2x me-2"></i> <?= basename($reply['attachment']); ?>
                </a>
                <?php endif; ?>
                <?php endif; ?>

            </div>
        </div>
        <?php endwhile; ?>
    </div>

    <!-- Reply Form -->
    <div class="card shadow-2-strong">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">Add a Reply</h5>
        </div>
        <div class="card-body">
            <form id="replyForm" enctype="multipart/form-data">
                <div class="form-group mb-3">
                    <label for="replyContent">Your Reply</label>
                    <textarea id="replyContent" name="replyContent" rows="3" class="form-control" required></textarea>
                </div>
                <div class="form-group mb-3">
                    <label for="replyAttachment">Attachment (optional)</label>
                    <input type="file" id="replyAttachment" name="replyAttachment" class="form-control">
                </div>
                <input type="hidden" name="ticket_id" value="<?= $ticket_id ?>">
                <input type="hidden" name="client_id" value="<?= $client_id ?>">
                <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                <button type="submit" class="btn btn-secondary">Submit Reply</button>
            </form>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>
document.getElementById("replyForm").addEventListener("submit", function(event) {
    event.preventDefault();
    const formData = new FormData(this);

    // Check for the file in FormData before sending
    for (let [key, value] of formData.entries()) {
        console.log(`${key}:`, value);
    }

    fetch(`${ROOT_URL}/includes/support/support_reply_ticket.php`, {
            method: "POST",
            body: formData
        })
        .then(response => response.text())
        .then(data => {
            if (data.trim() === "success") {
                loadReplies();
                document.getElementById("replyContent").value = ""; // Clear the reply textarea
                document.getElementById("replyAttachment").value = ""; // Clear the file input
            } else {
                alert("Failed to send the reply. Please try again.");
            }
        });
});



function loadReplies() {
    fetch(`${ROOT_URL}/includes/support/support_load_replies.php?ticket_id=<?= $ticket_id ?>&tenant=${TENANT_URL}`)
        .then(response => response.text())
        .then(data => {

            document.getElementById("repliesSection").innerHTML = data;
        });
}

document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/support&p=support_tickets.php">Support</a> <i class="fad fa-angle-double-right mx-2 mt-1"  aria-hidden="true"></i></li> <li class="breadcrumb-item active">Viewing ticket #<?= str_pad($ticket['id'], 6, '0', STR_PAD_LEFT); ?></li>';
</script>