<?php
session_start();
include('../includes/config.php');

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_priority = isset($_GET['priority']) ? $_GET['priority'] : '';
$filter_category = isset($_GET['category']) ? $_GET['category'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$assigned_to = isset($_GET['assigned_to']) ? intval($_GET['assigned_to']) : 0;

// Build query (same as main page)
$sql = "SELECT t.*, u.username, u.email, a.name as assigned_admin 
        FROM support_tickets t 
        LEFT JOIN users u ON t.user_id = u.id 
        LEFT JOIN admins a ON t.assigned_to = a.id 
        WHERE 1=1";

if ($filter_status) {
    $sql .= " AND t.status = '$filter_status'";
}

if ($filter_priority) {
    $sql .= " AND t.priority = '$filter_priority'";
}

if ($filter_category) {
    $sql .= " AND t.category = '$filter_category'";
}

if ($search) {
    $sql .= " AND (t.ticket_number LIKE '%$search%' OR t.subject LIKE '%$search%' OR u.username LIKE '%$search%' OR u.email LIKE '%$search%')";
}

if ($assigned_to > 0) {
    $sql .= " AND t.assigned_to = $assigned_to";
}

$sql .= " ORDER BY 
    CASE WHEN t.status = 'open' THEN 1 
         WHEN t.status = 'in_progress' THEN 2
         WHEN t.status = 'resolved' THEN 3
         ELSE 4 END,
    CASE WHEN t.priority = 'urgent' THEN 1
         WHEN t.priority = 'high' THEN 2
         WHEN t.priority = 'medium' THEN 3
         ELSE 4 END,
    t.created_at DESC
    LIMIT 100";

$result = mysqli_query($conn, $sql);

// Status colors
$status_colors = array(
    'open' => 'danger',
    'in_progress' => 'warning',
    'resolved' => 'success',
    'closed' => 'secondary'
);

// Priority colors
$priority_colors = array(
    'urgent' => 'danger',
    'high' => 'warning',
    'medium' => 'info',
    'low' => 'success'
);

if (mysqli_num_rows($result) > 0) {
    while ($ticket = mysqli_fetch_assoc($result)) {
        $status_color = isset($status_colors[$ticket['status']]) ? $status_colors[$ticket['status']] : 'secondary';
        $priority_color = isset($priority_colors[$ticket['priority']]) ? $priority_colors[$ticket['priority']] : 'secondary';
        $created_date = date('M d, Y', strtotime($ticket['created_at']));
        $updated_date = $ticket['updated_at'] ? date('M d, Y', strtotime($ticket['updated_at'])) : '-';
        
        echo '<tr>';
        echo '<td><strong>' . $ticket['ticket_number'] . '</strong></td>';
        echo '<td>';
        echo '<p class="mb-0 fw-500">' . htmlspecialchars($ticket['subject']) . '</p>';
        echo '<small class="text-mute">' . substr($ticket['description'], 0, 50) . '...</small>';
        echo '</td>';
        echo '<td>';
        echo '<p class="mb-0">' . htmlspecialchars($ticket['username']) . '</p>';
        echo '<small class="text-mute">' . htmlspecialchars($ticket['email']) . '</small>';
        echo '</td>';
        echo '<td>';
        echo '<span class="badge bg-secondary">';
        echo ucfirst(str_replace('_', ' ', $ticket['category']));
        echo '</span>';
        echo '</td>';
        echo '<td>';
        echo '<span class="badge bg-' . $priority_color . '">';
        echo ucfirst($ticket['priority']);
        echo '</span>';
        echo '</td>';
        echo '<td>';
        echo '<span class="badge bg-' . $status_color . '">';
        echo ucfirst(str_replace('_', ' ', $ticket['status']));
        echo '</span>';
        echo '</td>';
        echo '<td>';
        if ($ticket['assigned_admin']) {
            echo '<p class="mb-0">' . $ticket['assigned_admin'] . '</p>';
            echo '<small class="text-mute">Assigned</small>';
        } else {
            echo '<span class="badge bg-light text-dark">Unassigned</span>';
        }
        echo '</td>';
        echo '<td>';
        echo '<p class="mb-0">' . $created_date . '</p>';
        echo '<small class="text-mute">' . time_ago($ticket['created_at']) . ' ago</small>';
        echo '</td>';
        echo '<td>';
        echo '<p class="mb-0">' . $updated_date . '</p>';
        echo '<small class="text-mute">Updated</small>';
        echo '</td>';
        echo '<td>';
        echo '<div class="btn-group">';
        echo '<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">';
        echo '<i class="fas fa-cog"></i>';
        echo '</button>';
        echo '<div class="dropdown-menu">';
        echo '<a class="dropdown-item view-ticket" href="#" data-bs-toggle="modal" data-bs-target="#viewTicketModal" data-ticket-id="' . $ticket['id'] . '">';
        echo '<i class="fas fa-eye me-2"></i> View Details';
        echo '</a>';
        echo '<a class="dropdown-item reply-ticket" href="#" data-bs-toggle="modal" data-bs-target="#replyModal" data-ticket-id="' . $ticket['id'] . '">';
        echo '<i class="fas fa-reply me-2"></i> Reply';
        echo '</a>';
        echo '<a class="dropdown-item update-ticket" href="#" data-bs-toggle="modal" data-bs-target="#updateTicketModal" data-ticket-id="' . $ticket['id'] . '" data-current-status="' . $ticket['status'] . '" data-current-priority="' . $ticket['priority'] . '">';
        echo '<i class="fas fa-edit me-2"></i> Update Status';
        echo '</a>';
        echo '<div class="dropdown-divider"></div>';
        echo '<a class="dropdown-item text-danger delete-ticket" href="#" onclick="confirmDelete(' . $ticket['id'] . ')">';
        echo '<i class="fas fa-trash me-2"></i> Delete';
        echo '</a>';
        echo '</div>';
        echo '</div>';
        echo '</td>';
        echo '</tr>';
    }
} else {
    echo '<tr>';
    echo '<td colspan="10" class="text-center py-20">';
    echo '<i class="fas fa-ticket-alt fa-2x text-mute mb-3"></i>';
    echo '<h5>No tickets found</h5>';
    echo '<p class="text-mute">Try adjusting your search or filters</p>';
    echo '</td>';
    echo '</tr>';
}

function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>