<?php

namespace App\Http\Controllers;

use App\Mail\NotificationGames;
use App\Models\Notification;
use App\Models\Credits;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use App\Mail\NotificationEmail;

class NotificationController extends Controller
{
    public function index()
    {
        $notifications = Notification::all();
        return response()->json($notifications);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:5000',
            'message' => 'required|string|max:5000',
            'notifyUsers' => 'boolean',
        ]);

        try {
            $notification = Notification::create([
                'message' => $validated['message'],
                'title' => $validated['title'],
            ]);

            // Attach notification to all users with seen set to false
            $users = DB::table('users')->select('id')->get();
            foreach ($users as $user) {
                $notification->users()->attach($user->id, ['seen' => false]);
            }

            if ($request->has('notifyUsers') && $request->notifyUsers) {
                $users = DB::table('users')->select('email', 'name')->get();
                $userCount = $users->count();

                // Check available credits
                $credits = Credits::first();
                if ($credits->number < $userCount) {
                    return response()->json(['error' => 'Insufficient credits'], 400);
                }

                // Send emails via Brevo batch API
                $this->sendBrevoEmails($users, $notification->title, $notification->message);

                // Deduct credits
                $credits->number -= $userCount;
                $credits->save();
            }

            return response()->json($notification, 201);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send notification', 'details' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $notification = Notification::findOrFail($id);
            $notification->delete();
            return response()->json(['message' => 'Notification deleted successfully'], 204);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to delete notification', 'details' => $e->getMessage()], 500);
        }
    }

    public function notifyUsers(Request $request)
    {
        try {
            // Fetch user emails
            $users = DB::table('users')->select('email', 'name')->get();
            $userCount = $users->count();
            //Log::info($users);
            // Check available credits
            $credits = Credits::first();
            if ($credits->number < $userCount) {
                return response()->json(['error' => 'Insufficient credits'], 400);
            }

            // Email content from NotificationGames template
            $title = 'New Games Posted';
            $message = '<!DOCTYPE html>
<html>
<head>
    <title>Game Notifications</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 600px;
            margin: 50px auto;
            background-color: #ffffff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #333333;
        }
        p {
            color: #555555;
            line-height: 1.6;
        }
        .footer {
            margin-top: 20px;
            font-size: 12px;
            color: #aaaaaa;
            text-align: center;
        }
        a {
            color: #1a73e8;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>New Games Posted</h1>
    <p>We are excited to inform you that new games have been posted. Click the link below to view the latest predictions:</p>
    <p><a href="https://www.odddsonpoint.com/predictions">View Predictions</a></p>
    <div class="footer">
        <p>&copy; ' . date('Y') . ' Oddsonppoint.com. All rights reserved.</p>
    </div>
</div>
</body>
</html>';

            // Send emails via Brevo batch API
          $this->sendBrevoEmails($users, $title, $message);

            // Deduct credits
            $credits->number -= $userCount;
            $credits->save();

            return response()->json(['message' => 'Notifications sent successfully'], 201);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send notification', 'details' => $e->getMessage()], 500);
        }
    }

    public function unseenCount()
    {
        $unseenCount = Auth::user()->notifications()->wherePivot('seen', false)->count();
        return response()->json(['unseen_count' => $unseenCount]);
    }

    public function markAsSeen()
    {
        $user = Auth::user();
        $user->notifications()->updateExistingPivot($user->notifications->pluck('id'), ['seen' => true]);
        return response()->json(['message' => 'Notifications marked as seen'], 200);
    }

    /**
     * Send emails via Brevo batch API
     *
     * @param \Illuminate\Support\Collection $users
     * @param string $subject
     * @param string $htmlContent
     * @return void
     */
    private function sendBrevoEmails($users, $subject, $htmlContent)
    {
        // Filter out invalid emails BEFORE processing
        $validUsers = $users->filter(function($user) {
            return !empty($user->email) &&
                filter_var($user->email, FILTER_VALIDATE_EMAIL);
        });

        // Split valid users into batches of 1000
        $batches = $validUsers->chunk(1000);

        foreach ($batches as $batch) {
            $messageVersions = [];

            foreach ($batch as $user) {
                $messageVersions[] = [
                    'to' => [
                        [
                            'email' => $user->email,
                            'name' => $user->name ?? ''
                        ]
                    ]
                ];
            }

            $response = Http::withHeaders([
                'api-key' => env('BREVO_API_KEY'),
                'accept' => 'application/json',
                'content-type' => 'application/json'
            ])->post('https://api.brevo.com/v3/smtp/email', [
                'sender' => [
                    'email' => env('BREVO_SENDER_EMAIL', 'predictions@oddsonpoint.com'),
                    'name' => env('BREVO_SENDER_NAME', 'OddsOnPoint')
                ],
                'subject' => $subject,
                'htmlContent' => $htmlContent,
                'messageVersions' => $messageVersions
            ]);

            if (!$response->successful()) {
                \Log::error('Brevo API Error: ' . $response->body());
                throw new \Exception('Failed to send emails via Brevo');
            }
        }
    }
}
