<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once '../config/database.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }
    
    // Validate required fields
    $required_fields = ['title', 'body'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            throw new Exception("Field '$field' is required");
        }
    }
    
    $pdo = getDBConnection();
    
    // Handle different notification types
    $target_type = $input['target_type'] ?? 'single';
    $user_ids = $input['user_ids'] ?? [];
    $device_tokens = $input['device_tokens'] ?? [];
    
    $notifications_to_send = [];
    
    if ($target_type === 'all') {
        // Send to all users with device tokens
        $stmt = $pdo->query("SELECT id, device_token FROM users WHERE device_token IS NOT NULL AND device_token != ''");
        $notifications_to_send = $stmt->fetchAll();
    } elseif ($target_type === 'specific' && !empty($user_ids)) {
        // Send to specific users
        $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
        $stmt = $pdo->prepare("SELECT id, device_token FROM users WHERE id IN ($placeholders) AND device_token IS NOT NULL AND device_token != ''");
        $stmt->execute($user_ids);
        $notifications_to_send = $stmt->fetchAll();
    } elseif (!empty($device_tokens)) {
        // Send to specific device tokens
        foreach ($device_tokens as $token) {
            $notifications_to_send[] = ['id' => null, 'device_token' => $token];
        }
    } elseif (isset($input['token'])) {
        // Single device token (backward compatibility)
        $notifications_to_send[] = ['id' => null, 'device_token' => $input['token']];
    } else {
        throw new Exception('No valid target specified. Provide user_ids, device_tokens, or token.');
    }
    
    if (empty($notifications_to_send)) {
        throw new Exception('No valid targets found for notification');
    }
    
    $success_count = 0;
    $failed_count = 0;
    $results = [];
    
            foreach ($notifications_to_send as $target) {
            try {
                // Try to store notification in database (table might not exist yet)
                $notification_id = null;
                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO push_notifications (
                            user_id, title, body, device_token, status, created_at
                        ) VALUES (?, ?, ?, ?, 'sent', CURRENT_TIMESTAMP)
                    ");
                    
                    $stmt->execute([
                        $target['id'],
                        $input['title'],
                        $input['body'],
                        $target['device_token']
                    ]);
                    
                    $notification_id = $pdo->lastInsertId();
                } catch (Exception $db_error) {
                    // Table doesn't exist yet, continue without database logging
                    error_log("Database logging failed (table may not exist): " . $db_error->getMessage());
                }
                
                // Here you would integrate with Firebase Cloud Messaging (FCM)
                // For now, we'll simulate the FCM call
                $fcm_response = simulateFCMNotification($target['device_token'], $input['title'], $input['body']);
                
                $results[] = [
                    'user_id' => $target['id'],
                    'device_token' => $target['device_token'],
                    'notification_id' => $notification_id,
                    'status' => 'sent',
                    'fcm_response' => $fcm_response
                ];
                
                $success_count++;
                
            } catch (Exception $e) {
                $failed_count++;
                error_log("Failed to send notification to device {$target['device_token']}: " . $e->getMessage());
                
                $results[] = [
                    'user_id' => $target['id'],
                    'device_token' => $target['device_token'],
                    'status' => 'failed',
                    'error' => $e->getMessage()
                ];
            }
        }
    
    echo json_encode([
        'success' => true,
        'message' => "Notifications processed successfully! Success: $success_count, Failed: $failed_count",
        'total_targets' => count($notifications_to_send),
        'success_count' => $success_count,
        'failed_count' => $failed_count,
        'results' => $results
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error occurred'
    ]);
}

/**
 * Simulate Firebase Cloud Messaging notification
 * In production, replace this with actual FCM integration
 */
function simulateFCMNotification($deviceToken, $title, $body) {
    // This is a placeholder for FCM integration
    // You would typically use the Firebase Admin SDK here
    
    $fcm_data = [
        'to' => $deviceToken,
        'notification' => [
            'title' => $title,
            'body' => $body,
            'sound' => 'default',
            'badge' => '1'
        ],
        'data' => [
            'click_action' => 'FLUTTER_NOTIFICATION_CLICK',
            'title' => $title,
            'body' => $body,
            'timestamp' => time()
        ]
    ];
    
    // Simulate API call delay
    usleep(100000); // 0.1 seconds
    
    // Return simulated FCM response
    return [
        'message_id' => 'simulated_' . uniqid(),
        'status' => 'success',
        'device_token' => $deviceToken
    ];
}
?> 