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

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

// For this implementation, we'll consider admins as support agents
if (!isAdmin()) {
    redirect(SITE_URL . '/index.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
if (!$ticket) {
    redirect(SITE_URL . '/admin/index.php');
}

// Get ticket replies (including internal notes)
$replies = getTicketReplies($pdo, $ticket_id, true);

// Get internal notes
$internal_notes = getInternalNotes($pdo, $ticket_id);

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

// Get all users for assignment (only admins for now)
$stmt = $pdo->query("SELECT id, username FROM users WHERE role = 'admin' ORDER BY username");
$agents = $stmt->fetchAll(PDO::FETCH_ASSOC);

$message = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_status'])) {
        // Validate status
        $allowed_statuses = ['New', 'In Review', 'Resolved', 'Closed'];
        $new_status = $_POST['status'];
        
        if (in_array($new_status, $allowed_statuses)) {
            if (updateTicketStatus($pdo, $ticket_id, $new_status)) {
                $message = '<div class="message success">Ticket status updated successfully!</div>';
                // Refresh ticket
                $ticket = getTicketById($pdo, $ticket_id);
            } else {
                $message = '<div class="message error">Error updating ticket status. Please try again.</div>';
            }
        } else {
            $message = '<div class="message error">Invalid status.</div>';
        }
    } elseif (isset($_POST['assign_agent'])) {
        $agent_id = (int)$_POST['agent_id'];
        
        // Verify agent exists and is admin
        $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ? AND role = 'admin'");
        $stmt->execute([$agent_id]);
        
        if ($stmt->fetch()) {
            if (assignTicketToAgent($pdo, $ticket_id, $agent_id)) {
                $message = '<div class="message success">Ticket assigned successfully!</div>';
                // Refresh ticket
                $ticket = getTicketById($pdo, $ticket_id);
            } else {
                $message = '<div class="message error">Error assigning ticket. Please try again.</div>';
            }
        } else {
            $message = '<div class="message error">Invalid agent.</div>';
        }
    } elseif (isset($_POST['add_reply'])) {
        $reply_message = sanitizeTicketInput($_POST['reply_message']);
        $is_internal = isset($_POST['is_internal']) ? 1 : 0;
        
        // 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 {
            if (addTicketReply($pdo, $ticket_id, $_SESSION['user_id'], $reply_message, $is_internal)) {
                $message = '<div class="message success">Reply added successfully!</div>';
                // Refresh replies
                $replies = getTicketReplies($pdo, $ticket_id, true);
                $internal_notes = getInternalNotes($pdo, $ticket_id);
            } else {
                $message = '<div class="message error">Error adding reply. Please try again.</div>';
            }
        }
    } elseif (isset($_POST['update_satisfaction'])) {
        $rating = (int)$_POST['satisfaction_rating'];
        
        if ($rating >= 1 && $rating <= 5) {
            if (updateSatisfactionRating($pdo, $ticket_id, $rating)) {
                $message = '<div class="message success">Satisfaction rating updated successfully!</div>';
                // Refresh ticket
                $ticket = getTicketById($pdo, $ticket_id);
            } else {
                $message = '<div class="message error">Error updating satisfaction rating. Please try again.</div>';
            }
        } else {
            $message = '<div class="message error">Invalid rating. Please select a rating between 1 and 5.</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="admin-nav">
        <ul>
            <li><a href="<?php echo SITE_URL; ?>/admin/index.php" class="btn btn-outline">← Back to Dashboard</a></li>
        </ul>
    </div>
    
    <div class="product-detail">
        <div class="product-detail-info">
            <div class="ticket-details">
                <table class="cart-table">
                    <tr>
                        <th>Customer:</th>
                        <td><?php echo htmlspecialchars($ticket['customer_name']); ?></td>
                    </tr>
                    <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; ?>
                    <?php if ($ticket['satisfaction_rating']): ?>
                    <tr>
                        <th>Satisfaction Rating:</th>
                        <td>
                            <?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)
                        </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; ?>
            
            <div class="ticket-actions">
                <div class="form-group">
                    <form method="POST" action="" style="display: inline;">
                        <label for="status">Update Status:</label>
                        <select id="status" name="status">
                            <option value="New" <?php echo $ticket['status'] === 'New' ? 'selected' : ''; ?>>New</option>
                            <option value="In Review" <?php echo $ticket['status'] === 'In Review' ? 'selected' : ''; ?>>In Review</option>
                            <option value="Resolved" <?php echo $ticket['status'] === 'Resolved' ? 'selected' : ''; ?>>Resolved</option>
                            <option value="Closed" <?php echo $ticket['status'] === 'Closed' ? 'selected' : ''; ?>>Closed</option>
                        </select>
                        <input type="hidden" name="update_status" value="1">
                        <button type="submit" class="btn btn-primary">Update Status</button>
                    </form>
                    
                    <form method="POST" action="" style="display: inline; margin-left: 20px;">
                        <label for="agent_id">Assign To:</label>
                        <select id="agent_id" name="agent_id">
                            <option value="">Select Agent</option>
                            <?php foreach ($agents as $agent): ?>
                                <option value="<?php echo $agent['id']; ?>" <?php echo $ticket['assigned_to'] == $agent['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($agent['username']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <input type="hidden" name="assign_agent" value="1">
                        <button type="submit" class="btn btn-primary">Assign</button>
                    </form>
                </div>
                
                <?php if ($ticket['status'] === 'Resolved' && !$ticket['satisfaction_rating']): ?>
                <div class="form-group">
                    <form method="POST" action="">
                        <label>Customer Satisfaction Rating:</label>
                        <div class="rating">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <input type="radio" id="rating<?php echo $i; ?>" name="satisfaction_rating" value="<?php echo $i; ?>" required>
                                <label for="rating<?php echo $i; ?>">★</label>
                            <?php endfor; ?>
                        </div>
                        <input type="hidden" name="update_satisfaction" value="1">
                        <button type="submit" class="btn btn-primary">Submit Rating</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
            
            <div class="ticket-replies">
                <h3>Replies</h3>
                <?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-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-content">
                                <?php echo nl2br(htmlspecialchars($reply['message'])); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <div class="add-reply">
                <h3>Add Reply</h3>
                <form method="POST" action="">
                    <div class="form-group">
                        <textarea name="reply_message" rows="5" placeholder="Enter your reply..." required></textarea>
                    </div>
                    <div class="form-group">
                        <label>
                            <input type="checkbox" name="is_internal" value="1"> 
                            Internal Note (only visible to support agents)
                        </label>
                    </div>
                    <input type="hidden" name="add_reply" value="1">
                    <button type="submit" class="btn btn-primary">Add Reply</button>
                </form>
            </div>
        </div>
    </div>
</div>

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

.ticket-details th {
    width: 25%;
    text-align: left;
    padding: 10px;
    background-color: #f8f9fa;
}

.ticket-details td {
    padding: 10px;
    border-bottom: 1px solid #eee;
}

.status-new {
    background-color: #fff3cd;
    color: #856404;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;
}

.status-in-review {
    background-color: #cce5ff;
    color: #004085;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;
}

.status-resolved {
    background-color: #d4edda;
    color: #155724;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;
}

.status-closed {
    background-color: #e2e3e5;
    color: #383d41;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;
}

.ticket-description {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.ticket-attachments {
    margin: 20px 0;
}

.ticket-attachments ul {
    list-style: none;
    padding: 0;
}

.ticket-attachments li {
    margin-bottom: 10px;
}

.ticket-actions {
    margin: 20px 0;
    padding: 15px;
    background-color: #f8f9fa;
    border-radius: 4px;
}

.reply {
    margin-bottom: 20px;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #eee;
}

.reply.public {
    background-color: #fff;
}

.reply.internal {
    background-color: #e9f7fe;
    border-color: #bee5eb;
}

.reply-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}

.reply-date {
    color: #6c757d;
    font-size: 0.9rem;
}

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

.add-reply {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.rating {
    display: flex;
    margin: 10px 0;
}

.rating input[type="radio"] {
    display: none;
}

.rating label {
    font-size: 2rem;
    color: #ddd;
    cursor: pointer;
    transition: color 0.3s;
}

.rating input[type="radio"]:checked ~ label,
.rating label:hover,
.rating label:hover ~ label {
    color: #ffc107;
}
</style>

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