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

// Check if user is logged in and is admin or agent
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 filter parameters with validation
$allowed_statuses = ['All', 'New', 'In Review', 'Resolved', 'Closed'];
$status_filter = isset($_GET['status']) && in_array($_GET['status'], $allowed_statuses) ? $_GET['status'] : 'All';

$type_filter = 'All';
if (isset($_GET['type'])) {
    // Validate type is numeric
    if (is_numeric($_GET['type'])) {
        $type_filter = (int)$_GET['type'];
        // Verify type exists
        $stmt = $pdo->prepare("SELECT id FROM ticket_types WHERE id = ?");
        $stmt->execute([$type_filter]);
        if (!$stmt->fetch()) {
            $type_filter = 'All';
        }
    }
}

// Get ticket types for filter
$ticket_types = getTicketTypes($pdo);

// Get tickets (assigned to this agent or all for admin)
$tickets = getAllTickets($pdo, $status_filter, $type_filter);

// Get statistics
$stats = getTicketStats($pdo);
?>

<div class="container">
    <div class="admin-header">
        <h2>Support Agent Dashboard</h2>
    </div>
    
    <div class="dashboard-stats">
        <div class="stat-card">
            <h3>Total Tickets</h3>
            <div class="stat-value"><?php echo $stats['total_tickets']; ?></div>
        </div>
        
        <div class="stat-card">
            <h3>Avg. Resolution Time</h3>
            <div class="stat-value"><?php echo $stats['avg_resolution_time']; ?> hrs</div>
        </div>
        
        <div class="stat-card">
            <h3>Open Tickets</h3>
            <div class="stat-value">
                <?php 
                $open_count = 0;
                foreach ($stats['by_status'] as $status) {
                    if ($status['status'] === 'New' || $status['status'] === 'In Review') {
                        $open_count += $status['count'];
                    }
                }
                echo $open_count;
                ?>
            </div>
        </div>
        
        <div class="stat-card">
            <h3>Closed Tickets</h3>
            <div class="stat-value">
                <?php 
                $closed_count = 0;
                foreach ($stats['by_status'] as $status) {
                    if ($status['status'] === 'Resolved' || $status['status'] === 'Closed') {
                        $closed_count += $status['count'];
                    }
                }
                echo $closed_count;
                ?>
            </div>
        </div>
    </div>
    
    <div class="filters">
        <form method="GET" action="" class="filter-form">
            <div class="filter-row">
                <div class="filter-group">
                    <label for="status">Status</label>
                    <select id="status" name="status">
                        <option value="All" <?php echo $status_filter === 'All' ? 'selected' : ''; ?>>All Statuses</option>
                        <option value="New" <?php echo $status_filter === 'New' ? 'selected' : ''; ?>>New</option>
                        <option value="In Review" <?php echo $status_filter === 'In Review' ? 'selected' : ''; ?>>In Review</option>
                        <option value="Resolved" <?php echo $status_filter === 'Resolved' ? 'selected' : ''; ?>>Resolved</option>
                        <option value="Closed" <?php echo $status_filter === 'Closed' ? 'selected' : ''; ?>>Closed</option>
                    </select>
                </div>
                
                <div class="filter-group">
                    <label for="type">Ticket Type</label>
                    <select id="type" name="type">
                        <option value="All" <?php echo $type_filter === 'All' ? 'selected' : ''; ?>>All Types</option>
                        <?php foreach ($ticket_types as $type): ?>
                            <option value="<?php echo $type['id']; ?>" <?php echo $type_filter == $type['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($type['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="filter-buttons">
                    <button type="submit" class="btn btn-primary">Filter</button>
                    <a href="<?php echo SITE_URL; ?>/tickets/agent_dashboard.php" class="btn btn-outline">Clear</a>
                </div>
            </div>
        </form>
    </div>
    
    <div class="section-title">
        <h2>Tickets</h2>
    </div>
    
    <?php if (empty($tickets)): ?>
        <div class="empty-products">
            <i class="fas fa-ticket-alt"></i>
            <h3>No Tickets Found</h3>
            <p>No tickets match your current filter criteria.</p>
        </div>
    <?php else: ?>
        <div class="cart-table">
            <table>
                <thead>
                    <tr>
                        <th>Ticket ID</th>
                        <th>Customer</th>
                        <th>Type</th>
                        <th>Subject</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($tickets as $ticket): ?>
                        <tr>
                            <td>#<?php echo $ticket['id']; ?></td>
                            <td><?php echo htmlspecialchars($ticket['customer_name']); ?></td>
                            <td><?php echo htmlspecialchars($ticket['type_name']); ?></td>
                            <td><?php echo htmlspecialchars($ticket['subject']); ?></td>
                            <td>
                                <span class="status-<?php echo strtolower(str_replace(' ', '-', $ticket['status'])); ?>">
                                    <?php echo $ticket['status']; ?>
                                </span>
                            </td>
                            <td><?php echo $ticket['priority']; ?></td>
                            <td><?php echo date('M j, Y', strtotime($ticket['created_at'])); ?></td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>/tickets/agent_view.php?id=<?php echo $ticket['id']; ?>" class="btn btn-outline">View</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<style>
.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'; ?>