<?php
session_start();
include 'layouts/dbconn.php';
// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}
// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);
if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}
// Check if ticket ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid ticket ID.";
    header('Location: my_tickets.php');
    exit();
}
$ticket_id = intval($_GET['id']);

// Fetch ticket details
$sql = "SELECT t.*, u.username, u.full_name
        FROM support_tickets t
        JOIN users u ON t.user_id = u.user_id
        WHERE t.ticket_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $ticket_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Ticket not found.";
    header('Location: my_tickets.php');
    exit();
}
$ticket = $result->fetch_assoc();

// Check if the user has access to this ticket
// Regular users can only view their own tickets
// Staff/admins can view all tickets
$is_admin = in_array($role_id, [1, 2, 3]); // Adjust role IDs as needed
$has_access = ($ticket['user_id'] == $user_id) || $is_admin;
if (!$has_access) {
    $_SESSION['error_message'] = "You don't have permission to view this ticket.";
    header('Location: my_tickets.php');
    exit();
}

// Fetch ticket messages
$sql = "SELECT m.*, u.username, u.full_name, u.user_role
        FROM ticket_messages m
        JOIN users u ON m.user_id = u.user_id
        WHERE m.ticket_id = ?
        ORDER BY m.created_at ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $ticket['id']); // Assuming 'id' is the primary key in support_tickets
$stmt->execute();
$messages_result = $stmt->get_result();
$messages = [];
while ($message = $messages_result->fetch_assoc()) {
    $messages[] = $message;
}

// Handle adding new message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $message = trim($_POST['message']);
    $status_update = isset($_POST['status']) ? $_POST['status'] : null;

    $errors = [];

    // Validate message content
    if (empty($message)) {
        $errors[] = "Message content cannot be empty.";
    }

    if (empty($errors)) {
        // Start transaction
        $conn->begin_transaction();

        try {
            // Insert new message
            $sql = "INSERT INTO ticket_messages (ticket_id, user_id, message, created_at) 
                    VALUES (?, ?, ?, NOW())";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iis", $ticket['id'], $user_id, $message);
            $stmt->execute();

            // Update ticket status if requested
            if ($status_update && $is_admin) {
                $sql = "UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("si", $status_update, $ticket['id']);
                $stmt->execute();
                
                // Update ticket status in local variable for immediate display
                $ticket['status'] = $status_update;
            } else {
                // Just update the timestamp
                $sql = "UPDATE support_tickets SET updated_at = NOW() WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("i", $ticket['id']);
                $stmt->execute();
            }

            // Handle file uploads
            if (!empty($_FILES['attachments']) && is_array($_FILES['attachments']['name'])) {
                $upload_dir = 'uploads/tickets/';
                
                // Create directory if it doesn't exist
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }
                
                $message_id = $conn->insert_id; // Get the new message ID
                
                // Process each file
                for ($i = 0; $i < count($_FILES['attachments']['name']); $i++) {
                    if ($_FILES['attachments']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES['attachments']['tmp_name'][$i];
                        $name = basename($_FILES['attachments']['name'][$i]);
                        $file_type = $_FILES['attachments']['type'][$i];
                        $file_size = $_FILES['attachments']['size'][$i];
                        
                        // Generate unique filename
                        $new_filename = uniqid() . '_' . $name;
                        $upload_path = $upload_dir . $new_filename;
                        
                        if (move_uploaded_file($tmp_name, $upload_path)) {
                            // Save file info to database
                            $sql = "INSERT INTO ticket_attachments (
                                        message_id, file_name, file_path, file_type, file_size
                                    ) VALUES (?, ?, ?, ?, ?)";
                            
                            $stmt = $conn->prepare($sql);
                            if (!$stmt) {
                                throw new Exception("Error preparing statement: " . $conn->error);
                            }
                            
                            $stmt->bind_param("isssi", $message_id, $name, $upload_path, $file_type, $file_size);
                            
                            if (!$stmt->execute()) {
                                throw new Exception("Error saving attachment: " . $stmt->error);
                            }
                        } else {
                            throw new Exception("Error uploading file: " . $name);
                        }
                    }
                }
            }

            // Commit transaction
            $conn->commit();

            // Add success message
            $_SESSION['success_message'] = "Your reply has been added successfully.";
            
            // Redirect to refresh the page and avoid form resubmission
            header("Location: view_ticket.php?id=" . urlencode($reference_number));
            exit();
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}

