<?php
$page_title = "View Ticket";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';

$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

// Check if ticket ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error'] = "Invalid ticket ID";
    header('Location: support.php');
    exit();
}

$ticket_id = (int)$_GET['id'];

// Get ticket details (ensure it belongs to current user)
$ticket_stmt = $db->prepare("
    SELECT * FROM support_tickets
    WHERE id = ? AND user_id = ?
");
$ticket_stmt->execute([$ticket_id, $user_id]);
$ticket = $ticket_stmt->fetch();

if (!$ticket) {
    $_SESSION['error'] = "Ticket not found or access denied";
    header('Location: support.php');
    exit();
}

// Handle reply submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_reply'])) {
    $reply_message = trim($_POST['reply_message']);

    if (empty($reply_message)) {
        $_SESSION['error'] = "Please enter a reply message";
    } elseif ($ticket['status'] === 'closed') {
        $_SESSION['error'] = "Cannot reply to a closed ticket";
    } else {
        // Add reply to ticket
        $reply_stmt = $db->prepare("
            INSERT INTO ticket_replies (ticket_id, user_id, user_type, message, created_at)
            VALUES (?, ?, 'user', ?, NOW())
        ");
        $result = $reply_stmt->execute([$ticket_id, $user_id, $reply_message]);

        if ($result) {
            // Update ticket updated_at
            $update_stmt = $db->prepare("
                UPDATE support_tickets SET updated_at = NOW() WHERE id = ?
            ");
            $update_stmt->execute([$ticket_id]);

            $_SESSION['success'] = "Reply added successfully";
        } else {
            $_SESSION['error'] = "Failed to add reply. Please try again.";
        }
    }

    header('Location: ticket-view.php?id=' . $ticket_id);
    exit();
}

// Get ticket replies
$replies_stmt = $db->prepare("
    SELECT tr.*, u.username, au.username as admin_username
    FROM ticket_replies tr
    LEFT JOIN users u ON tr.user_id = u.id AND tr.user_type = 'user'
    LEFT JOIN admin_users au ON tr.user_id = au.id AND tr.user_type = 'admin'
    WHERE tr.ticket_id = ?
    ORDER BY tr.created_at ASC
");
$replies_stmt->execute([$ticket_id]);
$replies = $replies_stmt->fetchAll();
?>

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

<div class="min-h-screen bg-gray-50">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900">Support Ticket</h1>
                    <p class="mt-2 text-gray-600">Ticket #<?php echo $ticket['id']; ?> - <?php echo htmlspecialchars($ticket['subject']); ?></p>
                </div>
                <a href="support.php" class="bg-gray-600 text-white px-4 py-2 rounded-md hover:bg-gray-700">
                    ← Back to Support
                </a>
            </div>
        </div>

        <!-- Ticket Status -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-4">
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium
                        <?php
                        switch ($ticket['status']) {
                            case 'open':
                                echo 'bg-green-100 text-green-800';
                                break;
                            case 'in_progress':
                                echo 'bg-yellow-100 text-yellow-800';
                                break;
                            case 'closed':
                                echo 'bg-gray-100 text-gray-800';
                                break;
                            default:
                                echo 'bg-gray-100 text-gray-800';
                        }
                        ?>">
                        Status: <?php echo ucfirst(str_replace('_', ' ', $ticket['status'])); ?>
                    </span>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium
                        <?php
                        switch ($ticket['priority']) {
                            case 'low':
                                echo 'bg-blue-100 text-blue-800';
                                break;
                            case 'normal':
                                echo 'bg-gray-100 text-gray-800';
                                break;
                            case 'high':
                                echo 'bg-orange-100 text-orange-800';
                                break;
                            case 'urgent':
                                echo 'bg-red-100 text-red-800';
                                break;
                            default:
                                echo 'bg-gray-100 text-gray-800';
                        }
                        ?>">
                        Priority: <?php echo ucfirst($ticket['priority']); ?>
                    </span>
                </div>
                <div class="text-sm text-gray-500">
                    Created: <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?>
                    <?php if ($ticket['updated_at'] != $ticket['created_at']): ?>
                        <br>Last Updated: <?php echo date('M j, Y g:i A', strtotime($ticket['updated_at'])); ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Ticket Conversation -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Conversation</h2>

            <!-- Original Message -->
            <div class="border-l-4 border-blue-500 pl-4 mb-6">
                <div class="flex items-center mb-2">
                    <div class="flex-shrink-0">
                        <div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                            <span class="text-white text-sm font-medium">U</span>
                        </div>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-gray-900">You</p>
                        <p class="text-sm text-gray-500"><?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></p>
                    </div>
                </div>
                <div class="text-gray-700 whitespace-pre-line">
                    <?php echo htmlspecialchars($ticket['message']); ?>
                </div>
            </div>

            <!-- Replies -->
            <?php foreach ($replies as $reply): ?>
                <div class="border-l-4 <?php echo $reply['user_type'] === 'admin' ? 'border-green-500' : 'border-blue-500'; ?> pl-4 mb-6">
                    <div class="flex items-center mb-2">
                        <div class="flex-shrink-0">
                            <div class="w-8 h-8 <?php echo $reply['user_type'] === 'admin' ? 'bg-green-500' : 'bg-blue-500'; ?> rounded-full flex items-center justify-center">
                                <span class="text-white text-sm font-medium">
                                    <?php echo $reply['user_type'] === 'admin' ? '<i class="fas fa-headset"></i>' : strtoupper(substr($reply['username'] ?? 'U', 0, 1)); ?>
                                </span>
                            </div>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm font-medium text-gray-900">
                                <?php echo $reply['user_type'] === 'admin' ? 'Support Team' : 'You'; ?>
                            </p>
                            <p class="text-sm text-gray-500"><?php echo date('M j, Y g:i A', strtotime($reply['created_at'])); ?></p>
                        </div>
                    </div>
                    <div class="text-gray-700 whitespace-pre-line">
                        <?php echo htmlspecialchars($reply['message']); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Add Reply (if ticket is not closed) -->
        <?php if ($ticket['status'] !== 'closed'): ?>
            <div class="bg-white rounded-lg shadow-sm p-6">
                <h2 class="text-xl font-semibold text-gray-900 mb-4">Add Reply</h2>

                <form method="POST" class="space-y-4">
                    <div>
                        <label for="reply_message" class="block text-sm font-medium text-gray-700">Your Reply</label>
                        <textarea id="reply_message" name="reply_message" rows="4" required
                                  class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
                                  placeholder="Type your reply here..."></textarea>
                    </div>

                    <button type="submit" name="add_reply"
                            class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        Send Reply
                    </button>
                </form>
            </div>
        <?php else: ?>
            <div class="bg-gray-100 rounded-lg p-6 text-center">
                <p class="text-gray-600">This ticket is closed. If you need further assistance, please create a new ticket.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

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