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

// Check if user is logged in and is admin
if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/index.php');
}

require_once '../includes/ticket_functions.php';

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

// Get recent tickets
$recent_tickets = getRecentTickets($pdo, 10);

// Get ticket types for charts
$ticket_types = getTicketTypes($pdo);
?>

<div class="container">
    <div class="admin-header">
        <h2>Ticket Analytics 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>Satisfaction Rate</h3>
            <div class="stat-value">
                <?php 
                // Calculate satisfaction rate from resolved tickets with ratings
                $stmt = $pdo->query("SELECT COUNT(*) as total, AVG(satisfaction_rating) as avg_rating FROM tickets WHERE satisfaction_rating IS NOT NULL");
                $satisfaction = $stmt->fetch(PDO::FETCH_ASSOC);
                echo $satisfaction['total'] > 0 ? round($satisfaction['avg_rating'] * 20, 1) . '%' : 'N/A';
                ?>
            </div>
        </div>
    </div>
    
    <div class="section-title">
        <h2>Ticket Distribution</h2>
    </div>
    
    <div class="dashboard-charts">
        <div class="chart-container">
            <h3>By Status</h3>
            <div class="chart-bars">
                <?php foreach ($stats['by_status'] as $status): ?>
                    <div class="chart-bar">
                        <div class="bar-label"><?php echo $status['status']; ?></div>
                        <div class="bar-container">
                            <div class="bar" style="width: <?php echo $stats['total_tickets'] > 0 ? ($status['count'] / $stats['total_tickets'] * 100) : 0; ?>%;">
                                <?php echo $status['count']; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="chart-container">
            <h3>By Type</h3>
            <div class="chart-bars">
                <?php foreach ($stats['by_type'] as $type): ?>
                    <div class="chart-bar">
                        <div class="bar-label"><?php echo htmlspecialchars($type['name']); ?></div>
                        <div class="bar-container">
                            <div class="bar" style="width: <?php echo $stats['total_tickets'] > 0 ? ($type['count'] / $stats['total_tickets'] * 100) : 0; ?>%;">
                                <?php echo $type['count']; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <div class="section-title">
        <h2>Recent Tickets</h2>
    </div>
    
    <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 if (empty($recent_tickets)): ?>
                    <tr>
                        <td colspan="8" class="text-center">No tickets found</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($recent_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; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <div class="admin-nav">
        <ul>
            <li><a href="<?php echo SITE_URL; ?>/admin/index.php" class="btn btn-outline">← Back to Admin Dashboard</a></li>
            <li><a href="<?php echo SITE_URL; ?>/tickets/agent_dashboard.php" class="btn btn-primary">Support Agent Dashboard</a></li>
        </ul>
    </div>
</div>

<style>
.dashboard-charts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 30px;
    margin-bottom: 30px;
}

.chart-container {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.chart-container h3 {
    margin-bottom: 20px;
    color: #2c3e50;
}

.chart-bars {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.chart-bar {
    display: flex;
    align-items: center;
}

.bar-label {
    width: 120px;
    font-size: 0.9rem;
    color: #7f8c8d;
}

.bar-container {
    flex: 1;
    background: #ecf0f1;
    border-radius: 4px;
    height: 24px;
    overflow: hidden;
}

.bar {
    background: linear-gradient(90deg, #3498db, #2c3e50);
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding-right: 10px;
    color: white;
    font-size: 0.8rem;
    font-weight: bold;
    border-radius: 4px;
}

.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; }

.text-center {
    text-align: center;
}
</style>

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