@extends('layouts.app')
@section('content')
@php
function safeCarbonFromDDHM($dd, $hm = '00:00') {
$now = \Carbon\Carbon::now();
if (!$dd || !preg_match('/^\d{1,2}$/', $dd)) return null;
if (!$hm || !preg_match('/^\d{2}:\d{2}$/', $hm)) $hm = '00:00';
$date = $now->format('Y-m-') . str_pad($dd, 2, '0', STR_PAD_LEFT);
$time = $hm . ':00';
try {
return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date . ' ' . $time);
} catch (Exception $e) {
return null;
}
}
@endphp
<main>
    <header class="alert alert-success">
        <h4 class="container">契約更新 > 定期契約を更新する</h4>
    </header>
    <section class="container mt30 mb50">
        @if(count($contracts) > 0)
        @foreach($contracts as $i => $contract)
        @if($i % 2 == 0)
        <div class="row">
            @endif
            <article class="col-12 col-lg-6 mb20">
                @php
                $now = \Carbon\Carbon::now();
                $update_flag = $contract->contract_renewal;
                $start_dd = $contract->update_grace_period_start_date;
                $start_hm = $contract->update_grace_period_start_time;
                $end_dd = $contract->update_grace_period_end_date;
                $end_hm = $contract->update_grace_period_end_time;
                $contract_end_dt = $contract->contract_periode ? \Carbon\Carbon::parse($contract->contract_periode) : null;
                $periode_month = $contract_end_dt ? $contract_end_dt->month : null;
                $periode_year = $contract_end_dt ? $contract_end_dt->year : null;
                $bg = 'alert-warning';
                $btn_text = '更新する';
                $btn_active = true;

                // 契約終了月より前は「ご契約中」
                if ($now->lt($contract_end_dt)) {
                $bg = 'bg-white';
                $btn_text = 'ご契約中';
                $btn_active = false;
                } else {
                // 契約終了月より後は猶予期間判定
                if (is_numeric($start_dd) && is_numeric($end_dd)) {
                // 開始日
                $start_date = $contract_end_dt->format('Y-m-') . str_pad($start_dd, 2, '0', STR_PAD_LEFT);
                $start_time = ($start_hm && preg_match('/^\d{2}:\d{2}$/', $start_hm)) ? $start_hm : '00:00';
                $start_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $start_date . ' ' . $start_time . ':00');
                // 終了日
                if ($start_dd < $end_dd) {
                    $end_date=$contract_end_dt->format('Y-m-') . str_pad($end_dd, 2, '0', STR_PAD_LEFT);
                    $end_time = ($end_hm && preg_match('/^\d{2}:\d{2}$/', $end_hm)) ? $end_hm : '23:59';
                    $end_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $end_date . ' ' . $end_time . ':00');
                    } else {
                    $next_month_dt = $contract_end_dt->copy()->addMonth();
                    $end_date = $next_month_dt->format('Y-m-') . str_pad($end_dd, 2, '0', STR_PAD_LEFT);
                    $end_time = ($end_hm && preg_match('/^\d{2}:\d{2}$/', $end_hm)) ? $end_hm : '23:59';
                    $end_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $end_date . ' ' . $end_time . ':00');
                    }
                    } else {
                    $start_dt = null;
                    $end_dt = null;
                    }
                    // 猶予期間判定
                    if ($update_flag === 0) {
                    $bg = 'bg-white';
                    $btn_text = '手続き中';
                    $btn_active = false;
                    } elseif ($update_flag === 1) {
                    $bg = 'bg-white';
                    $btn_text = '更新済';
                    $btn_active = false;
                    } elseif ($start_dt && $end_dt && $now->between($start_dt, $end_dt)) {
                    // 猶予期間内
                    if ($contract_end_dt && $now->gt($contract_end_dt)) {
                    $bg = 'alert-danger';
                    $btn_text = '更新する';
                    $btn_active = true;
                    } else {
                    $bg = 'alert-warning';
                    $btn_text = '更新する';
                    $btn_active = true;
                    }
                    } else {
                    $bg = 'bg-white';
                    $btn_text = 'ご契約中';
                    $btn_active = false;
                    }
                    }
                    // 契約終了月の場合（既存ロジック）
                    if (is_numeric($start_dd) && is_numeric($end_dd)) {
                    // 開始日
                    $start_date = $contract_end_dt->format('Y-m-') . str_pad($start_dd, 2, '0', STR_PAD_LEFT);
                    $start_time = ($start_hm && preg_match('/^\d{2}:\d{2}$/', $start_hm)) ? $start_hm : '00:00';
                    $start_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $start_date . ' ' . $start_time . ':00');
                    // 終了日
                    if ($start_dd < $end_dd) {
                        $end_date=$contract_end_dt->format('Y-m-') . str_pad($end_dd, 2, '0', STR_PAD_LEFT);
                        $end_time = ($end_hm && preg_match('/^\d{2}:\d{2}$/', $end_hm)) ? $end_hm : '23:59';
                        $end_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $end_date . ' ' . $end_time . ':00');
                        } else {
                        $next_month_dt = $contract_end_dt->copy()->addMonth();
                        $end_date = $next_month_dt->format('Y-m-') . str_pad($end_dd, 2, '0', STR_PAD_LEFT);
                        $end_time = ($end_hm && preg_match('/^\d{2}:\d{2}$/', $end_hm)) ? $end_hm : '23:59';
                        $end_dt = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $end_date . ' ' . $end_time . ':00');
                        }
                        } else {
                        $start_dt = null;
                        $end_dt = null;
                        }
                        // 以降は既存のボタン・背景色判定ロジック
                        if ($update_flag===0) {
                        $bg='bg-white';
                        $btn_text='手続き中';
                        $btn_active=false;
                        }
                        elseif ($update_flag===1) {
                        $bg='bg-white';
                        $btn_text='更新済';
                        $btn_active=false;
                        }
                        elseif (!is_null($end_dt) && $end_dt->gt($start_dt)) {
                        if ($start_dt && $now->lt($start_dt)) {
                        $bg = 'bg-white';
                        $btn_text = 'ご契約中';
                        $btn_active = false;
                        } else {
                        // 契約終了日を過ぎていて、更新可能期間内は赤背景
                        if ($contract_end_dt && $now->gt($contract_end_dt) && $start_dt && $end_dt && $now->between($start_dt, $end_dt)) {
                        $bg = 'alert-danger';
                        $btn_text = '更新する';
                        $btn_active = true;
                        } else {
                        $bg = 'alert-warning';
                        $btn_text = '更新する';
                        $btn_active = true;
                        }
                        }
                        }
                        elseif ($start_dt && $start_dt->gt($end_dt)) {
                        if ($now->lt($start_dt)) {
                        $bg = 'bg-white';
                        $btn_text = 'ご契約中';
                        $btn_active = false;
                        } elseif ($now->gte($start_dt) && $now->lte($contract_end_dt->copy()->endOfMonth())) {
                        $bg = 'alert-warning';
                        $btn_text = '更新する';
                        $btn_active = true;
                        } else {
                        $bg = 'alert-danger';
                        $btn_text = '更新する';
                        $btn_active = true;
                        }
                        }
                        @endphp
                        @if($bg == 'bg-white')
                        <div class="card border-success">
                            @elseif($bg == 'alert-warning')
                            <div class="card alert-warning">
                                @elseif($bg == 'alert-danger')
                                <div class="card alert-danger">
                                    @else
                                    <div class="card">
                                        @endif
                                        <style>
                                            .table.text-center {
                                                border-radius: 0.25rem !important;
                                                border-collapse: separate !important;
                                                overflow: hidden;
                                            }

                                            .btn-outline-secondary.badge-pill.custom-rounded-btn[disabled],
                                            .btn-outline-secondary.badge-pill.custom-rounded-btn.disabled {
                                                pointer-events: none;
                                                cursor: default !important;
                                                background: #fff !important;
                                                color: #6c757d !important;
                                                border-color: #6c757d !important;
                                                opacity: 1 !important;
                                            }

                                            .btn-outline-secondary.badge-pill.custom-rounded-btn:not([disabled]):hover,
                                            .btn-outline-secondary.badge-pill.custom-rounded-btn:not(.disabled):hover {
                                                color: #212529 !important;
                                            }

                                            .border-warning {
                                                border: 1px solid #ffc107 !important;
                                            }

                                            .border-white {
                                                border: 1px solid #fff !important;
                                            }

                                            .border-danger {
                                                border: 1px solid #dc3545 !important;
                                            }

                                            .table-no-margin {
                                                margin-bottom: 0 !important;
                                                padding-bottom: 0 !important;
                                            }
                                        </style>
                                        <table class="table text-center table-no-margin {{ $bg }}
                        @if($bg == 'alert-warning') border-warning
                        @elseif($bg == 'bg-white') border-white
                        @elseif($bg == 'alert-danger') border-danger
                        @endif">
                                            <tr>
                                                <th>定期契約ID</th>
                                                <td>{{ $contract->contract_id }}</td>
                                            </tr>
                                            <tr>
                                                <th>駐輪場名</th>
                                                <td>{{ $contract->park_name }}</td>
                                            </tr>
                                            <tr>
                                                <th>利用者区分</th>
                                                <td>{{ $contract->usertype_subject1 }}</td>
                                            </tr>
                                            <tr>
                                                <th>利用開始日</th>
                                                <td>{{ \Carbon\Carbon::parse($contract->contract_periods)->format('Y/m/d') }}</td>
                                            </tr>
                                            <tr>
                                                <th>契約月数</th>
                                                <td>{{ $contract->enable_months }}ヶ月</td>
                                            </tr>
                                            <tr>
                                                <td colspan="2" class="text-center">
                                                    <div style="display: flex; flex-direction: column; align-items: center;">
                                                        <div style="display: flex; gap: 6px; margin-bottom: 12px;">
                                                            @if($bg == 'alert-warning' && $btn_active)
                                                            <a href="{{ url('regular_contract/update/' . $contract->contract_id) }}" class="btn btn-warning badge-pill custom-rounded-btn">{{ $btn_text }}</a>
                                                            @elseif($bg == 'alert-danger' && $btn_active)
                                                            <a href="{{ url('regular_contract/update/' . $contract->contract_id) }}" class="btn btn-danger badge-pill custom-rounded-btn">{{ $btn_text }}</a>
                                                            @else
                                                            <button type="button" class="btn btn-outline-secondary badge-pill custom-rounded-btn" disabled>{{ $btn_text }}</button>
                                                            @endif
                                                            @if($bg == 'alert-warning')
                                                            <button type="button" id="cancelModalBtn" class="btn btn-outline-warning badge-pill custom-rounded-btn" style="background: transparent;" data-bs-toggle="modal" data-bs-target="#cancelModal">解約について</button>
                                                            @elseif($bg == 'alert-danger')
                                                            <button type="button" id="cancelModalBtn" class="btn btn-outline-danger badge-pill custom-rounded-btn" style="background: transparent;" data-bs-toggle="modal" data-bs-target="#cancelModal">解約について</button>
                                                            @else
                                                            <button type="button" id="cancelModalBtn" class="btn btn-outline-secondary badge-pill custom-rounded-btn" style="background: transparent;" data-bs-toggle="modal" data-bs-target="#cancelModal">解約について</button>
                                                            @endif
                                                        </div>
                                                        @php
                                                        $has_receipt = DB::table('inv_publish')->where('contract_id', $contract->contract_id)->exists();
                                                        @endphp
                                                        @if($has_receipt)
                                                        @if($bg == 'alert-warning')
                                                        <a href="{{ url('receipt/download/' . $contract->contract_id) }}" class="btn btn-outline-warning badge-pill custom-rounded-btn" style="background: transparent;">領収書再発行</a>
                                                        @elseif($bg == 'alert-danger')
                                                        <a href="{{ url('receipt/download/' . $contract->contract_id) }}" class="btn btn-outline-danger badge-pill custom-rounded-btn" style="background: transparent;">領収書再発行</a>
                                                        @else
                                                        <a href="{{ url('receipt/download/' . $contract->contract_id) }}" class="btn btn-outline-secondary badge-pill custom-rounded-btn" style="background: transparent;">領収書再発行</a>
                                                        @endif
                                                        @else
                                                        @if($bg == 'alert-warning')
                                                        <a href="{{ url('receipt/input/' . $contract->contract_id) }}" class="btn btn-outline-warning badge-pill custom-rounded-btn" style="background: transparent;">領収書発行</a>
                                                        @elseif($bg == 'alert-danger')
                                                        <a href="{{ url('receipt/input/' . $contract->contract_id) }}" class="btn btn-outline-danger badge-pill custom-rounded-btn" style="background: transparent;">領収書発行</a>
                                                        @else
                                                        <a href="{{ url('receipt/input/' . $contract->contract_id) }}" class="btn btn-outline-secondary badge-pill custom-rounded-btn" style="background: transparent;">領収書発行</a>
                                                        @endif
                                                        @endif
                                                    </div>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
            </article>
            @if($i % 2 == 1 || $i == count($contracts) - 1)
        </div>
        @endif
        @endforeach
        @else
        <div class="col-12 col-lg-12 mb20">
            <p>定期契約情報はありません。</p>
        </div>
        @endif
        {{-- modal moved to end of file to avoid clipping issues --}}
        <form class="row form">
            <div class="col-12 col-md-4 offset-0 offset-md-4 mt50 mb50">
                <a href="{{ url('mypage') }}" class="btn btn-lg btn-block btn-outline-success">マイページへ戻る</a>
            </div>
        </form>
    </section>
</main>

<!-- 解約についてモーダル -->
<div class="modal fade" id="cancelModal" tabindex="-1" aria-labelledby="cancelModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                解約の手続きにつきましては、下記コールセンターへお問い合わせください。<br>So-Managerコールセンター<br>03-5856-4720
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">閉じる</button>
            </div>
        </div>
    </div>
</div>
<style>
    .custom-rounded-btn {
        border-radius: 2rem !important;
        padding-left: 2rem !important;
        padding-right: 2rem !important;
        min-width: 140px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    }
</style>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
@endsection