<?php
require_once '../includes/header.php';

// Check if user is logged in
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    redirect(SITE_URL . '/auth/login.php');
}

require_once '../includes/ticket_functions.php';

// Get ticket ID from URL
$ticket_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Get ticket details
$ticket = getTicketById($pdo, $ticket_id);

// Check if ticket exists and user has permission to view it
if (!$ticket || ($ticket['user_id'] != $_SESSION['user_id'] && !isAdmin())) {
    redirect(SITE_URL . '/tickets/my_tickets.php');
}

// Get ticket replies
$replies = getTicketReplies($pdo, $ticket_id, isAdmin());

// Get ticket attachments
$attachments = getTicketAttachments($pdo, $ticket_id);

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $reply_message = sanitizeTicketInput($_POST['reply_message']);
    
    // Validation
    if (empty($reply_message)) {
        $message = '<div class="message error">Please enter a message.</div>';
    } else if (strlen($reply_message) > 5000) {
        $message = '<div class="message error">Message is too long. Maximum 5000 characters.</div>';
    } else {
        // Add reply (customers can only add public replies)
        if (addTicketReply($pdo, $ticket_id, $_SESSION['user_id'], $reply_message, 0)) {
            $message = '<div class="message success">Reply added successfully!</div>';
            // Refresh replies
            $replies = getTicketReplies($pdo, $ticket_id, isAdmin());
        } else {
            $message = '<div class="message error">Error adding reply. Please try again.</div>';
        }
    }
}

// Handle satisfaction rating after resolution
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['satisfaction_rating']) && $ticket['status'] === 'Resolved') {
    $rating = (int)$_POST['satisfaction_rating'];
    if ($rating >= 1 && $rating <= 5) {
        if (updateSatisfactionRating($pdo, $ticket_id, $rating)) {
            $message = '<div class="message success">Thank you for your feedback!</div>';
            // Refresh ticket
            $ticket = getTicketById($pdo, $ticket_id);
        } else {
            $message = '<div class="message error">Error submitting rating. Please try again.</div>';
        }
    } else {
        $message = '<div class="message error">Invalid rating.</div>';
    }
}
?>

