<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\News;
use App\Models\NewsCategory;
use App\Supports\Response;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Helper\Helper;

/**
 * @group Lottery Prize
 */
class NewsController extends Controller
{
    public function __construct(
    )
    {
    }

    public function list(Request $request, $locate = 'tw')
    {
        $page = $request->input("page", 1);
        $per_page = $request->input("per_page", 15);
        $year = $request->input("year", -1);
        $month = $request->input("month", -1);
        $locate = $locate == "tw" ? "zh_TW" : $locate;
        $result = [];
        
        $dateFilter = Carbon::now();
        $now = Carbon::now(); 

        //文章列表
        $news = News::where("visible", 1);
        if($month > 0 || $year > 0){
            
            if($year > 0){
                $dateFilter->setYear(intval($year));
                if($month > 0){
                    $dateFilter->setMonth(intval($month));
                    $news = $news->whereBetween("post_date", [$dateFilter->copy()->startOfMonth(), $dateFilter->copy()->endOfMonth()]);
                }else{
                    $news = $news->whereBetween("post_date", [$dateFilter->copy()->startOfYear(), $dateFilter->copy()->endOfYear()]);
                }
                
            }
        }

        $news = $news->where(fn($q) =>
            $q->whereNull('start_date')
            ->orWhere('start_date', '<=', $now)
        )->where(fn($q) =>
            $q->whereNull('end_date')
            ->orWhere('end_date', '>=', $now)
        );

        $news = $news->orderByDesc("order")->orderByDesc("post_date");
        $result["pagination"] = [
            "page" => $page,
            "per_page" => $per_page
        ];
        if($per_page == -1){
            $news = $news->get();
            $result["pagination"]["total"] = $news->count();
            $result["pagination"]["total_page"] =1;
        }else{
            $news = $news->paginate($per_page, ['*'], 'page', $page);
            $result["pagination"]["total"] = $news->total();
            $result["pagination"]["total_page"] =$news->lastPage();

        }
        $result["list"] = [];
        foreach($news as $item){
            $result["list"][] = [
                "id" => $item->id,
                "categoryId" => $item->newsCategory->id,
                "category" => $item->newsCategory->getTranslation("name", $locate, false),
                "postDate" => Carbon::parse($item->post_date)->format("Y.m.d"),
                "title" => $item->getTranslation("title", $locate, false),
                "imgPC" => $item->news_img_pc_url,
                "imgMobile" => $item->news_img_mobile_url,
                "written" => $item->getTranslation("written_by", $locate, false),
                "description" => $item->getTranslation("description", $locate, false),
            ];
        }
        return response()->json(["data" => $result], 200);
    }

    public function getTop(Request $request, $locate = 'tw')
    {
        $categoryId = $request->input("categoryId", "");
        $locate = $locate == "tw" ? "zh_TW" : $locate;
        $result = [];

        //年份清單
        $yearList = News::select(DB::raw("DATE_FORMAT(post_date, '%Y/%m') as years"))->distinct()->orderBy("years", "desc")->pluck("years");

        //文章列表
        $news = News::where("visible", 1)->where('on_top', 1)->first();
        if($news)
        $result["data"] = [
            "meta" => [
                "meta_title" => $news->getTranslation("meta_title", $locate, false),
                "meta_keyword" => $news->getTranslation("meta_keyword", $locate, false),
                "meta_description" => $news->getTranslation("meta_description", $locate, false),
                "imgPC" => $news->news_meta_img,
            ],
            "yearList" => $yearList,
            "top" => [
                "id" => $news->id,
                "categoryId" => $news->newsCategory->id,
                "category" => $news->newsCategory->getTranslation("name", $locate, false),
                "postDate" => Carbon::parse($news->post_date)->format("Y/m/d"),
                "title" => $news->getTranslation("title", $locate, false),
                "imgPC" => $news->news_img_pc_url,
                "imgMobile" => $news->news_img_mobile_url,
                "written" => $news->getTranslation("written_by", $locate, false),
                "description" => $news->getTranslation("description", $locate, false),
            ]
        ];
        return response()->json($result, 200);
    }

