#!/usr/bin/env php
<?php

/**
 * Test script to dispatch all transactional emails in all locales
 *
 * This script creates test scenarios for each email type and dispatches
 * them to a test email address in all available locales.
 */

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\User;
use App\Models\Organization;
use App\Models\Transaction;
use App\Models\Post;
use App\Models\Reaction;
use App\Models\Tag;
use App\Mail\TransferReceived;
use App\Mail\ReactionCreatedMail;
use App\Mail\ReservationCreatedMail;
use App\Mail\ReservationUpdateMail;
use App\Mail\ReservationCancelledMail;
use App\Mail\ProfileEditedByAdminMail;
use App\Mail\ProfileLinkChangedMail;
use App\Mail\TagAddedMail;
use App\Mail\UserDeletedMail;
use App\Mail\VerifyProfileEmailMailable;
use App\Mail\NewMessageMail;
use Illuminate\Support\Facades\Mail;

echo "=" . str_repeat("=", 78) . "\n";
echo "Testing All Transactional Emails\n";
echo "=" . str_repeat("=", 78) . "\n\n";

// Configuration
$testEmail = 'test@example.com'; // Change this to your test email
$locales = ['en', 'nl', 'de', 'es', 'fr'];

// Find or create test user
$testUser = User::where('email', 'test-user@timebank.local')->first();
if (!$testUser) {
    echo "ERROR: Test user not found. Please create a user with email 'test-user@timebank.local'\n";
    echo "Attempting to use first available user instead...\n";
    $testUser = User::whereNull('deleted_at')->first();
    if (!$testUser) {
        echo "ERROR: No users found in database!\n";
        exit(1);
    }
}

echo "Using test user: {$testUser->name} ({$testUser->email})\n";
echo "Emails will be queued for: {$testEmail}\n\n";

$emailsSent = 0;
$errors = [];

// Helper function to send email
function sendTestEmail($mailClass, $emailName, $locale, $testEmail, &$emailsSent, &$errors) {
    try {
        Mail::to($testEmail)->queue($mailClass);
        echo "  ✓ {$locale}: Queued successfully\n";
        $emailsSent++;
    } catch (\Exception $e) {
        $error = "  ✗ {$locale}: {$e->getMessage()}";
        echo $error . "\n";
        $errors[] = $error;
    }
}

// 1. Transfer/Payment Received Email
echo "\n1. Testing Transfer Received Email\n";
echo str_repeat("-", 80) . "\n";

$transaction = Transaction::with(['accountFrom.accountable', 'accountTo.accountable'])
    ->whereHas('accountFrom')
    ->whereHas('accountTo')
    ->first();

