<?php

namespace App\Http\Controllers\Backend2;

use App\Components\Functions;
use App\Http\Requests\CreateNotificationRequest;
use App\Jobs\PushNotification;
use App\Models\Hostel;
use App\Models\Notification;
use App\Models\OwnerNotification;
use App\Models\Renter;
use App\Models\Room;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class NotificationController extends Controller
{
    public function __construct()
    {
    }

    public function index() {
        return view('admin2.notifications.index');
    }

    public function create() {
        $hostels = Hostel::query()->where('owner_id', auth('backend')->user()->id)->get();

        $rooms = Room::whereIn('hostel_id', $hostels->pluck('id')->toArray())->with(['renters'])->get(['id', 'name', 'hostel_id']);

        return view('admin2.notifications.create', compact('hostels', 'rooms'));
    }

    public function store(CreateNotificationRequest $request) {
        \DB::beginTransaction();
        try {
            $ownerId = auth('backend')->user()->id;
            if (auth('backend')->user()->type == User::STAFF) {
                $ownerId = auth('backend')->user()->staff_owner_id;
            }

            $title = $request->title;
            $content = $request->content;
            $hostelId = $request->hostelId;
            $roomId = $request->room_id;

            if (!$hostelId && !$roomId) {
                $hostels = Hostel::query()->where('owner_id', auth('backend')->user()->id)->get();
                $rooms = Room::whereIn('hostel_id', $hostels->pluck('id')->toArray())->with(['renters'])->get(['id', 'name', 'hostel_id']);
            } else {
                $rooms = Room::whereIn('id', $roomId)->with(['renters'])->get(['id', 'name', 'hostel_id']);
            }

            foreach ($rooms as $room) {
                if (!empty($room->renters)) {
                    $ownerNotification = OwnerNotification::create([
                        'title' => $request->title,
                        'owner_id' => $ownerId,
                        'hostel_id' => $room->hostel_id,
                        'room_id' => $room->id,
                        'content' => $request->content
                    ]);

                    if ($request->hasFile('image')) {
                        $imageFile = Functions::uploadImage($request->image);
                        \DB::table('notification_images')
                            ->insert([
                                'notification_id' => $ownerNotification->id,
                                'image' => $imageFile
                            ]);
                    }

                    foreach ($room->renters as $renter) {
                        $notification = Notification::create([
                            'to_user' => $renter->id,
                            'title' => $title,
                            'user_id' => $ownerId,
                            'hostel_id' => $room->hostel_id,
                            'room_id' => $room->id,
                            'content' => $content,
                            'status' => Notification::PUSHED,
                            'owner_notification_id' => $ownerNotification->id,
                            'is_owner_send' => true
                        ]);

                        dispatch((new PushNotification($notification->id))->onConnection('redis'));
                    }

                    $ownerStaffs = User::query()
                        ->where(function ($q) use ($ownerId) {
                            $q->orWhere('id', $ownerId);
                            $q->orWhere('staff_owner_id', $ownerId);
                        })
                        ->where('id', '<>', $ownerId)
                        ->get();

                    if ($ownerStaffs->count()) {
                        foreach ($ownerStaffs as $ownerStaff) {
                            $notification = Notification::create([
                                'to_user' => $ownerStaff->id,
                                'title' => $title,
                                'user_id' => $ownerId,
                                'hostel_id' => $room->hostel_id,
                                'room_id' => $room->id,
                                'content' => $content,
                                'status' => Notification::PUSHED,
                                'owner_notification_id' => $ownerNotification->id,
                                'is_owner_send' => true
                            ]);
                            dispatch((new PushNotification($notification->id))->onConnection('redis'));
                        }
                    }
                }
            }
            \DB::commit();

            return redirect()->back()->with('success', 'Gửi tin nhắn thành công');

        } catch (\Exception $exception) {
            \DB::rollBack();

            return redirect()->back()->with('error', 'Gửi tin nhắn không thành công');
        }
    }
}