// Mark ticket as read if viewing and status is new
if ($ticket['status'] === 'new') {
    $sql = "UPDATE support_tickets SET status = 'open', updated_at = NOW() WHERE id = ? AND status = 'new'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $ticket['id']);
    $stmt->execute();
    
    // Update ticket status in local variable for immediate display
    $ticket['status'] = 'open';
}

// Fetch initial ticket message
$sql = "SELECT m.*, u.username, u.full_name, u.user_role
        FROM ticket_messages m
        JOIN users u ON m.user_id = u.user_id
        WHERE m.ticket_id = ?
        ORDER BY m.created_at ASC
        LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $ticket['id']);
$stmt->execute();
$initial_message_result = $stmt->get_result();
$initial_message = null;
if ($initial_message_result->num_rows > 0) {
    $initial_message = $initial_message_result->fetch_assoc();
}

// Fetch ticket attachments
$sql = "SELECT a.* 
        FROM ticket_attachments a
        JOIN ticket_messages m ON a.message_id = m.message_id
        WHERE m.ticket_id = ?
        ORDER BY a.uploaded_at ASC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $ticket['id']);
$stmt->execute();
$attachments_result = $stmt->get_result();
$attachments = [];
while ($attachment = $attachments_result->fetch_assoc()) {
    $attachments[] = $attachment;
}

// Helper function to format date
function formatDate($date) {
    return date('M d, Y h:i A', strtotime($date));
}

// Get status badge color
function getStatusBadgeColor($status) {
    switch ($status) {
        case 'new':
            return 'bg-info';
        case 'open':
            return 'bg-primary';
        case 'in_progress':
            return 'bg-warning';
        case 'resolved':
            return 'bg-success';
        case 'closed':
            return 'bg-secondary';
        default:
            return 'bg-light';
    }
}

// Get priority badge color
function getPriorityBadgeColor($priority) {
    switch ($priority) {
        case 'low':
            return 'bg-success';
        case 'medium':
            return 'bg-warning';
        case 'high':
            return 'bg-danger';
        case 'critical':
            return 'bg-dark';
        default:
            return 'bg-light';
    }
}

// Get humanized status name
function getStatusName($status) {
    switch ($status) {
        case 'in_progress':
            return 'In Progress';
        default:
            return ucfirst($status);
    }
}

