<?php

namespace App\Http\Controllers\v2019;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Auth\User;
use Session;

class Magazine extends Controller
{
    public function get(Request $request)
    {   //$data = array();
        //$data = json_decode($request->getContent(), true);
		$resourceType='app';
		if ($request->has('resourceType') && $request->input('resourceType')!='')
			$resourceType = $request->input('resourceType');
	  
		if ($request->has('itemID') && $request->input('itemID')!='')
			$itemID = $request->input("itemID");
		
        $data["pageNumber"] = $request->input("pageNumber");
        $data['accessToken'] = $request->input("accessToken");
        $data["bookmarked"] = $request->input("bookmarked");
        $data['filter'] = $request->input("filter");
        $auth = 0;

        $v = app('App\Http\Controllers\v2019\Bookmark')->getBookmarkId($request);

        $bookmarks = $v->getData()->data;
        $bookmark_array = explode(",",$bookmarks);
        $validator = Validator::make($data, [
            'pageNumber' => 'required|int',
//            'filter.month' => ['required', new MonthValidation()],
//            'filter.year' => ['required', new YearValidation()],
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }

        $auth = (!empty(\App\Helper::getMemId()) ? 1 : 0);
		$memid = \App\Helper::getMemId();
        $m = $year = "";
		if (!empty($data['filter']['month']) && isset($data['filter']['month']) != "") {
			$m = date("m", strtotime($data['filter']['month']));
		}
		if (!empty($data['filter']['year']) && isset($data['filter']['year']) != "") {
			$year = $data['filter']['year'];
		}
        $page = $data['pageNumber'];
        $limit = 12; 
			
        $magazines = DB::table('tbl_magazine_issue')->where(function ($query) use ($m,$year,$itemID) {
            if(!empty($m)){
                $query->where(DB::Raw('MONTH(issue_date)'), '=', $m);
            }
            if(!empty($year)){
                $query->where(DB::Raw('YEAR(issue_date)'), '=', $year);
            }
            if(!empty($itemID)){
                $query->where(DB::Raw('id'), '=', $itemID);
            }
        })->orderBy('id', 'desc')->limit($limit)->offset(($page - 1) * $limit)->get();//dd(DB::getQueryLog());
        $rMagazines = [];
		
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='360');
		
        foreach ($magazines as $key => $magazine) {
			$magazine['issue_date'] = strtoupper(date('M Y', strtotime($magazine['issue_date'])));
			$ex = explode(" ", $magazine['issue_date']);
			$iss_dt = ucwords(strtolower($ex[0])) . $ex[1];			
			$imgName = "https://www.steelmint.com/steel360/images/issues_images/" . $iss_dt;  
			$magazine["image"] = $imgName . "_310X410.jpg";
			//$magazine["thumb_image"] = $imgName . "_250X330.jpg";
            $magazine["thumb_image"] = $imgName . "_310X410.jpg";
			
            if($data["bookmarked"] == "Y"){
                if(in_array($magazine["id"],$bookmark_array)){
                        $rMagazines[] = array(
                            "magazineId" => $magazine["id"],
                            "magazinePreviewURL" => $magazine["preview_link"],
                           // "magazineDownloadURL" => ($auth == 0 ? "hidden" : $magazine["download_link"]),
                            //"magazineDownloadURL" => ($isAccessible >= 0 ? "https://www.steelmint.com/app_webview_pages/unauthorised_action.php" : $magazine["download_link"]),
							"magazineDownloadURL" => ($isAccessible >= 0 ? "hidden" : $magazine["download_link"]),
                            "thumbImageURL" => $magazine["thumb_image"],
                            "imageURL" => $magazine["image"],
                            "isBookmarked" => "Y",
                            "title" => $magazine["title"],
                            "landing_page" => $magazine["landing_page"],
                            "datePublished" => date("M Y",strtotime($magazine["issue_date"]." 00:00:00"))
                        );
				}
            } else {
                        $rMagazines[] = array(
                            "magazineId" => $magazine["id"],
                            "magazinePreviewURL" => $magazine["preview_link"],
                            //"magazineDownloadURL" => ($auth == 0 ? "hidden" : $magazine["download_link"]),
                            //"magazineDownloadURL" => ($isAccessible >= 0 ? "https://www.steelmint.com/app_webview_pages/unauthorised_action.php" : $magazine["download_link"]),
							"magazineDownloadURL" => ($isAccessible >= 0 ? "hidden" : $magazine["download_link"]),
                            "thumbImageURL" => $magazine["thumb_image"],
                            "imageURL" => $magazine["image"],
                            "isBookmarked" => in_array($magazine["id"],$bookmark_array)?"Y":"N",
                            "title" => $magazine["title"],
							 "landing_page" => $magazine["landing_page"],
                            "datePublished" => date("M Y",strtotime($magazine["issue_date"]." 00:00:00"))
            );
           }
        }
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg 
            ],
			'data' => $rMagazines
        ]);
    }
}