if ($transaction) {
    foreach ($locales as $locale) {
        $mail = new TransferReceived($transaction, $locale);
        sendTestEmail($mail, 'TransferReceived', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No transactions found\n";
}

// 2. Reaction Emails (Star Received)
echo "\n2. Testing Star Received Email\n";
echo str_repeat("-", 80) . "\n";

$reaction = Reaction::where('reaction_type', 'star')
    ->with(['post.profile', 'profile'])
    ->first();

if ($reaction) {
    foreach ($locales as $locale) {
        $mail = new ReactionCreatedMail($reaction->post, $reaction, $locale);
        sendTestEmail($mail, 'StarReceived', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No star reactions found\n";
}

// 3. Reservation Created Email
echo "\n3. Testing Reservation Created Email\n";
echo str_repeat("-", 80) . "\n";

$reservation = Reaction::where('reaction_type', 'reservation')
    ->with(['post.profile', 'profile'])
    ->first();

if ($reservation) {
    foreach ($locales as $locale) {
        $mail = new ReservationCreatedMail($reservation->post, $reservation, $locale);
        sendTestEmail($mail, 'ReservationCreated', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No reservations found\n";
}

// 4. Reservation Updated Email
echo "\n4. Testing Reservation Updated Email\n";
echo str_repeat("-", 80) . "\n";

if ($reservation) {
    foreach ($locales as $locale) {
        $mail = new ReservationUpdateMail($reservation->post, $reservation, $locale);
        sendTestEmail($mail, 'ReservationUpdate', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No reservations found\n";
}

// 5. Reservation Cancelled Email
echo "\n5. Testing Reservation Cancelled Email\n";
echo str_repeat("-", 80) . "\n";

if ($reservation) {
    foreach ($locales as $locale) {
        $mail = new ReservationCancelledMail($reservation->post, $reservation, $locale);
        sendTestEmail($mail, 'ReservationCancelled', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No reservations found\n";
}

// 6. Profile Edited by Admin Email
echo "\n6. Testing Profile Edited by Admin Email\n";
echo str_repeat("-", 80) . "\n";

foreach ($locales as $locale) {
    $changes = [
        'name' => ['old' => 'Old Name', 'new' => 'New Name'],
        'email' => ['old' => 'old@example.com', 'new' => 'new@example.com'],
    ];
    $mail = new ProfileEditedByAdminMail($testUser, $changes, $locale);
    sendTestEmail($mail, 'ProfileEditedByAdmin', $locale, $testEmail, $emailsSent, $errors);
}

// 7. Profile Link Changed Email
echo "\n7. Testing Profile Link Changed Email\n";
echo str_repeat("-", 80) . "\n";

foreach ($locales as $locale) {
    $mail = new ProfileLinkChangedMail($testUser, 'website', 'https://old-site.com', 'https://new-site.com', $locale);
    sendTestEmail($mail, 'ProfileLinkChanged', $locale, $testEmail, $emailsSent, $errors);
}

// 8. Tag Added Email
echo "\n8. Testing Tag Added Email\n";
echo str_repeat("-", 80) . "\n";

$tag = Tag::first();
if ($tag) {
    foreach ($locales as $locale) {
        $mail = new TagAddedMail($testUser, $tag, $locale);
        sendTestEmail($mail, 'TagAdded', $locale, $testEmail, $emailsSent, $errors);
    }
} else {
    echo "  ⚠ Skipped: No tags found\n";
}

// 9. User Deleted Email
echo "\n9. Testing User Deleted Email\n";
echo str_repeat("-", 80) . "\n";

foreach ($locales as $locale) {
    $emailData = [
        'time' => now()->translatedFormat('j F Y, H:i'),
        'deletedUser' => (object)[
            'name' => $testUser->name,
            'full_name' => $testUser->full_name ?? $testUser->name,
            'lang_preference' => $locale,
        ],
        'mail' => $testEmail,
        'balanceHandlingOption' => 'delete',
        'totalBalance' => 500,
        'donationAccountId' => null,
        'donationAccountName' => null,
        'donationOrganizationName' => null,
    ];
    $mail = new UserDeletedMail($emailData);
    sendTestEmail($mail, 'UserDeleted', $locale, $testEmail, $emailsSent, $errors);
}

// 10. Email Verification
echo "\n10. Testing Email Verification Email\n";
echo str_repeat("-", 80) . "\n";

foreach ($locales as $locale) {
    $verificationUrl = url('/verify-email/' . base64_encode($testEmail));
    $mail = new VerifyProfileEmailMailable($testEmail, $verificationUrl, $locale);
    sendTestEmail($mail, 'VerifyEmail', $locale, $testEmail, $emailsSent, $errors);
}

// Summary
echo "\n" . str_repeat("=", 80) . "\n";
echo "Testing Complete!\n";
echo str_repeat("=", 80) . "\n";
echo "Total emails queued: {$emailsSent}\n";

if (count($errors) > 0) {
    echo "\nErrors encountered: " . count($errors) . "\n";
    foreach ($errors as $error) {
        echo $error . "\n";
    }
}

echo "\nProcessing queue...\n";
echo "Run: php artisan queue:work --stop-when-empty\n";
echo "\n";
