<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'tickets';
$database = new Database();
$db = $database->getConnection();

$success_message = '';
$error_message = '';

// Get ticket ID and verify ownership
$ticket_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$ticket_id) {
    header("Location: tickets.php");
    exit();
}

$stmt = $db->prepare("SELECT * FROM tickets WHERE id = ? AND user_id = ?");
$stmt->execute([$ticket_id, $_SESSION['user_id']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

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

// Mark related notifications as read
try {
    $stmt = $db->prepare("UPDATE notifications SET is_read = 1 WHERE user_id = ? AND link LIKE ?");
    $stmt->execute([$_SESSION['user_id'], "%ticket_details.php?id=$ticket_id%"]);
} catch (PDOException $e) {
    error_log("Error marking notifications as read: " . $e->getMessage());
}

// --- HANDLE ALL POST ACTIONS (REPLY, CLOSE) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // --- HANDLE TICKET REPLY ---
    if ($action === 'reply') {
        $message = trim($_POST['message'] ?? '');
        $attachment_filename = null;

        if (empty($message) && empty($_FILES['attachment']['name'])) {
            $error_message = "Your reply must contain a message or an attachment.";
        } else {
            // Handle file upload
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = '../uploads/ticket_attachments/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0775, true);
                }
                $original_filename = basename($_FILES['attachment']['name']);
                $safe_filename = preg_replace("/[^a-zA-Z0-9\._-]/", "", $original_filename);
                $attachment_filename = uniqid() . '-' . $safe_filename;
                
                if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $upload_dir . $attachment_filename)) {
                    $error_message = "Failed to upload attachment.";
                    $attachment_filename = null;
                }
            }

            if (empty($error_message)) {
                try {
                    $db->beginTransaction();
                    
                    $stmt = $db->prepare("INSERT INTO ticket_messages (ticket_id, sender_id, message, attachment, is_admin) VALUES (?, ?, ?, ?, 0)");
                    $stmt->execute([$ticket_id, $_SESSION['user_id'], $message, $attachment_filename]);
                    
                    // Re-open the ticket if it was closed and update timestamp
                    $stmt = $db->prepare("UPDATE tickets SET status = 'open', updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$ticket_id]);
                    
                    // Notify admin
                    $stmt = $db->prepare("INSERT INTO admin_notifications (type, title, message, link) VALUES ('ticket_reply', 'New Reply on Ticket', ?, ?)");
                    $stmt->execute(["User replied to ticket #{$ticket_id}: " . htmlspecialchars($ticket['subject']), "admin/ticket_details.php?id={$ticket_id}"]);
                    
                    $db->commit();
                    $_SESSION['success_message'] = "Your reply has been sent successfully.";
                    header("Location: ticket_details.php?id=$ticket_id");
                    exit();
                } catch (PDOException $e) {
                    $db->rollBack();
                    $error_message = "An error occurred. Please try again.";
                    error_log("Ticket Reply Error: " . $e->getMessage());
                }
            }
        }
    }

    // --- HANDLE TICKET CLOSE ---
    if ($action === 'close_ticket') {
        try {
            $stmt = $db->prepare("UPDATE tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$ticket_id]);
            $_SESSION['success_message'] = "Ticket #{$ticket_id} has been closed.";
            header("Location: ticket_details.php?id=$ticket_id");
            exit();
        } catch (PDOException $e) {
            $error_message = "Failed to close the ticket.";
            error_log("Ticket Close Error: " . $e->getMessage());
        }
    }
}

