<?php
require '../includes/db.php';
require 'includes/admin_auth.php';

// Handle reply or status update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['id'], $_POST['reply'])) {
        $id = intval($_POST['id']);
        $reply = trim($_POST['reply']);

        $stmt = $pdo->prepare("UPDATE support_tickets SET reply = ?, status = 'closed' WHERE id = ?");
        $stmt->execute([$reply, $id]);
    } elseif (isset($_POST['id'], $_POST['status'])) {
        $id = intval($_POST['id']);
        $status = in_array($_POST['status'], ['open', 'pending', 'closed']) ? $_POST['status'] : 'open';

        $stmt = $pdo->prepare("UPDATE support_tickets SET status = ? WHERE id = ?");
        $stmt->execute([$status, $id]);
    }
}

// Fetch all tickets
$tickets = $pdo->query("SELECT support_tickets.*, users.username FROM support_tickets JOIN users ON users.id = support_tickets.user_id ORDER BY support_tickets.created_at DESC")->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title>Admin - Support Tickets</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .read-more-content { display: none; }
        .read-more-button { cursor: pointer; color: blue; text-decoration: underline; }
        textarea { min-height: 120px; resize: vertical; }
    </style>
</head>
<body class="p-4">
    <div class="container">
        <h2 class="mb-4">Support Tickets</h2>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>User</th>
                    <th>Subject</th>
                    <th>Message</th>
                    <th>Reply</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($tickets as $t): ?>
                    <tr>
                        <td><?= htmlspecialchars($t['username']) ?></td>
                        <td><?= htmlspecialchars($t['subject']) ?></td>

                        <!-- Read More / Less Message -->
                        <td>
                            <?php
                                $fullMessage = nl2br(htmlspecialchars($t['message']));
                                $shortMessage = substr($fullMessage, 0, 100);
                                $isLong = strlen(strip_tags($fullMessage)) > 100;
                            ?>
                            <div>
                                <span class="short-msg"><?= $shortMessage ?><?= $isLong ? '...' : '' ?></span>
                                <?php if ($isLong): ?>
                                    <span class="read-more-content"><?= $fullMessage ?></span>
                                    <span class="read-more-button" onclick="toggleReadMore(this)">Read more</span>
                                <?php endif; ?>
                            </div>
                        </td>

                        <td>
    <?php if (!empty($t['reply'])): ?>
        <?= nl2br(htmlspecialchars($t['reply'])) ?>
    <?php elseif ($t['status'] === 'closed'): ?>
        <em>Closed without reply</em>
    <?php else: ?>
        <em>Pending</em>
    <?php endif; ?>
</td>


                        <!-- Status dropdown -->
                        <td>
                            <form method="POST" class="mb-0">
                                <input type="hidden" name="id" value="<?= $t['id'] ?>">
                                <select name="status" class="form-select form-select-sm status-dropdown" data-ticket-id="<?= $t['id'] ?>" onchange="this.form.submit()">
                                    <option value="open" <?= $t['status'] === 'open' ? 'selected' : '' ?>>Open</option>
                                    <option value="pending" <?= $t['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                                    <option value="closed" <?= $t['status'] === 'closed' ? 'selected' : '' ?>>Closed</option>
                                </select>
                            </form>
                        </td>

                        <!-- Reply form -->
                        <td>
                            <?php if ($t['status'] !== 'closed'): ?>
                                <button class="btn btn-sm btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#replyForm<?= $t['id'] ?>">
                                    Reply
                                </button>

                                <div class="collapse mt-2 reply-section" id="replyForm<?= $t['id'] ?>">
                                    <form method="POST">
                                        <input type="hidden" name="id" value="<?= $t['id'] ?>">
                                        <textarea name="reply" class="form-control mb-2" placeholder="Type your reply..." required></textarea>
                                        <button class="btn btn-sm btn-success">Send Reply</button>
                                    </form>
                                </div>
                            <?php else: ?>
                                <em>Closed</em>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Custom Script for Read More and Status control -->
    <script>
        function toggleReadMore(btn) {
            const parent = btn.parentElement;
            const short = parent.querySelector('.short-msg');
            const full = parent.querySelector('.read-more-content');
            const isShown = full.style.display === 'inline';

            if (isShown) {
                full.style.display = 'none';
                short.style.display = 'inline';
                btn.textContent = 'Read more';
            } else {
                full.style.display = 'inline';
                short.style.display = 'none';
                btn.textContent = 'Show less';
            }
        }
    </script>
</body>
</html>