    public function detail(Request $request, $locale = 'tw', $id){

        $isPreview = $request->input("preview","");
        $now = Carbon::now(); 
        
        if($isPreview){
            $news = News::where('id', $id)
                ->first();
        }else{
            $news = News::where('id', $id)
                ->where("visible", 1)
                ->where(fn($q) =>
                    $q->whereNull('start_date')
                    ->orWhere('start_date', '<=', $now)
                )->where(fn($q) =>
                    $q->whereNull('end_date')
                    ->orWhere('end_date', '>=', $now)
                )
                ->first();
        }


        $locate = $locale == "tw" ? "zh_TW" : $locale;
        
        $otherNewsList = [];
        if(!$news){
            return response()->json([
                'message' => "news not found"], 404);
        }
// dd($news);
        //取得前一篇
        $previous = News::where(function ($query) use ($news, $now) {
            $query->where('order', $news->order)
            ->where('post_date', $news->post_date)
            ->where('id', '>', $news->id)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orWhere(function ($query) use ($news, $now) {
            $query->where('order', $news->order)
            ->where('post_date', '>', $news->post_date)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orWhere(function ($query) use ($news, $now) {
            $query->where('order', '>', $news->order)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orderBy('order', 'asc')
        ->orderBy('post_date', 'asc')
        ->orderBy('id', 'asc')
        ->first();

        //取得下一篇
        $next = News::where(function ($query) use ($news, $now) {
            $query->where('order', $news->order)
            ->where('post_date', $news->post_date)
            ->where('id', '<', $news->id)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orWhere(function ($query) use ($news, $now) {
            $query->where('order', $news->order)
            ->where('post_date', '<', $news->post_date)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orWhere(function ($query) use ($news, $now) {
            $query->where('order', '<', $news->order)
            ->where("visible", 1)
            ->where(fn($q) => $q->whereNull('start_date')->orWhere('start_date', '<=', $now))
            ->where(fn($q) => $q->whereNull('end_date')->orWhere('end_date', '>=', $now));
        })
        ->orderBy('order', 'desc')
        ->orderBy('post_date', 'desc')
        ->orderBy('id', 'desc')
        ->first();

        if($previous)$otherNewsList["previous"] = [
            "id" => $previous->id,
            "categoryId" => $previous->newsCategory->id,
            "category" => $previous->newsCategory->getTranslation("name", $locate, false),
            "postDate" => Carbon::parse($previous->post_date)->format("Y/m/d"),
            "title" => $previous->getTranslation("title", $locate, false),
            "imgPC" => $previous->news_img_pc_url,
            "imgMobile" => $previous->news_img_mobile_url,
            "written" => $previous->getTranslation("written_by", $locate, false),
            "description" => $previous->getTranslation("description", $locate, false),
        ];
        if($next)$otherNewsList["next"] = [
            "id" => $next->id,
            "categoryId" => $next->newsCategory->id,
            "category" => $next->newsCategory->getTranslation("name", $locate, false),
            "postDate" => Carbon::parse($next->post_date)->format("Y/m/d"),
            "title" => $next->getTranslation("title", $locate, false),
            "imgPC" => $next->news_img_pc_url,
            "imgMobile" => $next->news_img_mobile_url,
            "written" => $next->getTranslation("written_by", $locate, false),
            "description" => $next->getTranslation("description", $locate, false),
        ];

        $paragraphs = [];
        foreach($news->paragraphs as $paragraph){
            $content = [];
            switch ($paragraph->contentType()){
                case "text":
                    $paragraphs[] = [
                        "type" => $paragraph->contentType(),
                        "content" => nl2br($paragraph->getTextContent($locate)),
                    ];
                    break;
                case "image":
                    $photos = $paragraph->photos;
                    $images = [];
                    foreach($photos as $photo){
                        $images[] = ["img_url" => $photo->news_photo_img, "alt" => $photo->getTranslation("image_alt", $locate, false)];
                    }
                    $paragraphs[] = [
                        "type" => $paragraph->contentType(),
                        "images" => $images,
                    ];
                    break;
                case "video":
                    $paragraphs[] = [
                        "type" => $paragraph->contentType(),
                        "video_img_url" => $paragraph->paragraph_video_img,
                        "is_yt" => $paragraph->video_type == 1 ? true : false,
                        "content" => $paragraph->getTranslation("video_img_alt", $locate, false),
                        "video_url" => $paragraph->getTranslation("link", $locate, false),
                    ];
                    break;
            }
        }
        $result = [
            "categoryId" => $news->newsCategory->id,
            "category" => $news->newsCategory->getTranslation("name", $locate, false),
            "postDate" => Carbon::parse($news->post_date)->format("Y/m/d"),
            "title" => $news->getTranslation("title", $locate, false),
            "description" => $news->getTranslation("description", $locate, false),
            "written" => $news->getTranslation("written_by", $locate, false),
            "imgPC" => $news->news_img_pc_url,
            "imgMobile" => $news->news_img_mobile_url,
            "metaTitle" => $news->getTranslation("meta_title", $locate, false),
            "metaKeyword" => $news->getTranslation("meta_keyword", $locate, false),
            "metaDesc" => $news->getTranslation("meta_description", $locate, false),
            "metaImg" => $news->meta_img,
            "paragraphs" => $paragraphs
        ];
        if(!empty($otherNewsList)) $result["otherNews"] = $otherNewsList;
        return response()->json(["data" => $result], 200);
    }
}
