<?php

namespace App\Http\Controllers\Service;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Controller;

/*
 * 한국천문연구원_특일 정보
 * https://www.data.go.kr/data/15012690/openapi.do
 */
class AnniversaryController extends Controller
{
    const API_KEY = 'vQz8tIxrdhjerG6DE1w1hcVEli5S27LtIsCvx0axiieZmRgOpB4vToQ77VmvknAkIC9YjxlPx2gDZcl06S88Xw==';
    const API_HOST = 'http://apis.data.go.kr/B090041/openapi/service/SpcdeInfoService';
    const OPERATION = [
        1 => 'getHoliDeInfo', // 국경일
        2 => 'getRestDeInfo', // 공휴일
        3 => 'getAnniversaryInfo', // 기념일
        4 => 'get24DivisionsInfo', // 24절기
        5 => 'getSundryDayInfo' // 잡절
    ];

    const MAP_OPERATION = [
        1 => '국경일',
        2 => '공휴일',
        3 => '기념일',
        4 => '24절기',
        5 => '잡절'
    ];

    public function __construct()
    {
        $this->middleware('front');
    }

    /**
     * 공휴일/특일
     * @method GET
     * @see /service/anniversary
     */
    public function index(Request $request)
    {
        $year = $request->get('year', now()->format('Y'));

        $data[] = null;
        foreach(self::OPERATION as $i => $operation) {
            $cacheName = sprintf('anniversary-%d-%d', $year, $i);

            if (!$data[$i] = Cache::get($cacheName)) {
                $response = Http::get(self::API_HOST . DIRECTORY_SEPARATOR . $operation, [
                    'ServiceKey' => self::API_KEY,
                    'solYear' => $year,
                    '_type' => 'json',
                    'numOfRows' => 100
                ]);

                $total = 0;
                $list = null;
                if ($response->ok()) {
                    $response = $response->json('response')['body'];
                    if(($total = $response['totalCount']) > 0) {
                        if($total == 1) {
                            $result = [$response['items']['item']];
                        }else{
                            $result = $response['items']['item'];
                        }
                        foreach($result as $item) {
                            $item['locdate'] = date_format(date_create($item['locdate']), 'Y.m.d');
                            $item['isHoliday'] = ($item['isHoliday'] == 'Y' ? '예' : '아니오');
                            $list[] = $item;
                        }
                    }
                }

                $data[$i] = [
                    'total' => $total,
                    'list' => $list
                ];

                Cache::put($cacheName, $data[$i], CACHE_EXPIRE_TIME);
            }
        }

        return view(layout('service.anniversary.index'), [
            'menuID' => 'anniversary',
            'data' => $data,
            'year' => $year,
            'mapOperation' => self::MAP_OPERATION
        ]);
    }
}
