<?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;

class Report extends Controller
{
    public function getReport(Request $request)
    {
        $data = json_decode($request->getContent(), true);
        /*$data["pageNumber"] = $request->input("pageNumber");
        $data["authorId"] = $request->input("authorId");
        $data['memId'] = $request->input("memId");
        $data['accessToken'] = $request->input("accessToken");
        $data['filters'] = $request->input("filter");*/
        $validator = Validator::make($data, [
//            'filters.type' => ['required', new ReportType],
            'pageNumber' => 'required|int',
            'authorId' => 'int',
        ]);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return response()->json([
                'status' => [
                    "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                    'message' => $messages
                ]
            ]);
        }
        $hasToken = 0;
        if (isset($data['memId']) || isset($data['accessToken'])) {
            if (!empty($data['accessToken']) && !empty($data['memId'])) {
                $hasToken = \App\Token::select('*')->where('token', $data['accessToken'])->where('id', $data['memId'])->first();
                if (empty($hasToken)) {
                    return \App\Helper::invalidAuthentication();
                }
            } else if (empty($data['accessToken']) || !empty($data['memId'])) {
                $hasToken = \App\Token::select('*')->where('id', $data['memId'])->first();
                if (empty($hasToken)) {
                    return \App\Helper::invalidAuthentication();
                }
            } else if (!empty($data['accessToken']) || empty($data['memId'])) {
                $hasToken = \App\Token::select('*')->where('token', $data['accessToken'])->first();
                if (empty($hasToken)) {
                    return \App\Helper::invalidAuthentication();
                }
            }
        }

        $auth = (!empty($hasToken) ? 1 : 0);
        $commodityIDs = $regionIDs = [];
        $filters = (isset($data['filters'])?$data['filters']:[]);
        if (isset($filters['commodityIDs'])) {
            $commodityIDs = $filters['commodityIDs'];
        }

        if (isset($filters['regionIDs'])) {
            $regionIDs = $filters['regionIDs'];
        }

        $authorId = "";
        if (isset($filters['authorId'])) {
            $authorId = $filters['authorId'];
        }

        $type = "";
        if (isset($filters['type'])) {
            if ($filters['type'] == "special") {
                $type = "s";
            } else if ($filters['type'] == "premium") {
                $type = "p";
            } else if ($filters['type'] == "regular") {
                $type = "r";
            }
        }
        $page = (isset($data['pageNumber']) ? $data['pageNumber'] : 1);
        $limit = 4;
        $filters = [
            'tbl_steelreports_category.commodity' => $commodityIDs,
            'tbl_steelreports_category.region' => $regionIDs,
            'tbl_steelreport.author_id' => $authorId,
            'tbl_steelreport.f_special_regular' => $type,
        ];
        //DB::enableQueryLog();
        $salesReport = DB::table('tbl_steelreport')
            ->leftJoin('tbl_steelreports_category', 'tbl_steelreport.category', '=', 'tbl_steelreports_category.category')
            ->leftJoin('tbl_rel_manager', 'tbl_steelreport.author_id', '=', 'tbl_rel_manager.id')
            ->select('tbl_steelreport.*', 'tbl_steelreport.id as reportId', 'tbl_steelreports_category.timeToRead', 'tbl_steelreports_category.report', 'tbl_steelreports_category.thumbnail', 'tbl_steelreports_category.thumbnail', 'tbl_steelreports_category.title', 'tbl_steelreports_category.id as categoryId', 'tbl_steelreports_category.f_special_regular', 'tbl_rel_manager.*')
            ->where(function ($query) use ($filters) {
                foreach ($filters as $column => $key) {
                    if ($column == 'tbl_steelreports_category.commodity' && !empty($key)) {
                        $query->whereIn('tbl_steelreports_category.commodity', $key);
                    }
                    if ($column == 'tbl_steelreports_category.region' && !empty($key)) {
                        $query->whereIn('tbl_steelreports_category.region', $key);
                    }
                    if ($column == 'tbl_steelreport.author_id' && !empty($key)) {
                        $query->where('tbl_steelreport.author_id', $key);
                    }
                    if ($column == 'tbl_steelreport.f_special_regular' && !empty($key)) {
                        $query->where('tbl_steelreports_category.f_special_regular', $key);
                    }
                }
            })
            ->limit($limit)->offset(($page - 1) * $limit)
            ->groupBy('tbl_steelreports_category.category')
            ->orderBy('tbl_steelreport.id','desc')
            ->get();//dd(DB::getQueryLog());
        $rArr = [];
        foreach ($salesReport as $report) {
            print_r($report);
            $bookmark = 0;
            if ($auth) {
                $bookmark = DB::table('tbl_bookmarks')
                    ->where('section', 'report')
                    ->where('item_id', $report->id)
                    ->count();
            }
            $f_special_regular = "";
            if ($report->f_special_regular == "r") {
                $f_special_regular = "regular";
            } else if ($report->f_special_regular == "s") {
                $f_special_regular = "special";
            } else if ($report->f_special_regular == "kc") {
                $f_special_regular = "knowledge center";
            }
            $author = DB::table('tbl_rel_manager')
                ->select('*')
                ->where('id', $report->author_id)
                ->first();
            $portfolio = DB::table('tbl_user_portfolio')
                ->where('id', $report->id)
                ->where('type', 'report')
                ->count();
            $rArr[] = array(
                "itemID" => $report->categoryId,
                "reportID" => $report->reportId,
                "coverImageURL" => $report->thumbnail,
                "title" => $report->title,
                "datePublished" => date("Y-m-d", strtotime($report->date)),
                "timeToRead" => (isset($report->timeToRead) ? $report->timeToRead : ""),
                "mainFileUrl" =>($auth == 0 ? "hidden" : $report->file ),
                "sampleFileURL" => (isset($report->sampleFileURL) ? $report->sampleFileURL : ""),
                "typeOfReport" => $f_special_regular,
                "description" => $report->report,
                "isBookmarked" => ($auth > 0 ? ($bookmark > 0 ? "Y" : "N") : "N"),
                "isAddedToPortfolio" =>($auth > 0 ? ($portfolio > 0 ? "Y" : "N") : "N"),
                "authorDetails" => [
                    "authorId" => (!empty($author) ? $author->id : ""),
                    "imageURL" => (!empty($author) ? $author->imageURL : ""),
                    "name" => (!empty($author) ? $author->RM_name : ""),
                    "emailId" => (!empty($author) ? $author->RM_email : ""),
                    "socialAccounts" => [
                        "fb" => (!empty($author) ? $author->facebookId : ""),
                        "twitter" => (!empty($author) ? $author->twitterId : ""),
                    ],
                    "description" => (!empty($author) ? $author->details : "")
                ],
            );
        }

        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
                'message' => \App\RestApiResponseCodes::RequestSentSuccessfullyMsg,
                'data' => $rArr
            ]
        ]);
    }
}
