<?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 {
    $action = isset($_GET['action']) ? $_GET['action'] : 'get';
    
    if ($action === 'get') {
        // Get unread notifications for admin
        $admin_id = $_SESSION['user_id'];
        
        $stmt = $connection->prepare("
            SELECT 
                id,
                type,
                message,
                consultation_id,
                status,
                created_at
            FROM notifications
            WHERE admin_id = ? AND status = 'unread'
            ORDER BY created_at DESC
            LIMIT 20
        ");
        
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $connection->error);
        }
        
        $stmt->bind_param("i", $admin_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $notifications = [];
        $unread_count = 0;
        
        while ($row = $result->fetch_assoc()) {
            $unread_count++;
            $notifications[] = [
                'id' => (int)$row['id'],
                'type' => $row['type'],
                'message' => htmlspecialchars($row['message']),
                'consultation_id' => (int)$row['consultation_id'],
                'status' => $row['status'],
                'created_at' => $row['created_at'],
                'time_ago' => getTimeAgo($row['created_at'])
            ];
        }
        
        echo json_encode([
            'success' => true,
            'notifications' => $notifications,
            'unread_count' => $unread_count,
            'timestamp' => date('Y-m-d H:i:s')
        ]);
        
    } elseif ($action === 'mark_read') {
        // Mark notification as read
        $notification_id = isset($_POST['notification_id']) ? intval($_POST['notification_id']) : 0;
        
        if ($notification_id <= 0) {
            throw new Exception('Invalid notification ID');
        }
        
        $admin_id = $_SESSION['user_id'];
        
        $stmt = $connection->prepare("
            UPDATE notifications 
            SET status = 'read' 
            WHERE id = ? AND admin_id = ?
        ");
        
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $connection->error);
        }
        
        $stmt->bind_param("ii", $notification_id, $admin_id);
        $stmt->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'Notification marked as read'
        ]);
        
    } elseif ($action === 'mark_all_read') {
        // Mark all notifications as read
        $admin_id = $_SESSION['user_id'];
        
        $stmt = $connection->prepare("
            UPDATE notifications 
            SET status = 'read' 
            WHERE admin_id = ? AND status = 'unread'
        ");
        
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $connection->error);
        }
        
        $stmt->bind_param("i", $admin_id);
        $stmt->execute();
        
        echo json_encode([
            'success' => true,
            'message' => 'All notifications marked as read'
        ]);
    }
    
} catch (Exception $e) {
    error_log('get-admin-notifications.php error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
} finally {
    if (isset($connection)) {
        $connection->close();
    }
}

function getTimeAgo($timestamp) {
    $now = new DateTime();
    $time = new DateTime($timestamp);
    $interval = $now->diff($time);
    
    if ($interval->y > 0) return $interval->y . "y ago";
    if ($interval->m > 0) return $interval->m . "m ago";
    if ($interval->d > 0) return $interval->d . "d ago";
    if ($interval->h > 0) return $interval->h . "h ago";
    if ($interval->i > 0) return $interval->i . "m ago";
    return "just now";
}
?>
