<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\EsgHistory;
use App\Models\UploadFile;
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 EsgController extends Controller
{
    public function __construct()
    {
    }

    public function histories($locale = 'tw')
    {
        $locale = $locale == "tw" ? "zh_TW" : $locale;
        $data = EsgHistory::where("visible", 1)->orderByDesc("selected_year", "desc")->orderByDesc("selected_month")->get();
        $yearList = EsgHistory::select("selected_year", \DB::raw("concat(selected_year, '年') as lable"))->distinct()->orderBy("selected_year", "desc")->pluck('lable', 'selected_year');
        $result = [];
        $result["yearList"] = $yearList;
        foreach ($data as $item) {
            $result["list"][$item->selected_year][] = [
                "operateMonth " => $item->selected_year . "." . str_pad($item->selected_month, 2, "0", STR_PAD_LEFT),
                "title" => $item->getTranslation("title", $locale),
                "description" => $item->getTranslation("description", $locale)
            ];
        }
        return Response::ok($result);
    }

    public function uploadFiles($locale = "tw")
    {
        $locale = $locale == "tw" ? "zh_TW" : $locale;

        // 定義「取得時間」的翻譯
        $awardDateLabels = [
            'zh_TW' => '取得時間',
            'en' => 'Awarded',
        ];

        // 取得對應的標籤，如果找不到則使用預設值
        $awardDateLabel = $awardDateLabels[$locale] ?? $awardDateLabels['zh_TW'];

        $request_ordering = $request->ordering ?? "desc";
        $fileList = UploadFile::where("type", 1)
            ->select("title", "upload_link", "award_date")
            ->orderBy("award_date", $request_ordering)
            ->orderBy("order", $request_ordering)->get()->map(function ($record) use ($awardDateLabel, $locale) {
                return [
                    "title" => $record->getTranslation("title", $locale),
                    "uploadLink" => $record->upload_file_link,
                    "awardDate" => $awardDateLabel . " : " . date("Y/m/d", strtotime($record->award_date))
                ];
            });
        return Response::ok($fileList);
    }
}
