@extends('layouts.app')

@section('content')
    <div id="page-container" class="fade page-sidebar-fixed page-header-fixed page-with-wide-sidebar">
        @include('partials.header')
        @include('partials.sidebar')

        <div id="content" class="content">
            <ol class="breadcrumb float-xl-right">
                <li class="breadcrumb-item"><a href="javascript:;">Home</a></li>
                <li class="breadcrumb-item"><a href="{{ route('welcome_greetings.index') }}">Welcome Greetings</a></li>
                <li class="breadcrumb-item active">Edit</li>
            </ol>

            <h1 class="page-header">Edit Welcome Greeting</h1>

            <div class="panel panel-inverse">
                <div class="panel-heading">
                    <h4 class="panel-title">Edit Details Welcome Greeting</h4>
                </div>
                <div class="panel-body">
                    @if ($errors->any())
                        <div class="alert alert-danger">
                            <ul class="mb-0">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ route('welcome_greetings.update', $welcomeGreeting->id) }}" method="POST"
                        enctype="multipart/form-data" novalidate>
                        @csrf
                        @method('PUT')

                        <div class="form-group">
                            <label for="title">Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title"
                                value="{{ $welcomeGreeting->title }}">
                        </div>

                        <div class="form-group">
                            <label for="image">Replace Image (Optional)</label>
                            <input type="file" class="form-control-file" id="image" name="image">
                        </div>

                        <div class="form-group">
                            <label for="alt_text">Alternative Text</label>
                            <input type="text" class="form-control" id="alt_text" name="alt_text"
                                value="{{ $welcomeGreeting->alt_text }}">
                            <small class="form-text text-muted">For accessibility. If blank, the title will be used.</small>
                        </div>

                        @if ($welcomeGreeting->hasImage())
                            <div class="form-group">
                                <label>Current Image</label>
                                <div>
                                    <img src="{{ $welcomeGreeting->image_url }}" alt="{{ $welcomeGreeting->alt_text }}"
                                        class="img-thumbnail" style="max-width: 200px; max-height: 150px;">
                                </div>
                            </div>
                        @endif

                        <div class="form-group" id="imagePreview" style="display: none;">
                            <label>New Image Preview:</label>
                            <div class="border p-3 text-center bg-light rounded"
                                style="max-height: 400px; overflow: hidden;">
                                <img id="preview" src="" alt="Preview"
                                    style="max-width: 100%; max-height: 350px; object-fit: contain;">
                            </div>
                        </div>

                        <hr>

                        <div class="form-group">
                            <label>Current Assignment Status</label>
                            <div id="assignment-status-container" class="border rounded p-3 bg-light">
                                @if ($summary['general'])
                                    <div class="assignment-item">
                                        <span class="badge badge-primary"><i class="fa fa-globe"></i> General
                                            Assignment</span>
                                        <p class="text-muted mb-0">Applied to all rooms.</p>
                                    </div>
                                @elseif ($summary['personal_rooms']->count() > 0)
                                    <div class="assignment-item">
                                        <span class="badge badge-info"><i class="fa fa-user"></i> Personal Assignment</span>
                                        <p class="text-muted mb-1">Applied to {{ $summary['personal_rooms']->count() }}
                                            specific room(s):</p>
                                        <div class="personal-rooms-list">
                                            @foreach ($summary['personal_rooms'] as $room)
                                                <span class="badge badge-light mr-1 mb-1 border">{{ $room->room }}</span>
                                            @endforeach
                                        </div>
                                    </div>
                                @else
                                    <div class="assignment-item">
                                        <span class="badge badge-secondary"><i class="fa fa-times"></i> No Assignment</span>
                                        <p class="text-muted mb-0">Not assigned to any rooms.</p>
                                    </div>
                                @endif
                            </div>
                        </div>

                        @php
                            $hasSchedule =
                                $isPersonal ||
                                (!empty($welcomeGreeting->start_date) && !empty($welcomeGreeting->expired_date));

                            $status = $welcomeGreeting->schedule_status;
                            $isActiveSchedule = $status === 'active';
                        @endphp

                        <div id="scheduleSection" style="{{ $hasSchedule ? '' : 'display:none;' }}">
                            <hr>

                            <h5 class="mb-3">Schedule Setting</h5>

                            @if($status === 'active')
                                <small class="alert alert-info form-text">
                                    This schedule is currently active and cannot be modified.  
                                    You may update the schedule once it has expired.
                                </small>
                            @endif

                            <div class="form-group">
                                <label for="timezone">Time Zone <span class="text-danger">*</span></label>
                                <select name="timezone_id" id="timezone" class="form-control" 
                                    {{ $hasSchedule ? 'required' : '' }}
                                    {{ $isActiveSchedule ? 'disabled' : '' }}>
                                    <option value="">Please Select</option>
                                    @foreach ($timezone as $tz)
                                        <option value="{{ $tz->id }}"
                                            {{ $welcomeGreeting->timezone_id == $tz->id ? 'selected' : '' }}>
                                            {{ $tz->timezone }}
                                        </option>
                                    @endforeach
                                </select>
                                @if($isActiveSchedule)
                                    <input type="hidden" name="timezone_id" value="{{ $welcomeGreeting->timezone_id }}">
                                @endif
                            </div>

                            <div class="form-group">
                                <label>Schedule <span class="text-danger">*</span></label>

                                @if($status === 'expired')
                                    <small class="alert alert-danger form-text">
                                        This schedule has already passed. Please update it to a future date and time.
                                    </small>
                                @endif
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="small text-muted">From</label>
                                        <input type="text"
                                            name="start_date"
                                            id="schedule_from"
                                            class="form-control"
                                            value="{{ optional($welcomeGreeting->start_date)->format('Y-m-d H:i') }}"
                                            style="background-color:#ffffff"
                                            {{ $hasSchedule ? 'required' : '' }}
                                            {{ $isActiveSchedule ? 'disabled' : '' }}>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="small text-muted">To</label>
                                        <input type="text"
                                            name="expired_date"
                                            id="schedule_to"
                                            class="form-control"
                                            value="{{ optional($welcomeGreeting->expired_date)->format('Y-m-d H:i') }}"
                                            style="background-color:#ffffff"
                                            {{ $hasSchedule ? 'required' : '' }}
                                            {{ $isActiveSchedule ? 'disabled' : '' }}>
                                    </div>

                                    @if($isActiveSchedule)
                                        <input type="hidden" name="start_date" value="{{ $welcomeGreeting->start_date }}">
                                        <input type="hidden" name="expired_date" value="{{ $welcomeGreeting->expired_date }}">
                                    @endif
                                </div>
                                <small class="alert alert-warning form-text">
                                    The greeting will be active only within the specified time range.<br>
                                    • <strong>Start Date</strong> must be later than the current date and time. When the schedule popup is opened, it will automatically default to <strong>5 minutes after</strong> the current time (editable if needed).<br>
                                    • <strong>End Date</strong> must be later than the selected Start Date and cannot be in the past. By default, it will automatically be set to <strong>24 hours after</strong> the selected Start Date (editable if needed).
                                </small>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-custom">Update Welcome Greeting</button>
                        <a href="{{ route('welcome_greetings.index') }}" class="btn btn-custom">Cancel</a>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <style>
        .panel-title {
            color: #000 !important;
        }
    </style>

    <script>
        document.addEventListener('DOMContentLoaded', function () {

            // Image preview
            const imageInput = document.getElementById('image');
            if (imageInput) {
                imageInput.addEventListener('change', function (e) {
                    const file = e.target.files[0];
                    if (!file) return;

                    const reader = new FileReader();
                    reader.onload = function (event) {
                        document.getElementById('preview').src = event.target.result;
                        document.getElementById('imagePreview').style.display = 'block';
                    };
                    reader.readAsDataURL(file);
                });
            }

            const startInput = document.getElementById("schedule_from");
            const endInput   = document.getElementById("schedule_to");

            if(!startInput || !endInput) return;

            function nowPlus(minutes = 5){
                const d = new Date();
                d.setMinutes(d.getMinutes() + minutes);
                return d;
            }

            function addHours(date, hours){
                const d = new Date(date);
                d.setHours(d.getHours() + hours);
                return d;
            }

            function formatLocal(date){
                const pad = (n)=> n.toString().padStart(2,'0');

                return date.getFullYear()+"-"+ 
                    pad(date.getMonth()+1)+"-"+ 
                    pad(date.getDate())+" "+
                    pad(date.getHours())+":"+
                    pad(date.getMinutes());
            }

            const startPicker = flatpickr(startInput, {

                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                minuteIncrement: 1,

                minDate: "today",
                defaultDate: startInput.value ? startInput.value : nowPlus(),

                onOpen: function(selectedDates, dateStr, instance){

                    const now = new Date();

                    instance.set("minTime",
                        now.getHours() + ":" + now.getMinutes()
                    );

                },

                onChange: function(selectedDates){

                    if(!selectedDates.length) return;

                    const start = selectedDates[0];

                    const endDefault = addHours(start, 24);

                    endPicker.set("minDate", start);

                    if(!endInput.value || new Date(endInput.value) <= start){
                        endPicker.setDate(endDefault);
                    }

                }

            });

            const endPicker = flatpickr(endInput, {

                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                minuteIncrement: 1,
                minTime: new Date().getHours() + ":" + new Date().getMinutes(),

            });

            // =============================
            // REALTIME VALIDATION
            // =============================

            document.querySelector("form").addEventListener("submit", function(e){

                const startDate = new Date(startInput.value);
                const now = new Date();

                if(startDate <= now){

                    alert("Start time cannot be in the past.");
                    e.preventDefault();
                    return false;

                }

                if(new Date(endInput.value) <= startDate){

                    alert("End date must be after start date.");
                    e.preventDefault();
                    return false;

                }

                // =============================
                // BUFFER TIME (2 menit)
                // =============================

                // startDate.setMinutes(startDate.getMinutes() + 2);

                // startInput.value = formatLocal(startDate);

            });

        });
    </script>
@endsection