<div class="container">
    <div class="section-title">
        <h2>Ticket #<?php echo $ticket['id']; ?>: <?php echo htmlspecialchars($ticket['subject']); ?></h2>
    </div>
    
    <?php echo $message; ?>
    
    <div class="product-detail">
        <div class="product-detail-info">
            <div class="ticket-details">
                <table class="cart-table">
                    <tr>
                        <th>Type:</th>
                        <td><?php echo htmlspecialchars($ticket['type_name']); ?></td>
                    </tr>
                    <tr>
                        <th>Status:</th>
                        <td>
                            <span class="status-<?php echo strtolower(str_replace(' ', '-', $ticket['status'])); ?>">
                                <?php echo $ticket['status']; ?>
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <th>Priority:</th>
                        <td><?php echo $ticket['priority']; ?></td>
                    </tr>
                    <?php if ($ticket['order_id']): ?>
                    <tr>
                        <th>Associated Order:</th>
                        <td>Order #<?php echo $ticket['order_id']; ?> - $<?php echo number_format($ticket['order_total'], 2); ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <th>Created:</th>
                        <td><?php echo date('M j, Y g:i A', strtotime($ticket['created_at'])); ?></td>
                    </tr>
                    <tr>
                        <th>Last Updated:</th>
                        <td><?php echo date('M j, Y g:i A', strtotime($ticket['updated_at'])); ?></td>
                    </tr>
                    <?php if ($ticket['assigned_to']): ?>
                    <tr>
                        <th>Assigned To:</th>
                        <td><?php echo htmlspecialchars($ticket['agent_name']); ?></td>
                    </tr>
                    <?php endif; ?>
                </table>
            </div>
            
            <div class="ticket-description">
                <h3>Description</h3>
                <p><?php echo nl2br(htmlspecialchars($ticket['description'])); ?></p>
            </div>
            
            <?php if (!empty($attachments)): ?>
            <div class="ticket-attachments">
                <h3>Attachments</h3>
                <ul>
                    <?php foreach ($attachments as $attachment): ?>
                        <li>
                            <a href="<?php echo SITE_URL . '/' . htmlspecialchars($attachment['file_path']); ?>" target="_blank">
                                <i class="fas fa-paperclip"></i> <?php echo htmlspecialchars($attachment['file_name']); ?>
                            </a>
                            (<?php echo round($attachment['file_size'] / 1024, 2); ?> KB)
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <?php if ($ticket['status'] === 'Resolved' && !$ticket['satisfaction_rating']): ?>
            <div class="satisfaction-rating">
                <h3>Rate Your Experience</h3>
                <form method="POST" action="">
                    <div class="rating-stars">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <label class="rating-star">
                                <input type="radio" name="satisfaction_rating" value="<?php echo $i; ?>" required>
                                <i class="fas fa-star"></i>
                            </label>
                        <?php endfor; ?>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit Rating</button>
                </form>
            </div>
            <?php elseif ($ticket['satisfaction_rating']): ?>
            <div class="satisfaction-rating">
                <h3>Your Rating</h3>
                <div class="rating-display">
                    <?php for ($i = 1; $i <= 5; $i++): ?>
                        <i class="fas fa-star <?php echo $i <= $ticket['satisfaction_rating'] ? 'rated' : ''; ?>"></i>
                    <?php endfor; ?>
                    (<?php echo $ticket['satisfaction_rating']; ?>/5)
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="section-title">
        <h3>Replies</h3>
    </div>
    
    <div class="ticket-replies">
        <?php if (empty($replies)): ?>
            <p>No replies yet.</p>
        <?php else: ?>
            <?php foreach ($replies as $reply): ?>
                <div class="reply <?php echo $reply['is_internal'] ? 'internal' : 'public'; ?>">
                    <div class="reply-header">
                        <strong><?php echo htmlspecialchars($reply['author_name']); ?></strong>
                        <span class="reply-role"><?php echo ucfirst($reply['author_role']); ?></span>
                        <span class="reply-date"><?php echo date('M j, Y g:i A', strtotime($reply['created_at'])); ?></span>
                        <?php if ($reply['is_internal']): ?>
                            <span class="internal-badge">Internal Note</span>
                        <?php endif; ?>
                    </div>
                    <div class="reply-message">
                        <?php echo nl2br(htmlspecialchars($reply['message'])); ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <?php if ($ticket['status'] !== 'Closed'): ?>
    <div class="form-container">
        <h3>Add Reply</h3>
        <form method="POST" action="">
            <div class="form-group">
                <textarea id="reply_message" name="reply_message" rows="4" placeholder="Type your reply here..." required></textarea>
            </div>
            <button type="submit" name="reply" class="btn btn-primary">Send Reply</button>
        </form>
    </div>
    <?php endif; ?>
</div>

<style>
.ticket-details table {
    width: 100%;
}

.ticket-details th {
    text-align: left;
    width: 30%;
}

.reply {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    border-left: 4px solid #3498db;
}

.reply.internal {
    border-left-color: #f39c12;
    background: #fff8e1;
}

.reply-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    flex-wrap: wrap;
    gap: 10px;
}

.reply-role {
    background: #3498db;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
}

.internal-badge {
    background: #f39c12;
    color: white;
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
}

.reply-date {
    color: #7f8c8d;
    font-size: 0.9rem;
}

.rating-stars {
    display: flex;
    margin: 15px 0;
}

.rating-star {
    margin-right: 10px;
    cursor: pointer;
}

.rating-star input {
    display: none;
}

.rating-star i {
    color: #ddd;
    font-size: 2rem;
}

.rating-star input:checked ~ i,
.rating-star input:hover ~ i {
    color: #f39c12;
}

.rating-display .fa-star.rated {
    color: #f39c12;
}

.status-new { color: #3498db; font-weight: bold; }
.status-in-review { color: #f39c12; font-weight: bold; }
.status-resolved { color: #2ecc71; font-weight: bold; }
.status-closed { color: #95a5a6; font-weight: bold; }
</style>

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