// Fetch all messages for this ticket
$stmt = $db->prepare("
    SELECT tm.*, u.first_name, u.last_name, u.profile_picture
    FROM ticket_messages tm
    LEFT JOIN users u ON tm.sender_id = u.id AND tm.is_admin = 0
    WHERE tm.ticket_id = ?
    ORDER BY tm.created_at ASC
");
$stmt->execute([$ticket_id]);
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Use session messages if they exist
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --border-color: #e2e8f0;
    --gray-light: #f3f4f6;
    --gray-dark: #4b5563;
}
.ticket-header { background-color: var(--primary-light); border-radius: 0.75rem; padding: 1.5rem; margin-bottom: 1.5rem; }
.ticket-status { padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.8rem; font-weight: 600; text-transform: capitalize; }
.ticket-status.open { background-color: #3b82f6; color: white; }
.ticket-status.in_progress { background-color: #f59e0b; color: white; }
.ticket-status.closed { background-color: #10b981; color: white; }
.priority-badge { padding: 0.2rem 0.6rem; border-radius: 9999px; font-size: 0.75rem; text-transform: capitalize; }
.priority-low { background-color: #e5e7eb; color: #4b5563; }
.priority-medium { background-color: #fef3c7; color: #92400e; }
.priority-high { background-color: #fee2e2; color: #b91c1c; }

.timeline { padding-left: 1.5rem; }
.timeline-item { position: relative; padding-bottom: 1.5rem; }
.timeline-item:not(:last-child)::before { content: ''; position: absolute; top: 20px; left: -25px; bottom: -20px; width: 2px; background-color: var(--border-color); }
.timeline-avatar { position: absolute; left: -45px; top: 0; width: 40px; height: 40px; border-radius: 50%; background-color: white; border: 2px solid var(--border-color); display: flex; align-items: center; justify-content: center; }
.timeline-avatar img { width: 100%; height: 100%; object-fit: cover; border-radius: 50%; }
.timeline-avatar .initials, .timeline-avatar i { font-weight: 600; font-size: 1.25rem; }
.timeline-avatar .initials { color: var(--primary-color); }
.timeline-avatar i { color: #3b82f6; }

.message-bubble { padding: 1rem; border-radius: 0.75rem; background-color: var(--gray-light); }
.message-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; font-size: 0.875rem; color: #6b7280; }
.message-sender { font-weight: 600; }
.message-content { white-space: pre-wrap; word-wrap: break-word; }
.attachment-link { display: inline-flex; align-items: center; background-color: #e5e7eb; padding: 0.5rem 1rem; border-radius: 0.375rem; text-decoration: none; color: var(--gray-dark); margin-top: 1rem; }
.attachment-link:hover { background-color: #d1d5db; }

.reply-form { border: 1px solid var(--border-color); border-radius: 0.75rem; padding: 1.5rem; }
.char-counter { font-size: 0.75rem; color: #6b7280; }
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex align-items-center mb-4">
            <a href="tickets.php" class="btn btn-light me-3" style="border-radius: 50%; width: 40px; height: 40px; display: grid; place-content: center;" title="Back to Tickets"><i class='bx bx-arrow-back'></i></a>
            <div>
                <h1 class="h3 mb-0">Ticket Details</h1>
                <p class="text-muted mb-0">
                    Ticket #<?php echo $ticket_id; ?>
                    <button class="btn btn-sm btn-link p-0 ms-2" onclick="copyToClipboard('<?php echo $ticket_id; ?>', this)" title="Copy Ticket ID"><i class='bx bx-copy'></i></button>
                </p>
            </div>
        </div>

        <?php if ($success_message): ?><div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo $success_message; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if ($error_message): ?><div class="alert alert-danger alert-dismissible fade show" role="alert"><?php echo $error_message; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="ticket-header">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <h2 class="h4 mb-0"><?php echo htmlspecialchars($ticket['subject']); ?></h2>
                <span class="ticket-status <?php echo $ticket['status']; ?>"><?php echo str_replace('_', ' ', $ticket['status']); ?></span>
            </div>
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <span class="priority-badge priority-<?php echo $ticket['priority']; ?>"><?php echo $ticket['priority']; ?> Priority</span>
                    <span class="ms-3 text-muted small">Created: <?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></span>
                </div>
                <?php if ($ticket['status'] !== 'closed'): ?>
                    <button class="btn btn-sm btn-outline-danger" onclick="handleCloseTicket()">Close Ticket</button>
                <?php endif; ?>
            </div>
        </div>

        <div class="timeline" id="messageContainer">
            <?php foreach ($messages as $message): ?>
                <div class="timeline-item">
                    <div class="timeline-avatar">
                        <?php if ($message['is_admin']): ?>
                            <i class='bx bxs-user-badge'></i>
                        <?php elseif (!empty($message['profile_picture'])): ?>
                            <img src="<?php echo BASE_URL . 'uploads/profiles/' . htmlspecialchars($message['profile_picture']); ?>" alt="Avatar">
                        <?php else: ?>
                            <span class="initials"><?php echo strtoupper(substr($message['first_name'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="message-bubble">
                        <div class="message-header">
                            <div class="message-sender">
                                <?php echo $message['is_admin'] ? 'Support Team' : htmlspecialchars($message['first_name'] . ' ' . $message['last_name']); ?>
                            </div>
                            <div class="message-time"><?php echo date('M j, Y g:i A', strtotime($message['created_at'])); ?></div>
                        </div>
                        <div class="message-content">
                            <?php if (!empty($message['message'])): ?>
                                <p class="mb-0"><?php echo nl2br(htmlspecialchars($message['message'])); ?></p>
                            <?php endif; ?>
                            <?php if (!empty($message['attachment'])): ?>
                                <a href="<?php echo BASE_URL . 'uploads/ticket_attachments/' . htmlspecialchars($message['attachment']); ?>" target="_blank" class="attachment-link">
                                    <i class='bx bx-file me-2'></i> <?php echo htmlspecialchars($message['attachment']); ?>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if ($ticket['status'] !== 'closed'): ?>
            <div class="reply-form mt-4">
                <h5 class="mb-3">Reply to this ticket</h5>
                <form method="POST" action="ticket_details.php?id=<?php echo $ticket_id; ?>" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="reply">
                    <div class="mb-3">
                        <textarea class="form-control" name="message" id="messageText" rows="5" placeholder="Type your message here..." maxlength="2000"></textarea>
                        <div class="d-flex justify-content-between mt-1">
                            <small id="file-chosen" class="text-muted"></small>
                            <small id="char-counter" class="char-counter">2000 characters remaining</small>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <label for="attachment" class="btn btn-light"><i class='bx bx-paperclip'></i> Attach File</label>
                        <input type="file" name="attachment" id="attachment" class="d-none">
                        <button type="submit" class="btn btn-primary">Send Reply <i class='bx bx-send ms-1'></i></button>
                    </div>
                </form>
            </div>
        <?php else: ?>
            <div class="alert alert-info text-center"><i class='bx bx-info-circle me-2'></i> This ticket is closed. To re-open it, please create a new ticket.</div>
        <?php endif; ?>
    </div>
</div>

<!-- Hidden form for closing the ticket -->
<form id="closeTicketForm" action="ticket_details.php?id=<?php echo $ticket_id; ?>" method="POST" style="display: none;">
    <input type="hidden" name="action" value="close_ticket">
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto-scroll to the bottom of the messages
    const messageContainer = document.getElementById('messageContainer');
    if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
    }

    // Character counter for textarea
    const messageText = document.getElementById('messageText');
    const charCounter = document.getElementById('char-counter');
    if (messageText && charCounter) {
        messageText.addEventListener('input', function() {
            const remaining = this.maxLength - this.value.length;
            charCounter.textContent = `${remaining} characters remaining`;
        });
    }

    // Display selected filename
    const attachmentInput = document.getElementById('attachment');
    const fileChosenText = document.getElementById('file-chosen');
    if (attachmentInput && fileChosenText) {
        attachmentInput.addEventListener('change', function() {
            fileChosenText.textContent = this.files.length > 0 ? this.files[0].name : '';
        });
    }
});

// Function to handle closing a ticket with a confirmation
function handleCloseTicket() {
    Swal.fire({
        title: 'Are you sure?',
        text: "Do you want to close this ticket? You can reopen it later by replying.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, close it!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('closeTicketForm').submit();
        }
    });
}

// Simple copy to clipboard function
function copyToClipboard(text, element) {
    navigator.clipboard.writeText(text).then(() => {
        const originalTitle = element.getAttribute('data-bs-original-title');
        const tooltip = bootstrap.Tooltip.getInstance(element);
        if (tooltip) {
            tooltip.setContent({ '.tooltip-inner': 'Copied!' });
            setTimeout(() => {
                tooltip.setContent({ '.tooltip-inner': originalTitle });
            }, 2000);
        }
    });
}
</script>

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