<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Admin access required']);
    exit;
}

require_once '../config/db.php';

if (!isset($connection)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

try {
    // Get last check time from request (for polling)
    $last_check = isset($_GET['last_check']) ? $_GET['last_check'] : date('Y-m-d H:i:s', strtotime('-5 minutes'));
    
    // Get pending consultations and recently updated ones
    $stmt = $connection->prepare("
        SELECT 
            id, 
            CONCAT(first_name, ' ', last_name) as name,
            email, 
            phone,
            consultation_type, 
            preferred_date, 
            budget_range,
            status, 
            created_at, 
            updated_at,
            CASE 
                WHEN status = 'pending' THEN 'new'
                WHEN updated_at > ? THEN 'updated'
                ELSE 'existing'
            END as notification_type
        FROM consultations
        WHERE status = 'pending' OR updated_at > ?
        ORDER BY created_at DESC
        LIMIT 50
    ");
    
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . $connection->error);
    }
    
    $stmt->bind_param("ss", $last_check, $last_check);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $consultations = [];
    $new_count = 0;
    $updated_count = 0;
    
    while ($row = $result->fetch_assoc()) {
        if ($row['notification_type'] === 'new') {
            $new_count++;
        } elseif ($row['notification_type'] === 'updated') {
            $updated_count++;
        }
        
        $consultations[] = [
            'id' => (int)$row['id'],
            'name' => htmlspecialchars($row['name']),
            'email' => htmlspecialchars($row['email']),
            'phone' => htmlspecialchars($row['phone']),
            'consultation_type' => $row['consultation_type'],
            'preferred_date' => $row['preferred_date'],
            'budget_range' => $row['budget_range'],
            'status' => $row['status'],
            'created_at' => $row['created_at'],
            'updated_at' => $row['updated_at'],
            'notification_type' => $row['notification_type']
        ];
    }
    
    echo json_encode([
        'success' => true,
        'consultations' => $consultations,
        'new_count' => $new_count,
        'updated_count' => $updated_count,
        'total_count' => count($consultations),
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log('get-new-consultations.php error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching consultations'
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}
?>
