<?php
namespace App\Services;
use App\Models\EmailAccount;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
class EmailRotationService {
    public function send(string $to, string $subject, string $view, array $data = []): bool {
        $accounts = EmailAccount::where('is_active', true)->get();
        foreach ($accounts as $account) {
            if ($account->last_sent_at && !$account->last_sent_at->isToday()) {
                $account->sent_count = 0; $account->save();
            }
        }
        $account = $accounts->filter(fn($acc) => $acc->canSend())->first();
        if (!$account) { Log::error('No email account available'); return false; }
        try {
            config(['mail.mailers.smtp.username' => $account->email, 'mail.mailers.smtp.password' => $account->app_password, 'mail.from.address' => $account->email, 'mail.from.name' => config('app.name')]);
            Mail::send($view, $data, function ($message) use ($to, $subject) { $message->to($to)->subject($subject); });
            $account->incrementSent(); Log::info("Email sent via {$account->email} to {$to}"); return true;
        } catch (\Exception $e) { Log::error("Failed: " . $e->getMessage()); return false; }
    }
}