<?php
/**
 * Test Notification Script
 * Manually test push notifications for a specific user
 * 
 * Usage: php cron/test_notifications.php [user_id]
 */

// Set timezone to IST
date_default_timezone_set('Asia/Kolkata');

// Load configuration and autoloader
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/autoload.php';

echo "\n" . str_repeat('=', 80) . "\n";
echo "Push Notification Test Script\n";
echo "Date/Time: " . date('Y-m-d H:i:s') . " IST\n";
echo str_repeat('=', 80) . "\n\n";

try {
    // Get user ID from command line argument
    $userId = isset($argv[1]) ? (int)$argv[1] : null;
    
    if (!$userId) {
        echo "Usage: php cron/test_notifications.php [user_id]\n";
        echo "\nAvailable users:\n";
        
        // List all users
        $userModel = new User();
        $users = $userModel->getAll();
        
        foreach ($users as $user) {
            echo "  - ID: {$user['id']}, Username: {$user['username']}, Email: {$user['email']}\n";
        }
        
        exit(1);
    }
    
    // Create notification service
    $notificationService = new NotificationService();
    
    // Check service status
    $status = $notificationService->getStatus();
    echo "Service Status:\n";
    echo "  - VAPID Configured: " . ($status['vapid_configured'] ? 'Yes' : 'No') . "\n";
    echo "  - Service Available: " . ($status['service_available'] ? 'Yes' : 'No') . "\n";
    echo "  - Total Subscriptions: " . $status['total_subscriptions'] . "\n\n";
    
    if (!$status['vapid_configured'] || !$status['service_available']) {
        throw new Exception('Notification service not properly configured');
    }
    
    // Get user info
    $userModel = new User();
    $user = $userModel->findById($userId);
    
    if (!$user) {
        throw new Exception("User with ID {$userId} not found");
    }
    
    echo "Testing notifications for user:\n";
    echo "  - ID: {$user->id}\n";
    echo "  - Username: {$user->username}\n";
    echo "  - Email: {$user->email}\n\n";
    
    // Check if user has subscriptions
    $subscriptionModel = new NotificationSubscription();
    $subscriptions = $subscriptionModel->getByUser($userId);
    
    if (empty($subscriptions)) {
        echo "ERROR: User has no active push notification subscriptions.\n";
        echo "Please enable notifications in the PWA first.\n";
        exit(1);
    }
    
    echo "Found " . count($subscriptions) . " subscription(s) for this user.\n\n";
    
    // Generate payload
    echo "Generating notification payload...\n";
    $payload = $notificationService->generateNotificationPayload($userId);
    
    if ($payload === null) {
        echo "No reminders found for today. Sending test notification instead...\n\n";
        
        // Send test notification
        $success = $notificationService->sendTestNotification(
            $userId,
            "Test notification sent at " . date('H:i:s') . " IST"
        );
        
        if ($success) {
            echo "✓ Test notification sent successfully!\n";
        } else {
            echo "✗ Failed to send test notification.\n";
        }
    } else {
        echo "Payload generated:\n";
        echo "  - Title: {$payload['title']}\n";
        echo "  - Body: {$payload['body']}\n";
        echo "  - Birthdays: {$payload['data']['birthdayCount']}\n";
        echo "  - Reminders: {$payload['data']['reminderCount']}\n\n";
        
        // Send notification to all subscriptions
        echo "Sending notifications...\n";
        $sent = 0;
        $failed = 0;
        
        foreach ($subscriptions as $subscription) {
            $success = $notificationService->sendPushNotification($subscription, $payload);
            if ($success) {
                $sent++;
                echo "  ✓ Sent to subscription " . substr($subscription['endpoint'], -20) . "\n";
            } else {
                $failed++;
                echo "  ✗ Failed to send to subscription " . substr($subscription['endpoint'], -20) . "\n";
            }
        }
        
        echo "\nResults:\n";
        echo "  - Sent: {$sent}\n";
        echo "  - Failed: {$failed}\n";
    }
    
    echo "\n" . str_repeat('=', 80) . "\n";
    echo "Test Completed\n";
    echo str_repeat('=', 80) . "\n";
    
    exit(0);
    
} catch (Exception $e) {
    echo "\nERROR: " . $e->getMessage() . "\n";
    echo "Stack trace: " . $e->getTraceAsString() . "\n";
    exit(1);
}
