<?php

namespace App\Http\Controllers\Admin;

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

class SealsController extends Controller
{
    public function list(Request $request)
    {
        // ソート用パラメータ取得（指定がなければnull）
        $sort = $request->input('sort');
        $sort_type = $request->input('sort_type', 'asc');

        // sealテーブルを参照し、フィルター
        $query = DB::table('seal');

        // フィルター：発行日
        $periodType = $request->input('period_type');
        $recentPeriod = $request->input('recent_period');
        $sealDayFrom = $request->input('seal_day_from');
        $sealDayTo = $request->input('seal_day_to');

        if ($periodType === 'range' && $sealDayFrom && $sealDayTo) {
            $query->whereBetween('seal_day', [$sealDayFrom, $sealDayTo]);
        } elseif ($periodType === 'recent' && $recentPeriod) {
            $now = date('Y-m-d');
            switch ($recentPeriod) {
                case '12m':
                    $from = date('Y-m-d', strtotime('-12 months', strtotime($now)));
                    break;
                case '6m':
                    $from = date('Y-m-d', strtotime('-6 months', strtotime($now)));
                    break;
                case '3m':
                    $from = date('Y-m-d', strtotime('-3 months', strtotime($now)));
                    break;
                case '2m':
                    $from = date('Y-m-d', strtotime('-2 months', strtotime($now)));
                    break;
                case '1m':
                    $from = date('Y-m-d', strtotime('-1 months', strtotime($now)));
                    break;
                case '1w':
                    $from = date('Y-m-d', strtotime('-1 week', strtotime($now)));
                    break;
                default:
                    $from = null;
            }
            if (isset($from)) {
                $query->where('seal_day', '>=', $from);
            }
        } else {
            // デフォルト：直近3ヶ月
            $now = date('Y-m-d');
            $from = date('Y-m-d', strtotime('-3 months', strtotime($now)));
            $query->where('seal_day', '>=', $from);
        }

        // ソート指定があればorderBy、なければDB物理順
        if ($sort) {
            $list = $query->orderBy($sort, $sort_type)->paginate(20);
        } else {
            $list = $query->paginate(20);
        }

        return view('admin.seals.list', [
            'list' => $list,
            'sort' => $sort,
            'sort_type' => $sort_type,
        ]);
    }
}