<?php
/**
 * Admin Ticket Detail - View and reply to support tickets
 */

// Handle AJAX reply BEFORE header to avoid output buffer issues
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    require_once __DIR__ . '/../config/config.php';
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/../includes/functions.php';
    require_once __DIR__ . '/../includes/Auth.php';

    if (!auth()->isAdmin()) {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Unauthorized']);
        exit;
    }

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

    if ($_POST['action'] === 'reply') {
        $ticketId = (int)($_POST['ticket_id'] ?? 0);
        $message = trim($_POST['message'] ?? '');
        $adminId = auth()->getAdminId();

        if ($ticketId && $message) {
            dbInsert('ticket_messages', [
                'ticket_id' => $ticketId,
                'user_id' => $adminId,
                'sender_type' => 'admin',
                'sender_id' => $adminId,
                'message' => $message,
                'is_admin' => 1
            ]);
            dbQuery("UPDATE support_tickets SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", [$ticketId]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Missing data']);
        }
        exit;
    }

    if ($_POST['action'] === 'update_status') {
        $ticketId = (int)($_POST['ticket_id'] ?? 0);
        $status = $_POST['status'] ?? '';
        $validStatuses = ['open', 'in_progress', 'waiting', 'resolved', 'closed'];

        if ($ticketId && in_array($status, $validStatuses)) {
            dbQuery("UPDATE support_tickets SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", [$status, $ticketId]);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Invalid status']);
        }
        exit;
    }

    if ($_POST['action'] === 'get_messages') {
        $ticketId = (int)($_POST['ticket_id'] ?? 0);
        $lastId = (int)($_POST['last_id'] ?? 0);
        if ($ticketId) {
            $msgs = dbFetchAll("SELECT * FROM ticket_messages WHERE ticket_id = ? AND id > ? ORDER BY created_at ASC", [$ticketId, $lastId]);
            echo json_encode(['success' => true, 'messages' => $msgs]);
        } else {
            echo json_encode(['success' => false]);
        }
        exit;
    }

    echo json_encode(['success' => false, 'error' => 'Unknown action']);
    exit;
}

require_once 'includes/header.php';

$ticketId = (int)($_GET['id'] ?? 0);
if (!$ticketId) {
    header('Location: tickets.php');
    exit;
}

