<?php
$page_title = "View Support Ticket";
require_once 'header.php';

$db = Database::getInstance()->connect();
$ticket_id = $_GET['id'] ?? 0;

if (!$ticket_id) {
    header("Location: support.php");
    exit();
}

// Get ticket details
$stmt = $db->prepare("SELECT t.*, u.username, u.email, u.account_status 
                     FROM support_tickets t 
                     LEFT JOIN users u ON t.user_id = u.id 
                     WHERE t.id = ?");
$stmt->execute([$ticket_id]);
$ticket = $stmt->fetch();

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

// Handle reply
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $reply = trim($_POST['reply_message']);
    
    if (empty($reply)) {
        $error = "Please enter a reply message";
    } else {
        try {
            $db->beginTransaction();
            
            // Update ticket
            $update_stmt = $db->prepare("UPDATE support_tickets SET 
                                        status = 'answered',
                                        replied_by = ?,
                                        replied_at = NOW(),
                                        updated_at = NOW()
                                        WHERE id = ?");
            $update_stmt->execute([$_SESSION['admin_id'], $ticket_id]);
            
            // Insert reply into ticket_replies table
            $reply_stmt = $db->prepare("INSERT INTO ticket_replies (ticket_id, user_id, user_type, message, created_at) VALUES (?, ?, 'admin', ?, NOW())");
            $reply_stmt->execute([$ticket_id, $_SESSION['admin_id'], $reply]);
            
            // Log action
            $log_stmt = $db->prepare("INSERT INTO activity_logs (admin_id, user_id, action, description, ip_address, user_agent, details, created_at) VALUES (?, ?, 'ticket_reply', 'Replied to support ticket', ?, ?, ?, NOW())");
            $log_stmt->execute([
                $_SESSION['admin_id'],
                $ticket['user_id'],
                $_SERVER['REMOTE_ADDR'] ?? '',
                $_SERVER['HTTP_USER_AGENT'] ?? '',
                json_encode([
                    'ticket_id' => $ticket_id,
                    'ticket_subject' => $ticket['subject'],
                    'replied_by' => $_SESSION['admin_username']
                ])
            ]);
            
            // Send email notification to user
            $user_email = $ticket['email'];
            $subject = "RE: " . $ticket['subject'] . " - Ticket #" . $ticket['ticket_id'];
            $message = "Dear " . $ticket['username'] . ",\n\n" .
                      "Our support team has replied to your ticket:\n\n" .
                      "Your Message:\n" . $ticket['message'] . "\n\n" .
                      "Admin Reply:\n" . $reply . "\n\n" .
                      "You can view this ticket in your account dashboard.\n\n" .
                      "Best regards,\n" .
                      SITE_NAME . " Support Team";
            
            // mail($user_email, $subject, $message);
            
            $db->commit();
            $success = "Reply sent successfully!";
            
            // Refresh ticket data
            $stmt = $db->prepare("SELECT t.*, u.username, u.email, u.account_status 
                                 FROM support_tickets t 
                                 LEFT JOIN users u ON t.user_id = u.id 
                                 WHERE t.id = ?");
            $stmt->execute([$ticket_id]);
            $ticket = $stmt->fetch();
            
        } catch (Exception $e) {
            $db->rollBack();
            $error = "Failed to send reply: " . $e->getMessage();
        }
    }
}

// Handle status change
if (isset($_GET['action']) && $_GET['action'] == 'change_status') {
    $new_status = $_GET['status'];
    
    $update_stmt = $db->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
    $update_stmt->execute([$new_status, $ticket_id]);
    
    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();
?>

<div class="container-fluid">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-xl shadow p-6 mb-6">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <div>
                    <div class="flex items-center space-x-4">
                        <div>
                            <h1 class="text-2xl font-bold">Ticket #<?php echo $ticket['ticket_id']; ?></h1>
                            <p class="text-gray-600"><?php echo htmlspecialchars($ticket['subject']); ?></p>
                        </div>
                        <span class="px-3 py-1 rounded-full text-sm font-semibold <?php
                            echo $ticket['status'] == 'open' ? 'bg-red-100 text-red-800' :
                                ($ticket['status'] == 'answered' ? 'bg-green-100 text-green-800' :
                                'bg-gray-100 text-gray-800');
                        ?>">
                            <?php echo ucfirst($ticket['status']); ?>
                        </span>
                    </div>
                </div>
                
                <div class="flex space-x-2">
                    <a href="support.php" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50">
                        <i class="fas fa-arrow-left mr-2"></i>Back to Tickets
                    </a>
                    
                    <div class="relative group">
                        <button class="px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-900">
                            <i class="fas fa-cog mr-2"></i>Actions
                        </button>
                        <div class="absolute right-0 mt-2 w-48 bg-white shadow-xl rounded-lg p-2 hidden group-hover:block z-50">
                            <?php if ($ticket['status'] != 'closed'): ?>
                            <a href="?id=<?php echo $ticket_id; ?>&action=change_status&status=closed" 
                               onclick="return confirm('Close this ticket?')"
                               class="block px-4 py-2 text-red-600 hover:bg-red-50 rounded">
                                <i class="fas fa-times mr-2"></i>Close Ticket
                            </a>
                            <?php else: ?>
                            <a href="?id=<?php echo $ticket_id; ?>&action=change_status&status=open" 
                               onclick="return confirm('Reopen this ticket?')"
                               class="block px-4 py-2 text-green-600 hover:bg-green-50 rounded">
                                <i class="fas fa-redo mr-2"></i>Reopen Ticket
                            </a>
                            <?php endif; ?>
                            
                            <a href="support.php?action=delete&id=<?php echo $ticket_id; ?>" 
                               onclick="return confirm('Delete this ticket?')"
                               class="block px-4 py-2 text-red-600 hover:bg-red-50 rounded">
                                <i class="fas fa-trash mr-2"></i>Delete Ticket
                            </a>
                            
                            <a href="mailto:<?php echo htmlspecialchars($ticket['email']); ?>" 
                               class="block px-4 py-2 text-blue-600 hover:bg-blue-50 rounded">
                                <i class="fas fa-envelope mr-2"></i>Email User
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if ($error): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
            <?php echo $error; ?>
        </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <?php echo $success; ?>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Main Content -->
            <div class="lg:col-span-2 space-y-6">
                <!-- User Message -->
                <div class="bg-white rounded-xl shadow p-6">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full flex items-center justify-center text-white font-bold">
                                <?php echo strtoupper(substr($ticket['username'], 0, 1)); ?>
                            </div>
                            <div>
                                <p class="font-semibold"><?php echo htmlspecialchars($ticket['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($ticket['email']); ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm text-gray-500"><?php echo date('F j, Y g:i A', strtotime($ticket['created_at'])); ?></p>
                            <p class="text-xs text-gray-500"><?php echo time_ago($ticket['created_at']); ?></p>
                        </div>
                    </div>
                    
                    <div class="border-t pt-4">
                        <div class="prose max-w-none">
                            <?php echo nl2br(htmlspecialchars($ticket['message'])); ?>
                        </div>
                    </div>
                    
                    <!-- Ticket Meta -->
                    <div class="border-t pt-4 mt-4">
                        <div class="flex flex-wrap gap-2">
                            <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-semibold">
                                <i class="fas fa-tag mr-1"></i><?php echo ucfirst($ticket['category']); ?>
                            </span>
                            <span class="px-3 py-1 <?php
                                echo $ticket['priority'] == 'urgent' ? 'bg-red-100 text-red-800' :
                                    ($ticket['priority'] == 'high' ? 'bg-yellow-100 text-yellow-800' :
                                    'bg-gray-100 text-gray-800');
                            ?> rounded-full text-xs font-semibold">
                                <i class="fas fa-flag mr-1"></i><?php echo ucfirst($ticket['priority']); ?> Priority
                            </span>
                            <span class="px-3 py-1 bg-gray-100 text-gray-800 rounded-full text-xs font-semibold">
                                <i class="fas fa-user mr-1"></i>User ID: <?php echo $ticket['user_id']; ?>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Conversation History -->
                <?php foreach ($replies as $reply): 
                    $is_admin = $reply['user_type'] === 'admin';
                ?>
                <div class="bg-white rounded-xl shadow p-6">
                    <div class="flex items-center justify-between mb-4">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 <?php echo $is_admin ? 'bg-gradient-to-r from-green-500 to-blue-500' : 'bg-gradient-to-r from-blue-500 to-purple-500'; ?> rounded-full flex items-center justify-center text-white font-bold">
                                <?php echo $is_admin ? '<i class="fas fa-headset"></i>' : strtoupper(substr($reply['username'] ?? 'U', 0, 1)); ?>
                            </div>
                            <div>
                                <p class="font-semibold"><?php echo $is_admin ? 'Support Team (' . htmlspecialchars($reply['admin_username'] ?? 'Admin') . ')' : htmlspecialchars($reply['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo $is_admin ? 'Staff' : 'User'; ?></p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm text-gray-500"><?php echo date('F j, Y g:i A', strtotime($reply['created_at'])); ?></p>
                            <p class="text-xs text-gray-500"><?php echo time_ago($reply['created_at']); ?></p>
                        </div>
                    </div>
                    <div class="border-t pt-4">
                        <div class="prose max-w-none <?php echo $is_admin ? 'bg-green-50' : 'bg-gray-50'; ?> p-4 rounded-lg">
                            <?php echo nl2br(htmlspecialchars($reply['message'])); ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>

                <!-- Reply Form -->
                <?php if ($ticket['status'] != 'closed'): ?>
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-bold mb-4">Reply to Ticket</h3>
                    <form method="POST" action="">
                        <div class="mb-4">
                            <label class="block text-gray-700 font-medium mb-2">Your Reply *</label>
                            <textarea name="reply_message" rows="6" required
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                                      placeholder="Type your reply here..."><?php echo htmlspecialchars($_POST['reply_message'] ?? ''); ?></textarea>
                        </div>
                        
                        <div class="flex justify-between items-center">
                            <div class="flex items-center space-x-4">
                                <div class="flex items-center">
                                    <input type="checkbox" id="close_ticket" name="close_ticket" value="1"
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="close_ticket" class="ml-2 text-gray-700">
                                        Close ticket after reply
                                    </label>
                                </div>
                                
                                <div class="flex items-center">
                                    <input type="checkbox" id="send_email" name="send_email" value="1" checked
                                           class="h-4 w-4 text-purple-600 focus:ring-purple-500 border-gray-300 rounded">
                                    <label for="send_email" class="ml-2 text-gray-700">
                                        Send email notification
                                    </label>
                                </div>
                            </div>
                            
                            <button type="submit" name="reply"
                                    class="bg-gradient-to-r from-purple-600 to-blue-600 text-white font-bold px-6 py-3 rounded-lg hover:opacity-90">
                                <i class="fas fa-paper-plane mr-2"></i>Send Reply
                            </button>
                        </div>
                    </form>
                </div>
                <?php else: ?>
                <div class="bg-gray-50 border border-gray-200 rounded-xl p-6 text-center">
                    <i class="fas fa-lock text-4xl text-gray-400 mb-4"></i>
                    <h3 class="text-lg font-bold text-gray-600 mb-2">Ticket Closed</h3>
                    <p class="text-gray-500">This ticket has been closed. You can reopen it from the actions menu.</p>
                    <a href="?id=<?php echo $ticket_id; ?>&action=change_status&status=open" 
                       class="inline-block mt-4 bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                        <i class="fas fa-redo mr-2"></i>Reopen Ticket
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <!-- Sidebar -->
            <div class="space-y-6">
                <!-- User Information -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h4 class="text-lg font-bold mb-4">User Information</h4>
                    <div class="space-y-3">
                        <div class="flex justify-between">
                            <span class="text-gray-600">Username:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($ticket['username']); ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Email:</span>
                            <span class="font-medium"><?php echo htmlspecialchars($ticket['email']); ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Account Status:</span>
                            <span class="font-medium <?php echo $ticket['account_status'] == 'active' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo ucfirst($ticket['account_status']); ?>
                            </span>
                        </div>
                        <div class="pt-3">
                            <a href="user-edit.php?id=<?php echo $ticket['user_id']; ?>" 
                               class="block text-center bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                                <i class="fas fa-user-edit mr-2"></i>View User Profile
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Ticket Information -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h4 class="text-lg font-bold mb-4">Ticket Information</h4>
                    <div class="space-y-3">
                        <div class="flex justify-between">
                            <span class="text-gray-600">Ticket ID:</span>
                            <span class="font-mono"><?php echo $ticket['ticket_id']; ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Category:</span>
                            <span class="capitalize"><?php echo $ticket['category']; ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Priority:</span>
                            <span class="font-medium <?php
                                echo $ticket['priority'] == 'urgent' ? 'text-red-600' :
                                    ($ticket['priority'] == 'high' ? 'text-yellow-600' : 'text-gray-600');
                            ?>">
                                <?php echo ucfirst($ticket['priority']); ?>
                            </span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Status:</span>
                            <span class="font-medium <?php
                                echo $ticket['status'] == 'open' ? 'text-red-600' :
                                    ($ticket['status'] == 'answered' ? 'text-green-600' : 'text-gray-600');
                            ?>">
                                <?php echo ucfirst($ticket['status']); ?>
                            </span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Created:</span>
                            <span><?php echo date('M d, Y', strtotime($ticket['created_at'])); ?></span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Last Update:</span>
                            <span><?php echo date('M d, Y', strtotime($ticket['updated_at'])); ?></span>
                        </div>
                        <?php if ($ticket['replied_at']): ?>
                        <div class="flex justify-between">
                            <span class="text-gray-600">Replied:</span>
                            <span><?php echo date('M d, Y', strtotime($ticket['replied_at'])); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h4 class="text-lg font-bold mb-4">Quick Actions</h4>
                    <div class="space-y-3">
                        <button onclick="useTemplate('standard')" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 rounded-lg">
                            <i class="fas fa-file-alt mr-2"></i>Use Standard Reply
                        </button>
                        <button onclick="useTemplate('technical')" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 rounded-lg">
                            <i class="fas fa-cogs mr-2"></i>Technical Issue Template
                        </button>
                        <button onclick="useTemplate('deposit')" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 rounded-lg">
                            <i class="fas fa-money-bill-wave mr-2"></i>Deposit Issue Template
                        </button>
                        <button onclick="useTemplate('withdrawal')" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 rounded-lg">
                            <i class="fas fa-wallet mr-2"></i>Withdrawal Issue Template
                        </button>
                    </div>
                </div>

                <!-- Ticket History -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h4 class="text-lg font-bold mb-4">Ticket History</h4>
                    <div class="space-y-3">
                        <div class="text-sm">
                            <p class="font-medium">Created</p>
                            <p class="text-gray-500"><?php echo date('M d, Y g:i A', strtotime($ticket['created_at'])); ?></p>
                        </div>
                        
                        <?php if ($ticket['replied_at']): ?>
                        <div class="text-sm">
                            <p class="font-medium">Replied</p>
                            <p class="text-gray-500"><?php echo date('M d, Y g:i A', strtotime($ticket['replied_at'])); ?></p>
                            <p class="text-gray-500">By: <?php echo $ticket['replied_by']; ?></p>
                        </div>
                        <?php endif; ?>
                        
                        <div class="text-sm">
                            <p class="font-medium">Last Updated</p>
                            <p class="text-gray-500"><?php echo date('M d, Y g:i A', strtotime($ticket['updated_at'])); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Reply templates
const templates = {
    'standard': `Dear ${'<?php echo htmlspecialchars($ticket["username"]); ?>'},

Thank you for contacting <?php echo SITE_NAME; ?> support.

We have received your ticket and our team is looking into your issue. We will get back to you as soon as possible.

Best regards,
<?php echo SITE_NAME; ?> Support Team`,

    'technical': `Dear ${'<?php echo htmlspecialchars($ticket["username"]); ?>'},

Thank you for reporting this technical issue.

Our technical team has been notified and is investigating the problem. We apologize for any inconvenience caused and will update you as soon as we have more information.

If you need immediate assistance, please try clearing your browser cache or using a different browser.

Best regards,
<?php echo SITE_NAME; ?> Technical Support`,

    'deposit': `Dear ${'<?php echo htmlspecialchars($ticket["username"]); ?>'},

Thank you for your inquiry regarding your deposit.

Please note that deposits typically take 1-24 hours to be processed, depending on the payment method and network confirmations.

If your deposit has been pending for more than 24 hours, please provide us with the transaction hash or payment proof so we can investigate further.

Best regards,
<?php echo SITE_NAME; ?> Finance Team`,

    'withdrawal': `Dear ${'<?php echo htmlspecialchars($ticket["username"]); ?>'},

Thank you for your inquiry regarding your withdrawal.

Withdrawals are processed within 24 hours during business days. Please ensure that your withdrawal details are correct and that you have completed any required verification.

If your withdrawal has been pending for more than 24 hours, it may require manual approval. Our team will process it as soon as possible.

Best regards,
<?php echo SITE_NAME; ?> Finance Team`
};

function useTemplate(templateName) {
    if (confirm('Apply ' + templateName + ' template? This will replace any existing text.')) {
        document.querySelector('textarea[name="reply_message"]').value = templates[templateName];
    }
}

// Auto-save draft
let autoSaveTimer;
const textarea = document.querySelector('textarea[name="reply_message"]');

textarea.addEventListener('input', function() {
    clearTimeout(autoSaveTimer);
    autoSaveTimer = setTimeout(function() {
        localStorage.setItem('ticket_reply_draft_<?php echo $ticket_id; ?>', textarea.value);
    }, 1000);
});

// Load draft on page load
window.addEventListener('load', function() {
    const draft = localStorage.getItem('ticket_reply_draft_<?php echo $ticket_id; ?>');
    if (draft && !textarea.value) {
        textarea.value = draft;
    }
});

// Clear draft on submit
document.querySelector('form')?.addEventListener('submit', function() {
    localStorage.removeItem('ticket_reply_draft_<?php echo $ticket_id; ?>');
});

// Character counter
textarea.addEventListener('input', function() {
    const charCount = this.value.length;
    const counter = document.getElementById('charCounter') || (() => {
        const div = document.createElement('div');
        div.id = 'charCounter';
        div.className = 'text-sm text-gray-500 mt-2';
        this.parentNode.appendChild(div);
        return div;
    })();
    
    counter.textContent = ${charCount} characters;
    
    if (charCount > 5000) {
        counter.className = 'text-sm text-red-500 mt-2';
    } else if (charCount > 3000) {
        counter.className = 'text-sm text-yellow-500 mt-2';
    } else {
        counter.className = 'text-sm text-gray-500 mt-2';
    }
});
</script>

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