<?php
// Fetch client ID from subscription_params table
$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'];

// Fetch tickets for the client from the admin database, separating closed tickets for the archive
$tickets_query = mysqli_query($admin_con, "SELECT * FROM support_tickets WHERE client_id = '$client_id' AND status != 'completed' ORDER BY status ASC, date_created DESC");
$closed_tickets_query = mysqli_query($admin_con, "SELECT * FROM support_tickets WHERE client_id = '$client_id' AND status = 'completed' ORDER BY date_created DESC");

// Check for errors in the query
if (!$tickets_query || !$closed_tickets_query) {
    die("Database query failed: " . mysqli_error($admin_con));
}


?>

<div class="container">
    <h3>Support Tickets</h3>
    <p>View your open tickets, search past tickets, or create a new support request.</p>

    <!-- Actions -->
    <div class="d-flex justify-content-between align-items-center mb-3">
        <button class="btn btn-primary" onclick="openNewTicketModal()">New Ticket</button>
        <div class="d-flex">
            <input type="text" id="ticketSearch" class="form-control" placeholder="Search tickets">
            <select id="filterStatus" class="form-select ms-2">
                <option value="">All</option>
                <option value="open">Open</option>
                <option value="in_progress">In Progress</option>
                <option value="completed">Completed</option>
            </select>
            <button class="btn btn-secondary ms-2" onclick="filterTickets()">Search</button>
        </div>
    </div>

    <!-- Tickets Table -->
    <div class="table-responsive">
        <?php if (mysqli_num_rows($tickets_query) > 0): ?>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Ticket ID</th>
                    <th>Title</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Last Updated</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="ticketList">
                <?php while ($ticket = mysqli_fetch_assoc($tickets_query)) { ?>
                <tr>
                    <td>#<?= htmlspecialchars(str_pad($ticket['id'], 6, '0', STR_PAD_LEFT)); ?></td>
                    <td><?= htmlspecialchars($ticket['title']); ?></td>
                    <td>
                        <span class="badge d-block <?= $ticket['status'] === 'In Progress' ? 'bg-warning' : ($ticket['status'] === 'completed' ? 'bg-danger' : 'bg-success') ?>">
                            <?= ucfirst($ticket['status']); ?>
                        </span>
                    </td>
                    <td><?= date("d/m/Y H:i", strtotime($ticket['date_created'])); ?></td>
                    <td><?= date("d/m/Y H:i", strtotime($ticket['last_updated'])); ?></td>
                    <td>
                        <a class="btn btn-sm btn-info" href="index.php?t=includes/support&p=support_view_ticket.php&ticket_id=<?= $ticket['id']; ?>">View</a>
                        <?php if ($ticket['status'] !== 'completed'): ?>
                        <button class="btn btn-sm btn-danger" onclick="closeTicket(<?= $ticket['id']; ?>)">Close</button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php else: ?>
        <p class="text-center">No support tickets found. You can create a new ticket by clicking "New Ticket".</p>
        <?php endif; ?>
    </div>

    <!-- Archived Tickets Section -->
    <div class="container mt-5">
        <h4>Archived Tickets</h4>
        <?php if (mysqli_num_rows($closed_tickets_query) > 0): ?>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Ticket ID</th>
                    <th>Title</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th>Last Updated</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="archiveList">
                <?php while ($ticket = mysqli_fetch_assoc($closed_tickets_query)) { ?>
                <tr>
                    <td>#<?= htmlspecialchars(str_pad($ticket['id'], 6, '0', STR_PAD_LEFT)); ?></td>
                    <td><?= htmlspecialchars($ticket['title']); ?></td>
                    <td><span class="badge d-block bg-danger">Completed</span></td>
                    <td><?= date("d/m/Y H:i", strtotime($ticket['date_created'])); ?></td>
                    <td><?= date("d/m/Y H:i", strtotime($ticket['last_updated'])); ?></td>
                    <td>
                        <a class="btn btn-sm btn-info" href="index.php?t=includes/support&p=support_archive_ticket.php&ticket_id=<?= $ticket['id']; ?>">View Details</a>
                    </td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php else: ?>
        <p class="text-center">No archived tickets found.</p>
        <?php endif; ?>
    </div>
</div>

<!-- New Ticket Modal -->
<div class="modal fade" id="newTicketModal" tabindex="-1" aria-labelledby="newTicketModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="newTicketModalLabel">Create New Support Ticket</h5>
                <button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="newTicketError" class="alert alert-warning d-none"></div>
                <form id="newTicketForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="ticketTitle" class="form-label">Title</label>
                        <input type="text" class="form-control" id="ticketTitle" name="title" required>
                    </div>
                    <div class="mb-3">
                        <label for="ticketDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="ticketDescription" name="description" rows="4" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="ticketAttachment" class="form-label">Attachment (optional)</label>
                        <input type="file" class="form-control" id="ticketAttachment" name="attachment">
                    </div>
                    <div class="mb-3">
                        <label for="ticketPriority" class="form-label">Priority</label>
                        <select class="form-select" id="ticketPriority" name="priority" required>
                            <option value="low">Low</option>
                            <option value="medium">Medium</option>
                            <option value="high">High</option>
                        </select>
                    </div>
                     <input type="hidden" class="form-control" id="tenant" name="tenant" value="<?=TENANT_URL?>"> 
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-mdb-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitNewTicket()">Submit Ticket</button>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript for ticket actions -->
<script>
function openNewTicketModal() {
    var modal = new mdb.Modal(document.getElementById('newTicketModal'));
    modal.show();
}

function submitNewTicket() {
    const errorBox = document.getElementById("newTicketError");
    errorBox.classList.add("d-none");
    errorBox.textContent = "";

    const formData = new FormData();
    formData.append("title", document.getElementById("ticketTitle").value);
    formData.append("description", document.getElementById("ticketDescription").value);
    formData.append("priority", document.getElementById("ticketPriority").value);
    formData.append("client_id", <?= json_encode($client_id) ?>); // Include client_id from PHP
    formData.append("tenant", TENANT_URL); // Include client_id from PHP

    // Add file if selected
    const attachment = document.getElementById("ticketAttachment").files[0];
    if (attachment) {
        formData.append("attachment", attachment); // Include the file in form data
    }

    fetch(ROOT_URL + "/includes/support/support_create_ticket.php", {
            method: "POST",
            body: formData
        })
        .then(response => response.text())
        .then(text => {
            let data;

            try {
                data = JSON.parse(text);
            } catch (error) {
                data = {
                    success: text.trim() === "success",
                    message: text.trim()
                };
            }

            if (data.success) {
                showResponse("success", data.message || "Ticket created successfully.");
                location.reload(); // Reload to show the new ticket
            } else {
                const message = data.message || "Failed to create the ticket. Please try again.";
                errorBox.textContent = message;
                errorBox.classList.remove("d-none");
                showResponse("warning", message);
            }
        })
        .catch(error => {
            console.error("Error:", error);
            const message = "Failed to create the ticket. Please try again.";
            errorBox.textContent = message;
            errorBox.classList.remove("d-none");
            showResponse("warning", message);
        });
}


function filterTickets() {
    const searchQuery = document.getElementById("ticketSearch").value.trim();
    const statusFilter = document.getElementById("filterStatus").value;

    fetch(`${ROOT_URL}/includes/support/support_search_tickets.php`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: new URLSearchParams({
                search_query: searchQuery,
                status: statusFilter,
                tenant: TENANT_URL
            })
        })
        .then(response => response.text())
        .then(data => {
            document.getElementById("ticketList").innerHTML = data;
        });
}

function closeTicket(ticketId) {
    var dest = "<p>Are you sure you wish to close this ticket?</p>"
    loadModalContent(dest, 'confirmBox', 'modal-md', 1060, 'true', 'Close ticket #' + ticketId, 'cancelConfirm', () => closeTicketConfirmed(ticketId))
}

function closeTicketConfirmed(ticketId) {

    fetch(`${ROOT_URL}/includes/support/support_close_ticket.php`, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: new URLSearchParams({
                ticket_id: ticketId,
                tenant: TENANT_URL
            })
        })
        .then(response => response.text())
        .then(data => {

            if (data.trim() === "success") {
                showResponse("success", "Ticket closed successfully.");
                location.reload();
            } else {
                showResponse("warning", "Unable to close the ticket. Please try again.");
            }
        });

}

document.getElementById("ticketSearch").addEventListener("input", function() {
    const query = this.value.toLowerCase();
    const rows = document.querySelectorAll("#ticketList tr");

    rows.forEach(row => {
        const title = row.cells[1].textContent.toLowerCase(); // Title is in the second cell
        // Show all rows if the search query is empty, otherwise filter
        if (query === "" || title.includes(query)) {
            row.style.display = ""; // Show row
        } else {
            row.style.display = "none"; // Hide row
        }
    });
});
document.getElementById('navBox').innerHTML =
    '<li class="breadcrumb-item"><a href="index.php?t=includes/support&p=support_tickets.php">Support</a> </li>';
</script>
