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

$db = Database::getInstance()->connect();

// Handle actions
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = $_GET['action'];
    $ticket_id = $_GET['id'];
    
    if ($action == 'close') {
        $stmt = $db->prepare("UPDATE support_tickets SET status = 'closed', updated_at = NOW() WHERE id = ?");
        $stmt->execute([$ticket_id]);
        
        $message = "Ticket closed successfully!";
        $success = true;
        
    } elseif ($action == 'delete') {
        $stmt = $db->prepare("DELETE FROM support_tickets WHERE id = ?");
        $stmt->execute([$ticket_id]);
        
        $message = "Ticket deleted successfully!";
        $success = true;
    }
    
    if ($success) {
        echo "<script>alert('$message'); window.location.href='support.php';</script>";
        exit();
    }
}

// Get tickets
$status = $_GET['status'] ?? 'open';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Build query
$where = "WHERE 1=1";
$params = [];

if ($status != 'all') {
    $where .= " AND t.status = ?";
    $params[] = $status;
}

if (isset($_GET['user_id'])) {
    $where .= " AND t.user_id = ?";
    $params[] = $_GET['user_id'];
}

if (isset($_GET['category'])) {
    $where .= " AND t.category = ?";
    $params[] = $_GET['category'];
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM support_tickets t $where";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_tickets = $count_stmt->fetch()['total'];
$total_pages = ceil($total_tickets / $limit);

// Get tickets with user details
$sql = "SELECT t.*, u.username, u.email, u.account_status 
        FROM support_tickets t 
        LEFT JOIN users u ON t.user_id = u.id 
        $where 
        ORDER BY 
            CASE t.priority 
                WHEN 'urgent' THEN 1
                WHEN 'high' THEN 2
                WHEN 'medium' THEN 3
                WHEN 'low' THEN 4
            END,
            t.created_at DESC 
        LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$tickets = $stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open,
    SUM(CASE WHEN status = 'answered' THEN 1 ELSE 0 END) as answered,
    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed,
    SUM(CASE WHEN priority = 'urgent' THEN 1 ELSE 0 END) as urgent,
    SUM(CASE WHEN priority = 'high' THEN 1 ELSE 0 END) as high
    FROM support_tickets";

$stats_stmt = $db->query($stats_sql);
$stats = $stats_stmt->fetch();

// Get categories
$categories_stmt = $db->query("SELECT DISTINCT category FROM support_tickets WHERE category IS NOT NULL");
$categories = $categories_stmt->fetchAll();
?>

<div class="container-fluid">
    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-6 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Tickets</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total']); ?></h3>
                </div>
                <i class="fas fa-ticket-alt text-blue-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Open Tickets</p>
                    <h3 class="text-2xl font-bold text-red-600"><?php echo number_format($stats['open']); ?></h3>
                </div>
                <i class="fas fa-exclamation-circle text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Urgent</p>
                    <h3 class="text-2xl font-bold text-red-600"><?php echo number_format($stats['urgent']); ?></h3>
                </div>
                <i class="fas fa-exclamation-triangle text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">High Priority</p>
                    <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format($stats['high']); ?></h3>
                </div>
                <i class="fas fa-flag text-yellow-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Answered</p>
                    <h3 class="text-2xl font-bold text-green-600"><?php echo number_format($stats['answered']); ?></h3>
                </div>
                <i class="fas fa-check-circle text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Closed</p>
                    <h3 class="text-2xl font-bold text-gray-600"><?php echo number_format($stats['closed']); ?></h3>
                </div>
                <i class="fas fa-archive text-gray-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <div class="flex flex-wrap gap-4 items-center">
            <div class="flex space-x-2">
                <a href="?status=open" class="px-4 py-2 rounded-lg <?php echo $status == 'open' ? 'bg-red-100 text-red-800' : 'bg-gray-100'; ?>">
                    Open (<?php echo $stats['open']; ?>)
                </a>
                <a href="?status=answered" class="px-4 py-2 rounded-lg <?php echo $status == 'answered' ? 'bg-green-100 text-green-800' : 'bg-gray-100'; ?>">
                    Answered (<?php echo $stats['answered']; ?>)
                </a>
                <a href="?status=closed" class="px-4 py-2 rounded-lg <?php echo $status == 'closed' ? 'bg-gray-100 text-gray-800' : 'bg-gray-100'; ?>">
                    Closed (<?php echo $stats['closed']; ?>)
                </a>
                <a href="?status=all" class="px-4 py-2 rounded-lg <?php echo $status == 'all' ? 'bg-purple-100 text-purple-800' : 'bg-gray-100'; ?>">
                    All Tickets
                </a>
            </div>
            
            <div class="flex-1">
                <form method="GET" class="flex gap-2">
                    <input type="text" name="user_id" value="<?php echo $_GET['user_id'] ?? ''; ?>"
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Filter by User ID">
                    <select name="category" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo $cat['category']; ?>" <?php echo ($_GET['category'] ?? '') == $cat['category'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst($cat['category']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="bg-gray-800 text-white px-4 py-2 rounded-lg hover:bg-gray-900">
                        <i class="fas fa-search"></i>
                    </button>
                </form>
            </div>
            
            <div>
                <button onclick="exportTickets()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-download mr-2"></i>Export
                </button>
            </div>
        </div>
    </div>

    <!-- Tickets Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Ticket ID</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Subject</th>
                        <th class="p-4 text-left">Category</th>
                        <th class="p-4 text-left">Priority</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Created</th>
                        <th class="p-4 text-left">Last Update</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($tickets) > 0): ?>
                        <?php foreach ($tickets as $ticket): 
                            $priority_colors = [
                                'urgent' => 'bg-red-100 text-red-800',
                                'high' => 'bg-yellow-100 text-yellow-800',
                                'medium' => 'bg-blue-100 text-blue-800',
                                'low' => 'bg-gray-100 text-gray-800'
                            ];
                            $status_colors = [
                                'open' => 'bg-red-100 text-red-800',
                                'answered' => 'bg-green-100 text-green-800',
                                'closed' => 'bg-gray-100 text-gray-800',
                                'resolved' => 'bg-blue-100 text-blue-800'
                            ];
                            $category_colors = [
                                'deposit' => 'bg-green-100 text-green-800',
                                'withdrawal' => 'bg-red-100 text-red-800',
                                'investment' => 'bg-blue-100 text-blue-800',
                                'account' => 'bg-purple-100 text-purple-800',
                                'technical' => 'bg-yellow-100 text-yellow-800',
                                'general' => 'bg-gray-100 text-gray-800'
                            ];
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Ticket ID -->
                            <td class="p-4">
                                <p class="font-mono text-sm"><?php echo $ticket['ticket_id']; ?></p>
                                <p class="text-xs text-gray-500">ID: <?php echo $ticket['id']; ?></p>
                            </td>
                            
                            <!-- User -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($ticket['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($ticket['email']); ?></p>
                                <p class="text-xs <?php echo $ticket['account_status'] == 'active' ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo ucfirst($ticket['account_status']); ?>
                                </p>
                            </td>
                            
                            <!-- Subject -->
                            <td class="p-4">
                                <p class="font-medium truncate max-w-xs"><?php echo htmlspecialchars($ticket['subject']); ?></p>
                                <p class="text-xs text-gray-500 truncate max-w-xs"><?php echo substr(htmlspecialchars($ticket['message']), 0, 50); ?>...</p>
                            </td>
                            
                            <!-- Category -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $category_colors[$ticket['category']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($ticket['category']); ?>
                                </span>
                            </td>
                            
                            <!-- Priority -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $priority_colors[$ticket['priority']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($ticket['priority']); ?>
                                </span>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $status_colors[$ticket['status']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($ticket['status']); ?>
                                </span>
                            </td>
                            
                            <!-- Created -->
                            <td class="p-4">
                                <p><?php echo date('M d', strtotime($ticket['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i', strtotime($ticket['created_at'])); ?></p>
                            </td>
                            
                            <!-- Last Update -->
                            <td class="p-4">
                                <p><?php echo date('M d', strtotime($ticket['updated_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i', strtotime($ticket['updated_at'])); ?></p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <a href="ticket-view.php?id=<?php echo $ticket['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View & Reply
                                    </a>
                                    
                                    <?php if ($ticket['status'] != 'closed'): ?>
                                    <a href="?action=close&id=<?php echo $ticket['id']; ?>" 
                                       onclick="return confirm('Close this ticket?')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-times mr-1"></i> Close
                                    </a>
                                    <?php endif; ?>
                                    
                                    <a href="?action=delete&id=<?php echo $ticket['id']; ?>" 
                                       onclick="return confirm('Delete this ticket?')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="p-8 text-center text-gray-500">
                                <i class="fas fa-inbox text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No support tickets found</p>
                                <?php if ($status != 'all'): ?>
                                <p class="text-sm mt-2">Try viewing <a href="?status=all" class="text-purple-600">all tickets</a></p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_tickets); ?> of <?php echo number_format($total_tickets); ?> tickets
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['category']) ? '&category=' . $_GET['category'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['category']) ? '&category=' . $_GET['category'] : ''; ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $status; ?><?php echo isset($_GET['user_id']) ? '&user_id=' . $_GET['user_id'] : ''; ?><?php echo isset($_GET['category']) ? '&category=' . $_GET['category'] : ''; ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Quick Stats -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
        <!-- Response Time -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Response Time Stats</h4>
            <?php
            $response_stmt = $db->prepare("
                SELECT 
                    AVG(TIMESTAMPDIFF(HOUR, created_at, replied_at)) as avg_hours,
                    MAX(TIMESTAMPDIFF(HOUR, created_at, replied_at)) as max_hours,
                    COUNT(*) as responded
                FROM support_tickets 
                WHERE status IN ('answered', 'closed') 
                AND replied_at IS NOT NULL
            ");
            $response_stmt->execute();
            $response_stats = $response_stmt->fetch();
            ?>
            <div class="space-y-3">
                <div class="flex justify-between">
                    <span>Average Response:</span>
                    <span class="font-bold"><?php echo number_format($response_stats['avg_hours'] ?? 0, 1); ?> hours</span>
                </div>
                <div class="flex justify-between">
                    <span>Max Response:</span>
                    <span class="font-bold"><?php echo number_format($response_stats['max_hours'] ?? 0, 1); ?> hours</span>
                </div>
                <div class="flex justify-between">
                    <span>Tickets Responded:</span>
                    <span class="font-bold"><?php echo number_format($response_stats['responded'] ?? 0); ?></span>
                </div>
            </div>
        </div>
        
        <!-- Category Distribution -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Tickets by Category</h4>
            <?php
            $category_stmt = $db->query("
                SELECT category, COUNT(*) as count 
                FROM support_tickets 
                WHERE status = 'open' 
                GROUP BY category 
                ORDER BY count DESC
            ");
            $category_stats = $category_stmt->fetchAll();
            ?>
            <div class="space-y-2">
                <?php foreach ($category_stats as $stat): ?>
                <div class="flex justify-between items-center">
                    <span class="capitalize"><?php echo $stat['category']; ?></span>
                    <span class="font-bold"><?php echo $stat['count']; ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Bulk Actions -->
        <div class="bg-white rounded-xl shadow p-6">
            <h4 class="text-lg font-bold mb-4">Bulk Actions</h4>
            <div class="space-y-3">
                <button onclick="bulkClose()" class="w-full bg-red-600 text-white py-2 rounded-lg hover:bg-red-700">
                    <i class="fas fa-times-circle mr-2"></i>Close All Open Tickets
                </button>
                <button onclick="exportFiltered()" class="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                    <i class="fas fa-file-export mr-2"></i>Export Filtered Tickets
                </button>
                <button onclick="sendBulkReply()" class="w-full bg-green-600 text-white py-2 rounded-lg hover:bg-green-700">
                    <i class="fas fa-reply-all mr-2"></i>Send Bulk Reply
                </button>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
function exportTickets() {
    const params = new URLSearchParams(window.location.search);
    window.open(../api/export-tickets.php?${params.toString()}, '_blank');
}

function exportFiltered() {
    exportTickets();
}

function bulkClose() {
    if (confirm('Close ALL open tickets? This action cannot be undone.')) {
        jQuery.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'bulk_close_tickets',
                status: '<?php echo $status; ?>'
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

function sendBulkReply() {
    const message = prompt('Enter reply message for all open tickets:');
    if (message && message.trim()) {
        if (confirm('Send this reply to all open tickets?')) {
            jQuery.ajax({
                url: '../api/admin-actions.php',
                method: 'POST',
                data: {
                    action: 'bulk_reply_tickets',
                    message: message.trim()
                },
                success: function(response) {
                    const result = JSON.parse(response);
                    showNotification(result.message, result.success ? 'success' : 'error');
                    if (result.success) location.reload();
                }
            });
        }
    }
}

// Quick actions
function quickTicketAction(ticketId, action) {
    if (confirm(`${action.charAt(0).toUpperCase() + action.slice(1)} this ticket?`)) {
        window.location.href = `?action=${action}&id=${ticketId}`;
    }
}

// Expose functions to global scope for onclick events
window.exportTickets = exportTickets;
window.exportFiltered = exportFiltered;
window.bulkClose = bulkClose;
window.sendBulkReply = sendBulkReply;
window.quickTicketAction = quickTicketAction;
});
</script>

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