// Include layout files
include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Ticket')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .message-bubble {
            position: relative;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        
        .message-user {
            background-color: #f0f0f0;
            margin-right: 50px;
        }
        
        .message-admin {
            background-color: #e3f2fd;
            margin-left: 50px;
        }
        
        .message-header {
            border-bottom: 1px solid rgba(0,0,0,0.1);
            padding-bottom: 8px;
            margin-bottom: 10px;
        }
        
        .message-content {
            white-space: pre-wrap;
        }
        
        .file-attachment {
            display: inline-block;
            padding: 6px 12px;
            margin: 5px;
            border-radius: 4px;
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
        }
        
        .ticket-details-card {
            border-left: 4px solid 
            <?php 
                $color = '';
                switch($ticket['priority']) {
                    case 'low': $color = '#28a745'; break;
                    case 'medium': $color = '#ffc107'; break;
                    case 'high': $color = '#dc3545'; break;
                    case 'critical': $color = '#343a40'; break;
                    default: $color = '#6c757d';
                }
                echo $color;
            ?>;
        }
        
        .ticket-message-date {
            font-size: 0.8rem;
            color: #6c757d;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Support', 'title' => 'View Ticket')); ?>

                    <!-- Alert Messages -->
                    <?php if (isset($errors) && !empty($errors)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <ul class="mb-0">
                                <?php foreach ($errors as $error): ?>
                                    <li><?php echo $error; ?></li>
                                <?php endforeach; ?>
                            </ul>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Ticket Details Card -->
                        <div class="col-lg-4">
                            <div class="card ticket-details-card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h5 class="card-title mb-0">Ticket Information</h5>
                                        <span class="badge <?php echo getStatusBadgeColor($ticket['status']); ?>">
                                            <?php echo getStatusName($ticket['status']); ?>
                                        </span>
                                    </div>
                                    
                                    <h6 class="mb-3">
                                        <i class="ri-file-text-line me-1"></i>
                                        #<?php echo htmlspecialchars($ticket['reference_number']); ?> - <?php echo htmlspecialchars($ticket['subject']); ?>
                                    </h6>
                                    
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-1">Submitted by:</span>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-xs me-2">
                                                <span class="avatar-title rounded-circle bg-primary">
                                                    <?php echo substr($ticket['full_name'], 0, 1); ?>
                                                </span>
                                            </div>
                                            <div>
                                                <h6 class="mb-0"><?php echo htmlspecialchars($ticket['full_name']); ?></h6>
                                                <small class="text-muted"><?php echo htmlspecialchars($ticket['username']); ?></small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-1">Created on:</span>
                                        <h6 class="mb-0"><?php echo formatDate($ticket['created_at']); ?></h6>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-1">Last Updated:</span>
                                        <h6 class="mb-0"><?php echo formatDate($ticket['updated_at']); ?></h6>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-1">Category:</span>
                                        <h6 class="mb-0"><?php echo htmlspecialchars($ticket['category']); ?></h6>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-1">Priority:</span>
                                        <h6 class="mb-0">
                                            <span class="badge <?php echo getPriorityBadgeColor($ticket['priority']); ?>">
                                                <?php echo ucfirst($ticket['priority']); ?>
                                            </span>
                                        </h6>
                                    </div>
                                    
                                    <?php if (!empty($attachments)): ?>
                                    <div class="mb-3">
                                        <span class="text-muted d-block mb-2">Attachments:</span>
                                        <div>
                                            <?php foreach ($attachments as $attachment): ?>
                                                <div class="file-attachment">
                                                    <i class="ri-file-line me-1"></i>
                                                    <a href="download_attachment.php?id=<?php echo $attachment['id']; ?>" target="_blank">
                                                        <?php echo htmlspecialchars($attachment['file_name']); ?>
                                                    </a>
                                                    <small class="text-muted ms-2">(<?php echo formatSizeUnits($attachment['file_size']); ?>)</small>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="mt-4">
                                        <a href="my_tickets.php" class="btn btn-sm btn-light">
                                            <i class="ri-arrow-left-line me-1"></i> Back to Tickets
                                        </a>
                                        <?php if ($is_admin && $ticket['status'] !== 'closed'): ?>
                                            <button class="btn btn-sm btn-success ms-2" data-bs-toggle="modal" data-bs-target="#closeTicketModal">
                                                <i class="ri-check-line me-1"></i> Close Ticket
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Messages Card -->
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header pb-3">
                                    <h5 class="card-title mb-0">Conversation</h5>
                                </div>
                                <div class="card-body">
                                    <div class="ticket-messages">
                                        <!-- Initial message from the ticket -->
                                        <?php if ($initial_message): ?>
                                        <div class="message-bubble message-<?php echo ($initial_message['user_id'] == $user_id) ? 'user' : 'admin'; ?>">
                                            <div class="message-header d-flex justify-content-between">
                                                <div>
                                                    <strong><?php echo htmlspecialchars($initial_message['full_name']); ?></strong>
                                                    <small class="text-muted ms-2"><?php echo htmlspecialchars($initial_message['username']); ?></small>
                                                </div>
                                                <div class="ticket-message-date">
                                                    <?php echo formatDate($initial_message['created_at']); ?>
                                                </div>
                                            </div>
                                            <div class="message-content">
                                                <?php echo nl2br(htmlspecialchars($initial_message['message'])); ?>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Subsequent messages -->
                                        <?php foreach ($messages as $index => $message): ?>
                                            <?php if ($index > 0 || !$initial_message): // Skip first message if we already displayed it as initial message ?>
                                            <div class="message-bubble message-<?php echo ($message['user_id'] == $user_id) ? 'user' : 'admin'; ?>">
                                                <div class="message-header d-flex justify-content-between">
                                                    <div>
                                                        <strong><?php echo htmlspecialchars($message['full_name']); ?></strong>
                                                        <small class="text-muted ms-2"><?php echo htmlspecialchars($message['username']); ?></small>
                                                        <?php if ($message['user_role'] == 'admin'): ?>
                                                            <span class="badge bg-primary ms-1">Staff</span>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="ticket-message-date">
                                                        <?php echo formatDate($message['created_at']); ?>
                                                    </div>
                                                </div>
                                                <div class="message-content">
                                                    <?php echo nl2br(htmlspecialchars($message['message'])); ?>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                        <?php endforeach; ?>
                                    </div>
                                    
                                    <!-- Reply Form -->
                                    <?php if ($ticket['status'] !== 'closed'): ?>
                                        <div class="reply-form mt-4">
                                            <h5 class="mb-3">Reply to Ticket</h5>
                                            <form action="" method="post" enctype="multipart/form-data">
                                                <div class="mb-3">
                                                    <textarea class="form-control" name="message" rows="4" placeholder="Type your reply here..." required></textarea>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">Attachments (optional):</label>
                                                    <input type="file" class="form-control" name="attachments[]" multiple>
                                                    <small class="form-text text-muted">You can upload multiple files. Maximum size per file: 5MB.</small>
                                                </div>
                                                
                                                <?php if ($is_admin): ?>
                                                <div class="mb-3">
                                                    <label class="form-label">Update Status:</label>
                                                    <select class="form-select" name="status">
                                                        <option value="">Don't change</option>
                                                        <option value="open" <?php echo ($ticket['status'] === 'open') ? 'selected' : ''; ?>>Open</option>
                                                        <option value="in_progress" <?php echo ($ticket['status'] === 'in_progress') ? 'selected' : ''; ?>>In Progress</option>
                                                        <option value="resolved" <?php echo ($ticket['status'] === 'resolved') ? 'selected' : ''; ?>>Resolved</option>
                                                    </select>
                                                </div>
                                                <?php endif; ?>
                                                
                                                <div class="text-end">
                                                    <button type="submit" name="reply" class="btn btn-primary">
                                                        <i class="ri-mail-send-line me-1"></i> Send Reply
                                                    </button>
                                                </div>
                                            </form>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-info mt-4 mb-0">
                                            <i class="ri-information-line me-2"></i>
                                            This ticket is closed. Please open a new ticket if you have additional questions.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Close Ticket Modal -->
    <div class="modal fade" id="closeTicketModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Close Ticket</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="" method="post">
                    <div class="modal-body">
                        <p>Are you sure you want to close this ticket? This action cannot be undone.</p>
                        <div class="mb-3">
                            <label class="form-label">Closing Note:</label>
                            <textarea class="form-control" name="message" rows="3" placeholder="Optional closing note" required></textarea>
                        </div>
                        <input type="hidden" name="status" value="closed">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="reply" class="btn btn-success">Close Ticket</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- Helper function to format file size -->
    <?php
    function formatSizeUnits($bytes) {
        if ($bytes >= 1073741824) {
            $bytes = number_format($bytes / 1073741824, 2) . ' GB';
        } elseif ($bytes >= 1048576) {
            $bytes = number_format($bytes / 1048576, 2) . ' MB';
        } elseif ($bytes >= 1024) {
            $bytes = number_format($bytes / 1024, 2) . ' KB';
        } elseif ($bytes > 1) {
            $bytes = $bytes . ' bytes';
        } elseif ($bytes == 1) {
            $bytes = $bytes . ' byte';
        } else {
            $bytes = '0 bytes';
        }
        return $bytes;
    }
    ?>

    <script>
        // Auto-scroll to bottom of messages on page load
        document.addEventListener('DOMContentLoaded', function() {
            const messagesContainer = document.querySelector('.ticket-messages');
            if (messagesContainer) {
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }
        });
    </script>
</body>
</html>