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

// Check if there are new notifications since last check
$last_check = isset($_SESSION['last_notification_check']) ? $_SESSION['last_notification_check'] : date('Y-m-d H:i:s', strtotime('-1 hour'));

// Check for pending deposits
$deposit_sql = "SELECT COUNT(*) as count FROM deposits WHERE status = 'pending' AND created_at > '$last_check'";
$deposit_result = mysqli_query($conn, $deposit_sql);
$deposit_row = mysqli_fetch_assoc($deposit_result);

// Check for pending withdrawals
$withdrawal_sql = "SELECT COUNT(*) as count FROM withdrawals WHERE status = 'pending' AND created_at > '$last_check'";
$withdrawal_result = mysqli_query($conn, $withdrawal_sql);
$withdrawal_row = mysqli_fetch_assoc($withdrawal_result);

// Check for new support tickets
$ticket_sql = "SELECT COUNT(*) as count FROM support_tickets WHERE status = 'open' AND created_at > '$last_check'";
$ticket_result = mysqli_query($conn, $ticket_sql);
$ticket_row = mysqli_fetch_assoc($ticket_result);

// Check for new admin activities
$activity_sql = "SELECT COUNT(*) as count FROM admin_activities WHERE created_at > '$last_check'";
$activity_result = mysqli_query($conn, $activity_sql);
$activity_row = mysqli_fetch_assoc($activity_result);

$has_new = false;
$title = '';
$message = '';
$type = 'info';
$link = '';

if ($deposit_row['count'] > 0) {
    $has_new = true;
    $title = 'New Deposit Request';
    $message = $deposit_row['count'] . ' new deposit(s) pending approval';
    $type = 'success';
    $link = 'pending_deposits.php';
} elseif ($withdrawal_row['count'] > 0) {
    $has_new = true;
    $title = 'New Withdrawal Request';
    $message = $withdrawal_row['count'] . ' new withdrawal(s) pending approval';
    $type = 'warning';
    $link = 'pending_withdrawals.php';
} elseif ($ticket_row['count'] > 0) {
    $has_new = true;
    $title = 'New Support Ticket';
    $message = $ticket_row['count'] . ' new support ticket(s) received';
    $type = 'info';
    $link = 'support_tickets.php';
} elseif ($activity_row['count'] > 0) {
    $has_new = true;
    $title = 'System Activity';
    $message = $activity_row['count'] . ' new system activities';
    $type = 'info';
    $link = 'admin_activities.php';
}

// Update last check time
$_SESSION['last_notification_check'] = date('Y-m-d H:i:s');

echo json_encode(array(
    'has_new' => $has_new,
    'title' => $title,
    'message' => $message,
    'type' => $type,
    'link' => $link
));
?>