<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Album;
use App\Models\AlbumCategory;
use App\Supports\Response;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

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

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

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

        //置頂影音
        $topVideos = Album::where("visible", 1)->where("on_top", 1)->orderBy("order")->orderByDesc("post_date")->get();
        foreach($topVideos as $topVideo){
            $result["top"][] = [
                "id" => $topVideo->id,
                "categoryId" => $topVideo->albumCategory->id,
                "category" => $topVideo->albumCategory->getTranslation("name", $locate),
                "postDate" => Carbon::parse($topVideo->post_date)->format("Y/m/d"),
                "title" => $topVideo->getTranslation("title", $locate),
                "imgBanner" => $topVideo->album_img_banner_url,
                "imgPC" => $topVideo->album_img_pc_url,
                "imgMobile" => $topVideo->album_img_mobile_url,
                "type" => $topVideo->album_upload_type,
                "link" => $topVideo->album_video_link,
            ];
        }

        //分類列表
        $categoryList = AlbumCategory::orderByDesc('order')->orderByDesc('id')->get();
        foreach($categoryList as $listItem){
            $result["categoryList"][] = [
                "id" => $listItem->id,
                "name" => $listItem->getTranslation("name", $locate),
            ];
        }

        //影音列表
        $albums = Album::where("visible", 1);
        if($categoryId){
            $albums->where("album_category_id", $categoryId);
        }
        $albums = $albums->orderByDesc("order")->orderByDesc("post_date")->get();
        foreach($albums as $item){
            $result["list"][] = [
                "id" => $item->id,
                "categoryId" => $item->albumCategory->id,
                "category" => $item->albumCategory->getTranslation("name", $locate),
                "postDate" => Carbon::parse($item->post_date)->format("Y/m/d"),
                "title" => $item->getTranslation("title", $locate),
                "imgBanner" => $item->album_img_banner_url,
                "imgPC" => $item->album_img_pc_url,
                "imgMobile" => $item->album_img_mobile_url,
                "type" => $item->album_upload_type,
                "link" => $item->album_video_link,
            ];
        }
        return Response::ok($result);
    }
}
