<?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)
    {
        $q = \DB::table('seal as s')
            ->leftJoin('park as p','s.park_id','=','p.park_id')
            ->leftJoin('regular_contract as rc','s.contract_id','=','rc.contract_id')
            ->leftJoin('psection as ps','rc.psection_id','=','ps.psection_id')
            ->select([
                's.seal_issueid',
                's.park_id',
                'p.park_name',
                's.contract_id',
                'rc.psection_id',
                \DB::raw('ps.psection_subject AS psection_subject'),
                'rc.contract_seal_issue',
                's.seal_day',
                's.seal_reason',
            ]);

        // 駐輪場フィルタ
        if($request->filled('park_id')){
            $q->where('s.park_id',$request->park_id);
        }

        // 期間フィルタ
        $periodType = $request->input('period_type','range');
        if($periodType === 'range'){
            if($request->filled('seal_day_from')){
                $q->whereDate('s.seal_day','>=',$request->seal_day_from);
            }
            if($request->filled('seal_day_to')){
                $q->whereDate('s.seal_day','<=',$request->seal_day_to);
            }
        } elseif($periodType === 'recent' && $request->filled('recent_period')){
            $map = ['12m'=>12,'6m'=>6,'3m'=>3,'2m'=>2,'1m'=>1,'1w'=>'1w'];
            $key = $request->recent_period;
            if(isset($map[$key])){
                $from = $key==='1w' ? now()->subWeek() : now()->subMonths($map[$key]);
                $q->where('s.seal_day','>=',$from->toDateString());
            }
        }

        // --- 並び替え: パラメータがある場合のみ適用 ---
        $sort     = $request->query('sort');              // デフォルト null
        $sortType = $request->query('sort_type','asc');   // 指定なければ asc
        $allow = [
            'seal_issueid'        => 's.seal_issueid',
            'park_id'             => 'p.park_name',
            'contract_id'         => 's.contract_id',
            'seal_day'            => 's.seal_day',
            'contract_seal_issue' => 'rc.contract_seal_issue',
            'psection_subject'    => 'ps.psection_subject',
        ];
        if(isset($allow[$sort])){
            $sortType = $sortType === 'desc' ? 'desc' : 'asc';
            $q->orderBy($allow[$sort], $sortType);
        }
        // 並び替え指定が無い時は orderBy 不要 → DB の物理(主キー)順

        $list = $q->paginate(20)->appends($request->query());

        $parks = \DB::table('park')
            ->select('park_id','park_name')
            ->orderBy('park_name')
            ->get();

        return view('admin.seals.list', compact('list','parks','sort','sortType'));
    }
}