<?php

namespace App\Services;

use App\Models\User;
use App\Models\Driver;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class NotificationService
{
    /**
     * Send push notification via Firebase Cloud Messaging
     */
    public function sendPush(string $token, string $title, string $body, array $data = []): bool
    {
        $serverKey = config('services.firebase.server_key');
        if (!$serverKey || !$token) return false;

        try {
            $response = Http::withHeaders([
                'Authorization' => "key={$serverKey}",
                'Content-Type' => 'application/json',
            ])->post('https://fcm.googleapis.com/fcm/send', [
                'to' => $token,
                'notification' => ['title' => $title, 'body' => $body, 'sound' => 'default'],
                'data' => array_merge(['click_action' => 'FLUTTER_NOTIFICATION_CLICK'], $data),
                'android' => ['priority' => 'high', 'notification' => ['channel_id' => 'lynx_channel']],
                'apns' => ['payload' => ['aps' => ['sound' => 'default']]],
            ]);

            return $response->successful();
        } catch (\Exception $e) {
            Log::error("Push notification error: {$e->getMessage()}");
            return false;
        }
    }

    /**
     * Send push notification to a user
     */
    public function notifyUser(User $user, string $title, string $body, array $data = []): bool
    {
        if (!$user->fcm_token) return false;
        return $this->sendPush($user->fcm_token, $title, $body, $data);
    }

    /**
     * Send push notification to a driver
     */
    public function notifyDriver(Driver $driver, string $title, string $body, array $data = []): bool
    {
        if (!$driver->fcm_token) return false;
        return $this->sendPush($driver->fcm_token, $title, $body, $data);
    }

    /**
     * Send email notification
     */
    public function sendEmail(string $to, string $subject, string $content): bool
    {
        try {
            Mail::raw($content, function ($message) use ($to, $subject) {
                $message->to($to)->subject($subject);
            });
            return true;
        } catch (\Exception $e) {
            Log::error("Email error: {$e->getMessage()}");
            return false;
        }
    }

    /**
     * Send SMS via Twilio
     */
    public function sendSMS(string $to, string $message): bool
    {
        $twilioSid = config('services.twilio.sid');
        $twilioToken = config('services.twilio.token');
        $twilioFrom = config('services.twilio.from');

        if (!$twilioSid || !$twilioToken) return false;

        try {
            $response = Http::withBasicAuth($twilioSid, $twilioToken)
                ->post("https://api.twilio.com/2010-04-01/Accounts/{$twilioSid}/Messages.json", [
                    'From' => $twilioFrom,
                    'To' => $to,
                    'Body' => $message,
                ]);
            return $response->successful();
        } catch (\Exception $e) {
            Log::error("SMS error: {$e->getMessage()}");
            return false;
        }
    }

    /**
     * Notify about a new ride request to nearby drivers
     */
    public function notifyNearbyDrivers(array $rideData, array $driverIds): void
    {
        $drivers = Driver::whereIn('id', $driverIds)->where('is_online', true)->get();
        foreach ($drivers as $driver) {
            $this->notifyDriver($driver, 'New Ride Request', "From: {$rideData['pickup_address']}", [
                'type' => 'new_ride',
                'ride_id' => $rideData['id'],
            ]);
        }
    }

    /**
     * Send bulk notification to all users or drivers
     */
    public function sendBulkNotification(string $type, string $title, string $body, array $userIds = []): void
    {
        $query = User::where('is_active', true);
        if (!empty($userIds)) $query->whereIn('id', $userIds);

        $users = $query->get();
        foreach ($users as $user) {
            $this->notifyUser($user, $title, $body);
        }
    }
}
