<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\AdminNotification;

class NotificationsController extends Controller
{
    public function __construct()
    {
        //
        $this->middleware('auth:admin');

        $adminUser = auth()->guard('admin')->user();

        if (!$adminUser)
        {
            return response()->json(['error' => 'Unauthorized.'], 401);
        }

    }

    public function index() {
        $notifications = AdminNotification::with('instigator')->orderBy('created_at', 'DESC')->get();

        return response()->json(['notifications' => $notifications], 200);
    }

    public function markAll(Request $request)
    {
        $type = $request->type;

        if ($type == true) {
            // Read all

            $notifications = AdminNotification::where('id', '>', 0)->get();

            foreach ($notifications as $key => $notification) {
                
                $notification->read_at = Carbon::now();
                $notification->save();
            }

        }else{
            // Unread all

            $notifications = AdminNotification::where('id', '>', 0)->get();

            foreach ($notifications as $key => $notification) {
                
                $notification->read_at = null;
                $notification->save();
            }

        }

        return response()->json(['status' => 'ok'], 200);
    }

    public function markRead($id, Request $request) {
        $notification = AdminNotification::find($id);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found'], 404);
        }

        $notification->read_at = Carbon::now();
        $notification->save();

        return response()->json(['success' => 'Notification marked as read'], 200);
    }

    public function markUnread($id, Request $request) {
        $notification = AdminNotification::find($id);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found'], 404);
        }

        $notification->read_at = null;
        $notification->save();

        return response()->json(['success' => 'Notification marked as unread'], 200);
    }

    public function delete($id, Request $request) {
        $notification = AdminNotification::find($id);

        if ($notification) {
            $notification->delete();
        }

        return response()->json(['success' => 'Product deleted successfully']);
    }


    public function lastNotification(Request $request)
    {
        $notification = AdminNotification::where([
            ['id', '>', 0],
            ['read_at', null]
        ])->orderBy('id', 'DESC')->limit(1)->get();

        return response()->json($notification, 200);
    }

}
