<?php

/**
 * Migration script for plan-type-specific notification templates
 * This script converts existing notification templates to the new plan-type-specific structure
 */

require_once dirname(__DIR__) . '/init.php';

// Check if running from command line or web
$isCli = php_sapi_name() === 'cli';

if (!$isCli) {
    _admin(); // Check admin permissions for web access
}

echo "Starting notification template migration...\n";

$notifications_file = $UPLOAD_PATH . DIRECTORY_SEPARATOR . 'notifications.json';
$default_file = $UPLOAD_PATH . DIRECTORY_SEPARATOR . 'notifications.default.json';

// Load existing notifications
$existing_notifications = [];
if (file_exists($notifications_file)) {
    $existing_notifications = json_decode(file_get_contents($notifications_file), true);
    echo "Found existing notifications.json\n";
} else {
    echo "No existing notifications.json found, using default templates\n";
    $existing_notifications = json_decode(file_get_contents($default_file), true);
}

// Load new default structure
$new_default = json_decode(file_get_contents($default_file), true);

// Plan-specific keys that need migration
$plan_specific_keys = ['expired', 'reminder_7_day', 'reminder_3_day', 'reminder_1_day'];

$migrated_notifications = [];

// Migrate plan-specific templates
foreach ($plan_specific_keys as $key) {
    if (isset($existing_notifications[$key])) {
        $existing_value = $existing_notifications[$key];
        
        // Check if it's already in new format (array)
        if (is_array($existing_value)) {
            echo "Template '$key' is already in new format, keeping as is\n";
            $migrated_notifications[$key] = $existing_value;
        } else {
            // Convert old format to new format
            echo "Converting template '$key' to plan-type-specific format\n";
            
            // Use the old template as default for both plan types
            $migrated_notifications[$key] = [
                'hotspot' => $existing_value,
                'pppoe' => $existing_value,
                'default' => $existing_value
            ];
        }
    } else {
        // Use new default structure
        echo "Using default template for '$key'\n";
        $migrated_notifications[$key] = $new_default[$key];
    }
}

// Copy other notification types as-is
$other_keys = ['balance_send', 'balance_received', 'invoice_paid', 'invoice_balance', 'user_registration'];
foreach ($other_keys as $key) {
    if (isset($existing_notifications[$key])) {
        $migrated_notifications[$key] = $existing_notifications[$key];
    } else {
        $migrated_notifications[$key] = $new_default[$key];
    }
}

// Create backup of original file
if (file_exists($notifications_file)) {
    $backup_file = $UPLOAD_PATH . DIRECTORY_SEPARATOR . 'notifications.backup.' . date('Y-m-d_H-i-s') . '.json';
    copy($notifications_file, $backup_file);
    echo "Created backup: $backup_file\n";
}

// Save migrated notifications
$result = file_put_contents($notifications_file, json_encode($migrated_notifications, JSON_PRETTY_PRINT));

if ($result !== false) {
    echo "Migration completed successfully!\n";
    echo "New notification structure saved to: $notifications_file\n";
    echo "\nMigration Summary:\n";
    echo "- Converted " . count($plan_specific_keys) . " plan-specific templates\n";
    echo "- Preserved " . count($other_keys) . " other notification types\n";
    echo "- Backup created for safety\n";
    echo "\nYou can now customize plan-type-specific templates in the admin panel.\n";
} else {
    echo "Error: Failed to save migrated notifications\n";
    exit(1);
}

// Test the new structure
echo "\nTesting new notification structure...\n";
$test_notifications = json_decode(file_get_contents($notifications_file), true);

foreach ($plan_specific_keys as $key) {
    if (isset($test_notifications[$key]) && is_array($test_notifications[$key])) {
        echo "✓ Template '$key' is properly structured\n";
    } else {
        echo "✗ Template '$key' has issues\n";
    }
}

echo "\nMigration completed!\n";
