<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Facades\App\Services\Notifications;
use Illuminate\Pagination\LengthAwarePaginator;
use Cache;

class NotificationController extends Controller
{
    public function getNotifications(Request $request)
    {
    	$notifications = Notifications::getAll();

        // Create a new Laravel collection from the array data.
        $notifications = collect($notifications);
        $count = count($notifications);

        if (request()->has('region') || request()->has('type') || request()->has('site_code')) {
        	$region   = request('region');
	    	$siteCode = request('site_code');
	    	$type     = request('type');

	    	if ($region) {
	    		$notifications = $notifications->filter(function($record) use($region) {
		    		return in_array($record['region_id'], $region);
		    	});
                $count = count($notifications);
	    	}

	    	if ($siteCode) {
	    		$notifications = $notifications->filter(function($record) use($siteCode) {
		    		return in_array($record['site_code_id'], $siteCode);
		    	});
                $count = count($notifications);
	    	}

	    	if ($type) {
	    		$notifications = $notifications->filter(function($record) use($type) {
		    		return in_array($record['type'], $type);
		    	});
                $count = count($notifications);
	    	}
        }

 		// Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();

        // Define how many items we want to be visible in each page.
        $perPage = 50;

        // Slice the collection to get the items to display in current page.
        $currentPageItems = $notifications->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

        $number = (($currentPage - 1) * $perPage) + 1 ;

        // Create our paginator and pass it to the view.
        $paginatedItems= new LengthAwarePaginator($currentPageItems , count($notifications), $perPage);

        // Set url path for generted links.
        $paginatedItems->setPath($request->url());

        return view('notification.index', ['notifications' => $paginatedItems, 'number' => $number, 'count' => $count]);

    }

    public function refresh()
    {
        Cache::forget('notification8');

    	return redirect('/notifications')->with('message', 'The notifications has been refreshed');
    }

}
