<?php

namespace App\Services;

use App\Models\User;
use App\Models\Role;
use App\Notifications\AdminNotification;
use Illuminate\Support\Facades\Log;

class AdminNotificationService
{
    /**
     * Get all admin users
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getAdminUsers()
    {
        return User::whereHas('roles', function ($query) {
            $query->where('role', 'admin');
        })->get();
    }

    /**
     * Send notification to all admins
     *
     * @param array $notificationData
     * @return void
     */
    public static function notifyAdmins($notificationData)
    {
        try {
            $admins = self::getAdminUsers();
            
            foreach ($admins as $admin) {
                $admin->notify(new AdminNotification((object) $notificationData));
            }

            Log::info('Admin notification sent', [
                'type' => isset($notificationData['type']) ? $notificationData['type'] : 'general',
                'title' => $notificationData['title'],
                'admin_count' => $admins->count()
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send admin notification', [
                'error' => $e->getMessage(),
                'notification_data' => $notificationData
            ]);
        }
    }

    /**
     * Notify admins about new user registration
     *
     * @param User $user
     * @return void
     */
    public static function newUserRegistration($user)
    {
        $notificationData = [
            'title' => 'New User Registration',
            'content' => 'A new user has registered on the platform',
            'type' => 'user_registration',
            'url' => '/admin/users',
            'mail_content' => "
                <h2>🔔 New User Registration Alert</h2>
                <p>A new user has registered on AMD CONSULTING platform.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>User Details:</h3>
                    <p><strong>Name:</strong> {$user->name}</p>
                    <p><strong>Email:</strong> {$user->email}</p>
                    <p><strong>Phone:</strong> " . (isset($user->phone) ? $user->phone : 'Not provided') . "</p>
                    <p><strong>Country:</strong> " . (isset($user->country) ? $user->country : 'Not provided') . "</p>
                    <p><strong>Registration Date:</strong> {$user->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review the new user account and verify their details.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #007bff; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        View User Profile
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'user_id' => $user->id,
                'user_name' => $user->name,
                'user_email' => $user->email,
                'registration_date' => $user->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new withdrawal request
     *
     * @param \App\Models\Withdrawal $withdrawal
     * @return void
     */
    public static function newWithdrawalRequest($withdrawal)
    {
        $notificationData = [
            'title' => 'New Withdrawal Request',
            'content' => 'A new withdrawal request has been submitted',
            'type' => 'withdrawal_request',
            'url' => '/admin/withdrawals',
            'mail_content' => "
                <h2>💰 New Withdrawal Request Alert</h2>
                <p>A new withdrawal request has been submitted and requires admin approval.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Withdrawal Details:</h3>
                    <p><strong>User:</strong> {$withdrawal->user->name}</p>
                    <p><strong>Email:</strong> {$withdrawal->user->email}</p>
                    <p><strong>Amount:</strong> $" . number_format($withdrawal->amount, 2) . "</p>
                    <p><strong>Source:</strong> {$withdrawal->source}</p>
                    <p><strong>Coin:</strong> {$withdrawal->coin_name}</p>
                    <p><strong>Address:</strong> {$withdrawal->address}</p>
                    <p><strong>Request Date:</strong> {$withdrawal->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review and approve/decline this withdrawal request.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Decline
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'withdrawal_id' => $withdrawal->id,
                'user_id' => $withdrawal->user_id,
                'amount' => $withdrawal->amount,
                'source' => $withdrawal->source,
                'coin_name' => $withdrawal->coin_name,
                'request_date' => $withdrawal->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new investment
     *
     * @param \App\Models\Investment $investment
     * @return void
     */
    public static function newInvestment($investment)
    {
        $notificationData = [
            'title' => 'New Investment Request',
            'content' => 'A new investment request has been submitted',
            'type' => 'investment_request',
            'url' => '/admin/investments',
            'mail_content' => "
                <h2>📈 New Investment Request Alert</h2>
                <p>A new investment request has been submitted and requires admin approval.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Investment Details:</h3>
                    <p><strong>User:</strong> {$investment->user->name}</p>
                    <p><strong>Email:</strong> {$investment->user->email}</p>
                    <p><strong>Plan:</strong> {$investment->plan->name}</p>
                    <p><strong>Amount:</strong> $" . number_format($investment->amount_invested, 2) . "</p>
                    <p><strong>Payment Source:</strong> {$investment->payment_source}</p>
                    <p><strong>Duration:</strong> {$investment->duration}</p>
                    <p><strong>Request Date:</strong> {$investment->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review and approve/decline this investment request.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Decline
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'investment_id' => $investment->id,
                'user_id' => $investment->user_id,
                'plan_id' => $investment->investment_plan_id,
                'amount' => $investment->amount_invested,
                'payment_source' => $investment->payment_source,
                'request_date' => $investment->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new funding request
     *
     * @param \App\Models\Funding $funding
     * @return void
     */
    public static function newFundingRequest($funding)
    {
        $notificationData = [
            'title' => 'New Funding Request',
            'content' => 'A new funding request has been submitted',
            'type' => 'funding_request',
            'url' => '/admin/fundings',
            'mail_content' => "
                <h2>💳 New Funding Request Alert</h2>
                <p>A new funding request has been submitted and requires admin review.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Funding Details:</h3>
                    <p><strong>User:</strong> {$funding->user->name}</p>
                    <p><strong>Email:</strong> {$funding->user->email}</p>
                    <p><strong>Amount:</strong> $" . number_format($funding->amount, 2) . "</p>
                    <p><strong>Gateway:</strong> {$funding->gateway}</p>
                    <p><strong>Transaction ID:</strong> {$funding->transaction_id}</p>
                    <p><strong>Status:</strong> {$funding->status}</p>
                    <p><strong>Request Date:</strong> {$funding->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review and verify this funding request.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Decline
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'funding_id' => $funding->id,
                'user_id' => $funding->user_id,
                'amount' => $funding->amount,
                'gateway' => $funding->gateway,
                'transaction_id' => $funding->transaction_id,
                'status' => $funding->status,
                'request_date' => $funding->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new transfer request
     *
     * @param \App\Models\Transfer $transfer
     * @return void
     */
    public static function newTransferRequest($transfer)
    {
        $notificationData = [
            'title' => 'New Transfer Request',
            'content' => 'A new fund transfer request has been submitted',
            'type' => 'transfer_request',
            'url' => '/admin/transfers/approvals',
            'mail_content' => "
                <h2>💸 New Transfer Request Alert</h2>
                <p>A new fund transfer request has been submitted and requires admin approval.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Transfer Details:</h3>
                    <p><strong>From:</strong> {$transfer->sender->name} ({$transfer->sender->email})</p>
                    <p><strong>To:</strong> {$transfer->recipient->name} ({$transfer->recipient->email})</p>
                    <p><strong>Amount:</strong> $" . number_format($transfer->amount, 2) . "</p>
                    <p><strong>Destination Wallet:</strong> {$transfer->destination}</p>
                    <p><strong>Description:</strong> {$transfer->description}</p>
                    <p><strong>Reference:</strong> {$transfer->reference}</p>
                    <p><strong>Request Date:</strong> {$transfer->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review and approve/reject this transfer request.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Reject
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'transfer_id' => $transfer->id,
                'sender_id' => $transfer->sender_id,
                'recipient_id' => $transfer->recipient_id,
                'amount' => $transfer->amount,
                'destination' => $transfer->destination,
                'reference' => $transfer->reference,
                'request_date' => $transfer->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new job posting request
     *
     * @param \App\Models\Job $job
     * @return void
     */
    public static function newJobPostingRequest($job)
    {
        $notificationData = [
            'title' => 'New Job Posting Request',
            'content' => 'A new job posting has been submitted and requires admin approval',
            'type' => 'job_posting_request',
            'url' => '/admin/jobs/approvals',
            'mail_content' => "
                <h2>💼 New Job Posting Request Alert</h2>
                <p>A new job posting has been submitted and requires admin approval.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Job Details:</h3>
                    <p><strong>Job Title:</strong> {$job->job_title}</p>
                    <p><strong>Company:</strong> {$job->company_name}</p>
                    <p><strong>Posted by:</strong> {$job->employer->name} ({$job->employer->email})</p>
                    <p><strong>Location:</strong> {$job->location}</p>
                    <p><strong>Job Type:</strong> {$job->job_type}</p>
                    <p><strong>Experience Level:</strong> {$job->experience_level}</p>
                    <p><strong>Salary Range:</strong> {$job->salary_range}</p>
                    <p><strong>Request Date:</strong> {$job->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review and approve/reject this job posting.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Reject
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'job_id' => $job->id,
                'employer_id' => $job->employer_id,
                'job_title' => $job->job_title,
                'company_name' => $job->company_name,
                'request_date' => $job->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about new job application request
     *
     * @param \App\Models\JobApplication $application
     * @return void
     */
    public static function newJobApplicationRequest($application)
    {
        $notificationData = [
            'title' => 'New Job Application',
            'content' => 'A new job application has been submitted and requires admin review',
            'type' => 'job_application_request',
            'url' => '/admin/job-applications',
            'mail_content' => "
                <h2>📝 New Job Application Alert</h2>
                <p>A new job application has been submitted and requires admin review.</p>
                
                <div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 15px 0;'>
                    <h3>Application Details:</h3>
                    <p><strong>Applicant:</strong> {$application->applicant->name} ({$application->applicant->email})</p>
                    <p><strong>Job:</strong> {$application->job->job_title}</p>
                    <p><strong>Company:</strong> {$application->job->company_name}</p>
                    <p><strong>Application Date:</strong> {$application->created_at->format('d M Y, H:i')}</p>
                </div>
                
                <p><strong>Action Required:</strong> Please review this job application.</p>
                
                <p style='margin-top: 20px;'>
                    <a href='#' style='background: #28a745; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; margin-right: 10px;'>
                        Approve
                    </a>
                    <a href='#' style='background: #dc3545; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>
                        Reject
                    </a>
                </p>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated notification from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => [
                'application_id' => $application->id,
                'applicant_id' => $application->applicant_id,
                'job_id' => $application->job_id,
                'request_date' => $application->created_at->toISOString()
            ]
        ];

        self::notifyAdmins($notificationData);
    }

    /**
     * Notify admins about system alerts
     *
     * @param string $title
     * @param string $message
     * @param string $type
     * @param array $data
     * @return void
     */
    public static function systemAlert($title, $message, $type = 'system', $data = [])
    {
        $notificationData = [
            'title' => $title,
            'content' => $message,
            'type' => $type,
            'url' => '/admin/dashboard',
            'mail_content' => "
                <h2>🚨 System Alert</h2>
                <p>{$message}</p>
                
                <div style='background: #fff3cd; padding: 15px; border-radius: 5px; margin: 15px 0; border-left: 4px solid #ffc107;'>
                    <h3>Alert Details:</h3>
                    <p><strong>Type:</strong> {$type}</p>
                    <p><strong>Time:</strong> " . now()->format('d M Y, H:i:s') . "</p>
                </div>
                
                <p style='margin-top: 20px; color: #666; font-size: 12px;'>
                    This is an automated system alert from AMD CONSULTING Admin System.
                </p>
            ",
            'data' => array_merge($data, [
                'alert_type' => $type,
                'alert_time' => now()->toISOString()
            ])
        ];

        self::notifyAdmins($notificationData);
    }
} 