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

// Get ticket stats
$sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) as open,
    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
    SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
    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,
    SUM(CASE WHEN priority = 'medium' THEN 1 ELSE 0 END) as medium,
    SUM(CASE WHEN priority = 'low' THEN 1 ELSE 0 END) as low,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_today
    FROM support_tickets";

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

// Get tickets created in last 30 minutes for "new tickets" notification
$thirty_minutes_ago = date('Y-m-d H:i:s', strtotime('-30 minutes'));
$new_sql = "SELECT COUNT(*) as new_tickets FROM support_tickets WHERE created_at >= '$thirty_minutes_ago'";
$new_result = mysqli_query($conn, $new_sql);
$new_row = mysqli_fetch_assoc($new_result);
$new_tickets = $new_row['new_tickets'];

echo json_encode(array(
    'success' => true,
    'total' => $stats['total'] ?: 0,
    'open' => $stats['open'] ?: 0,
    'in_progress' => $stats['in_progress'] ?: 0,
    'resolved' => $stats['resolved'] ?: 0,
    'closed' => $stats['closed'] ?: 0,
    'urgent' => $stats['urgent'] ?: 0,
    'high' => $stats['high'] ?: 0,
    'medium' => $stats['medium'] ?: 0,
    'low' => $stats['low'] ?: 0,
    'new_today' => $stats['new_today'] ?: 0,
    'new_tickets' => $new_tickets
));
?>