<?php

namespace App\Http\Controllers\Admin;

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

class UpdateCandidateController extends Controller
{
    /**
     * 更新予定者一覧表示
     */
    public function list(Request $request)
    {
        $q = DB::table('regular_contract as rc')
            ->leftJoin('user as u','rc.user_id','=','u.user_id')
            ->leftJoin('park as p','rc.park_id','=','p.park_id')
            ->leftJoin('psection as ps','rc.psection_id','=','ps.psection_id')
            ->leftJoin('usertype as ut','u.user_categoryid','=','ut.user_categoryid')
            ->select([
                'rc.contract_id',
                'rc.user_id',
                'rc.park_id',
                'rc.contract_created_at',
                'rc.contract_periods',
                'rc.contract_periode',
                'rc.tag_qr_flag',
                'rc.contract_cancel_flag',
                'rc.contract_permission',
                'u.user_name',
                'u.user_phonetic',
                'u.user_mobile',
                'u.user_homephone',
                'u.user_birthdate',
                'u.user_gender',
                'u.user_regident_zip',
                'u.user_regident_pre',
                'u.user_regident_city',
                'u.user_regident_add',
                'u.user_relate_zip',
                'u.user_relate_pre',
                'u.user_relate_city',
                'u.user_relate_add',
                'u.user_workplace',
                'u.user_school',
                'u.user_graduate',
                'u.user_reduction',
                'u.user_remarks',
                'p.park_name',
                DB::raw('ps.psection_subject as vehicle_type'),
                DB::raw('ut.usertype_subject1 as user_category1'),
                DB::raw('ut.usertype_subject2 as user_category2'),
                DB::raw('ut.usertype_subject3 as user_category3'),
                DB::raw('rc.contract_seal_issue as seal_issue_count'),
                DB::raw('rc.user_securitynum as crime_prevention'),
                DB::raw("CASE rc.enable_months
                          WHEN 1 THEN '月極(1ヶ月)'
                          WHEN 3 THEN '3ヶ月'
                          WHEN 6 THEN '6ヶ月'
                          WHEN 12 THEN '年'
                          ELSE CONCAT(rc.enable_months,'ヶ月') END as ticket_type"),
            ])
            ->where('rc.contract_cancel_flag',0)
            ->where('rc.contract_permission',1)
            // 追加: 本日以降が有効期限のレコードのみ
            ->whereDate('rc.contract_periode','>=', now()->toDateString());

        // 絞り込み
        if ($request->filled('park_id')) {
            $q->where('rc.park_id', $request->park_id);
        }
        if ($request->filled('user_id')) {
            $q->where('rc.user_id', trim($request->user_id));
        }
        // 分類名1 完全一致
        if ($request->filled('user_category1')) {
            $val = trim(mb_convert_kana($request->user_category1,'asKV'));
            $q->where('ut.usertype_subject1', $val);
        }
        // タグシリアル64進 部分一致 (SELECT 不要)
        if ($request->filled('user_tag_serial_64')) {
            $q->where('u.user_tag_serial_64','like','%'.$request->user_tag_serial_64.'%');
        }
        // 有効期限：指定日以前
        if ($request->filled('contract_periode')) {
            $raw = str_replace('/','-',$request->contract_periode);
            try {
                $target = \Carbon\Carbon::parse($raw)->format('Y-m-d');
                $q->whereDate('rc.contract_periode','<=',$target);
            } catch (\Exception $e) {}
        }
        if ($request->filled('user_phonetic')) {
            $q->where('u.user_phonetic','like','%'.$request->user_phonetic.'%');
        }
        if ($request->filled('user_mobile')) {
            $like = '%'.$request->user_mobile.'%';
            $q->where(function($w) use ($like){
                $w->where('u.user_mobile','like',$like)
                  ->orWhere('u.user_homephone','like',$like);
            });
        }
        if ($request->filled('user_primemail')) {
            $like = '%'.$request->user_primemail.'%';
            $q->where(function($w) use ($like){
                $w->where('u.user_primemail','like',$like)
                  ->orWhere('u.user_submail','like',$like);
            });
        }
        if ($request->filled('user_workplace')) {
            $q->where('u.user_workplace','like','%'.$request->user_workplace.'%');
        }
        if ($request->filled('user_school')) {
            $q->where('u.user_school','like','%'.$request->user_school.'%');
        }
        if ($request->filled('tag_qr_flag') && $request->tag_qr_flag!=='') {
            $q->where('rc.tag_qr_flag',$request->tag_qr_flag);
        }

        // 対象月
        $target = $request->input('target_month');
        if (in_array($target,['last','this','next','after2'],true)) {
            $base = now()->startOfMonth();
            $offset = ['last'=>-1,'this'=>0,'next'=>1,'after2'=>2][$target];
            $m = $base->copy()->addMonths($offset);
            if ($target === 'after2') {
                // 2か月後「以降」を抽出（該当月の月初以降）
                $q->whereDate('rc.contract_periode', '>=', $m->toDateString());
            } else {
                $q->whereYear('rc.contract_periode',$m->year)
                  ->whereMonth('rc.contract_periode',$m->month);
            }
        }

        // ソート（regular_contract の表示順に合わせて contract_id の降順を既定に）
        $sort = $request->input('sort','contract_id');
        $sortType = $request->input('sort_type','dac');
        $allow = [
            'contract_id'      => 'rc.contract_id',
            'user_id'          => 'rc.user_id',
            'contract_periode' => 'rc.contract_periode',
        ];
        if (!isset($allow[$sort])) $sort = 'contract_id';
        $sortType = $sortType==='desc' ? 'desc' : 'asc';
        $q->orderBy($allow[$sort], $sortType);

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

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

        return view('admin.update_candidate.list',
            compact('rows','parks'));
    }
}