$ticket = dbFetch("SELECT t.*, u.email, u.first_name, u.last_name 
    FROM support_tickets t 
    LEFT JOIN users u ON t.user_id = u.id 
    WHERE t.id = ?", [$ticketId]);

if (!$ticket) {
    header('Location: tickets.php');
    exit;
}

$messages = dbFetchAll("SELECT * FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC", [$ticketId]);

$statusColors = [
    'open' => 'danger',
    'in_progress' => 'primary',
    'waiting' => 'warning',
    'resolved' => 'success',
    'closed' => 'secondary'
];
$priorityColors = [
    'low' => 'secondary',
    'medium' => 'warning',
    'high' => 'danger',
    'urgent' => 'danger'
];
?>

<style>
.ticket-header{display:flex;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;gap:1rem}
.ticket-meta{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:1rem;margin:1rem 0}
.meta-item{background:var(--bg-tertiary);border-radius:8px;padding:12px 16px}
.meta-label{font-size:.75rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:.5px}
.meta-value{font-size:.95rem;margin-top:4px}
.messages-container{max-height:500px;overflow-y:auto;padding:1rem;background:var(--bg-tertiary);border-radius:12px;margin:1rem 0}
.msg{margin-bottom:1rem;display:flex;flex-direction:column}
.msg.user-msg{align-items:flex-start}
.msg.admin-msg{align-items:flex-end}
.msg-bubble{max-width:75%;padding:12px 16px;border-radius:12px;font-size:.9rem;line-height:1.5}
.msg.user-msg .msg-bubble{background:var(--bg-card);border-bottom-left-radius:4px}
.msg.admin-msg .msg-bubble{background:var(--primary);color:#fff;border-bottom-right-radius:4px}
.msg-info{font-size:.7rem;color:var(--text-muted);margin-top:4px;display:flex;gap:8px}
.reply-box{display:flex;gap:10px;padding:16px 0}
.reply-input{flex:1;background:var(--bg-tertiary);border:1px solid var(--border-color);border-radius:8px;padding:12px 16px;color:#fff;font-size:.9rem;resize:none}
.reply-input:focus{outline:none;border-color:var(--primary)}
.reply-btn{background:var(--primary);border:none;border-radius:8px;padding:12px 20px;color:#fff;cursor:pointer;font-size:.9rem;display:flex;align-items:center;gap:6px}
.reply-btn:hover{opacity:.85}
.status-select{background:var(--bg-tertiary);border:1px solid var(--border-color);border-radius:6px;padding:6px 12px;color:#fff;font-size:.85rem;cursor:pointer}
.back-link{color:var(--text-muted);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:.9rem;margin-bottom:1rem}
.back-link:hover{color:#fff}
.no-messages{text-align:center;padding:40px;color:var(--text-muted)}
.no-messages i{font-size:2rem;margin-bottom:12px;display:block;opacity:.4}
</style>

<a href="tickets.php" class="back-link"><i class="fas fa-arrow-left"></i> Back to Tickets</a>

<div class="card">
    <div class="card-header">
        <div class="ticket-header">
            <div>
                <h2 style="margin:0"><?= htmlspecialchars($ticket['subject']) ?></h2>
                <div style="color:var(--text-muted);font-size:.85rem;margin-top:4px">
                    #<?= $ticket['ticket_id'] ?> • Created <?= date('d M Y, H:i', strtotime($ticket['created_at'])) ?>
                </div>
            </div>
            <div style="display:flex;gap:8px;align-items:center">
                <select class="status-select" id="statusSelect" onchange="updateStatus(this.value)">
                    <option value="open" <?= $ticket['status']==='open'?'selected':'' ?>>Open</option>
                    <option value="in_progress" <?= $ticket['status']==='in_progress'?'selected':'' ?>>In Progress</option>
                    <option value="waiting" <?= $ticket['status']==='waiting'?'selected':'' ?>>Waiting</option>
                    <option value="resolved" <?= $ticket['status']==='resolved'?'selected':'' ?>>Resolved</option>
                    <option value="closed" <?= $ticket['status']==='closed'?'selected':'' ?>>Closed</option>
                </select>
            </div>
        </div>
    </div>

    <div class="card-body">
        <div class="ticket-meta">
            <div class="meta-item">
                <div class="meta-label">User</div>
                <div class="meta-value"><?= htmlspecialchars(($ticket['first_name'] ?? '') . ' ' . ($ticket['last_name'] ?? '')) ?></div>
                <div style="font-size:.8rem;color:var(--text-muted)"><?= htmlspecialchars($ticket['email'] ?? '') ?></div>
            </div>
            <div class="meta-item">
                <div class="meta-label">Category</div>
                <div class="meta-value"><?= ucfirst($ticket['category'] ?? 'Other') ?></div>
            </div>
            <div class="meta-item">
                <div class="meta-label">Priority</div>
                <div class="meta-value">
                    <span class="badge badge-<?= $priorityColors[$ticket['priority']] ?? 'secondary' ?>">
                        <?= ucfirst($ticket['priority'] ?? 'Medium') ?>
                    </span>
                </div>
            </div>
            <div class="meta-item">
                <div class="meta-label">Status</div>
                <div class="meta-value">
                    <span class="badge badge-<?= $statusColors[$ticket['status']] ?? 'secondary' ?>" id="statusBadge">
                        <?= ucfirst(str_replace('_', ' ', $ticket['status'])) ?>
                    </span>
                </div>
            </div>
        </div>

        <h4 style="margin:1.5rem 0 .5rem"><i class="fas fa-comments" style="opacity:.5"></i> Messages</h4>

        <div class="messages-container" id="messagesContainer">
            <?php if (empty($messages)): ?>
            <div class="no-messages" id="noMessages">
                <i class="fas fa-inbox"></i>
                No messages yet
            </div>
            <?php else: ?>
            <?php foreach ($messages as $msg): ?>
            <div class="msg <?= $msg['is_admin'] ? 'admin-msg' : 'user-msg' ?>">
                <div class="msg-bubble"><?= nl2br(htmlspecialchars($msg['message'])) ?></div>
                <div class="msg-info">
                    <span><?= $msg['is_admin'] ? 'Admin' : 'User' ?></span>
                    <span><?= date('d M, H:i', strtotime($msg['created_at'])) ?></span>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <?php if ($ticket['status'] !== 'closed'): ?>
        <div class="reply-box">
            <textarea class="reply-input" id="replyInput" placeholder="Type your reply..." rows="1" 
                onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();sendReply()}"></textarea>
            <button class="reply-btn" onclick="sendReply()">
                <i class="fas fa-paper-plane"></i> Send
            </button>
        </div>
        <?php else: ?>
        <div style="text-align:center;padding:12px;color:var(--text-muted);font-size:.9rem">
            <i class="fas fa-lock"></i> This ticket is closed. Change status to reply.
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
const TICKET_ID = <?= $ticketId ?>;
let lastMessageId = <?= !empty($messages) ? end($messages)['id'] : 0 ?>;
let pollInterval = null;

function sendReply() {
    const input = document.getElementById('replyInput');
    const msg = input.value.trim();
    if (!msg) return;

    // Optimistic UI update
    appendMessage({message: msg, is_admin: 1, created_at: new Date().toISOString()});
    input.value = '';

    fetch('ticket-detail.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `action=reply&ticket_id=${TICKET_ID}&message=${encodeURIComponent(msg)}`
    })
    .then(r => r.json())
    .then(d => {
        if (!d.success) {
            alert('Failed to send: ' + (d.error || 'Unknown error'));
        }
    })
    .catch(err => console.error('Send error:', err));
}

function appendMessage(msg) {
    const container = document.getElementById('messagesContainer');
    const noMsg = document.getElementById('noMessages');
    if (noMsg) noMsg.remove();

    const isAdmin = parseInt(msg.is_admin);
    const time = msg.created_at ? new Date(msg.created_at).toLocaleDateString('en-GB', {day:'2-digit',month:'short'}) + ', ' + new Date(msg.created_at).toLocaleTimeString([], {hour:'2-digit',minute:'2-digit'}) : 'Just now';

    const div = document.createElement('div');
    div.className = `msg ${isAdmin ? 'admin-msg' : 'user-msg'}`;
    div.innerHTML = `
        <div class="msg-bubble">${msg.message.replace(/\n/g, '<br>')}</div>
        <div class="msg-info">
            <span>${isAdmin ? 'Admin' : 'User'}</span>
            <span>${time}</span>
        </div>
    `;
    container.appendChild(div);
    container.scrollTop = container.scrollHeight;
    if (msg.id) lastMessageId = Math.max(lastMessageId, parseInt(msg.id));
}

function updateStatus(status) {
    fetch('ticket-detail.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: `action=update_status&ticket_id=${TICKET_ID}&status=${status}`
    })
    .then(r => r.json())
    .then(d => {
        if (d.success) {
            const badge = document.getElementById('statusBadge');
            const colors = {open:'danger',in_progress:'primary',waiting:'warning',resolved:'success',closed:'secondary'};
            badge.className = 'badge badge-' + (colors[status] || 'secondary');
            badge.textContent = status.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
        }
    })
    .catch(err => console.error('Status update error:', err));
}

// Poll for new messages
function startPolling() {
    pollInterval = setInterval(() => {
        fetch('ticket-detail.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=get_messages&ticket_id=${TICKET_ID}&last_id=${lastMessageId}`
        })
        .then(r => r.json())
        .then(d => {
            if (d.success && d.messages && d.messages.length > 0) {
                d.messages.forEach(msg => {
                    if (!parseInt(msg.is_admin)) { // Only add user messages (admin messages shown optimistically)
                        appendMessage(msg);
                    }
                    lastMessageId = Math.max(lastMessageId, parseInt(msg.id));
                });
            }
        })
        .catch(err => console.error('Poll error:', err));
    }, 5000);
}

// Scroll to bottom on load
document.getElementById('messagesContainer').scrollTop = document.getElementById('messagesContainer').scrollHeight;
startPolling();
</script>

<?php require_once 'includes/footer.php'; ?>
