@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="javascript:;">Information Display</a></li>
                <li class="breadcrumb-item"><a href="{{ route('welcome_greetings.index') }}">Welcome Greetings</a></li>
                <li class="breadcrumb-item active">Create</li>
            </ol>
            <h1 class="page-header">Create Welcome Greeting</h1>
            <div class="panel panel-inverse">
                <div class="panel-heading">
                    <h4 class="panel-title">Add New 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.store') }}" method="POST" enctype="multipart/form-data"
                        id="createForm" novalidate>
                        @csrf

                        <div class="form-group">
                            <label for="title">Welcome Greeting Title <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="title" name="title"
                                value="{{ old('title') }}" placeholder="Enter greeting title..." required>
                            <small class="form-text text-muted">
                                This title helps identify the greeting in the management interface.
                            </small>
                        </div>

                        <div class="form-group">
                            <label for="image">Welcome Image <span class="text-danger">*</span></label>
                            <input type="file" class="form-control-file" id="image" name="image"
                                accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" required>
                            <small class="form-text text-muted">
                                Accepted formats: JPEG, PNG, JPG, GIF, WebP. Maximum file size: 5MB.
                                Recommended dimensions: 1920x1080px or higher for best display quality.
                            </small>
                        </div>

                        <div class="form-group">
                            <label for="alt_text">Alternative Text (Optional)</label>
                            <input type="text" class="form-control" id="alt_text" name="alt_text"
                                value="{{ old('alt_text') }}" placeholder="Enter alternative text for accessibility...">
                            <small class="form-text text-muted">
                                This text will be used for screen readers and when the image fails to load.
                                If not provided, the title will be used.
                            </small>
                        </div>

                        <div class="form-group" id="imagePreview" style="display: none;">
                            <label>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>

                        <div class="form-group">
                            <label>Assignment Type <span class="text-danger">*</span></label>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="assignment_type" id="assign_none"
                                    value="none" {{ old('assignment_type', 'none') == 'none' ? 'checked' : '' }}>
                                <label class="form-check-label" for="assign_none">
                                    <i class="fa fa-circle-o text-secondary"></i> Create without assignment
                                </label>
                                <small class="form-text text-muted">Create the greeting first, assign it to rooms
                                    later</small>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="assignment_type" id="assign_general"
                                    value="general" {{ old('assignment_type') == 'general' ? 'checked' : '' }}>
                                <label class="form-check-label" for="assign_general">
                                    <i class="fa fa-globe text-primary"></i> Assign to All Rooms (General)
                                </label>
                                <small class="form-text text-muted">This will be the default greeting for all rooms</small>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="assignment_type" id="assign_personal"
                                    value="personal" {{ old('assignment_type') == 'personal' ? 'checked' : '' }}>
                                <label class="form-check-label" for="assign_personal">
                                    <i class="fa fa-user text-info"></i> Assign to Specific Rooms (Personal)
                                </label>
                                <small class="form-text text-muted">Select specific rooms for this greeting</small>
                            </div>
                        </div>

                        <div class="form-group" id="roomSelection" style="display: none;">
                            <label>Select Rooms <span class="text-danger">*</span></label>
                            <div class="room-selection-container">
                                <div class="room-search mb-3">
                                    <input type="text" class="form-control" id="roomSearch"
                                        placeholder="Search rooms...">
                                </div>
                                <div class="room-list" style="max-height: 300px; overflow-y: auto;">
                                    @foreach ($rooms as $room)
                                        <div class="form-check room-item">
                                            <input class="form-check-input room-checkbox" type="checkbox"
                                                value="{{ $room->id }}" id="create_room_{{ $room->id }}"
                                                name="room_ids[]" data-room-name="{{ strtolower($room->room) }}"
                                                data-room-type="{{ strtolower($room->roomType->name ?? '') }}"
                                                {{ in_array($room->id, old('room_ids', [])) ? 'checked' : '' }}>
                                            <label class="form-check-label" for="create_room_{{ $room->id }}">
                                                <strong>{{ $room->room }}</strong> <span
                                                    class="text-muted">({{ $room->roomType->name ?? 'N/A' }})</span>
                                            </label>
                                            <small class="ml-2 text-danger room-assigned-notice" style="display: none;">
                                                (Already assigned to another greeting)
                                            </small>
                                        </div>
                                    @endforeach
                                </div>
                                <div class="selected-count mt-2">
                                    <small class="text-muted">Selected: <span id="selectedCount">0</span> room(s)</small>
                                </div>
                            </div>
                        </div>

                        <div id="scheduleSection" style="display: none;">
                            <div class="form-group">
                                <label for="timezone">Time Zone <span class="text-danger">*</span></label>
                                <select name="timezone_id" id="timezone" class="form-control">
                                    <option value="">Please Select</option>

                                    @foreach ($timezone as $tz)
                                        <option value="{{ $tz->id }}"
                                            {{ old('timezone_id') == $tz->id ? 'selected' : '' }}>
                                            {{ $tz->timezone }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="form-group">
                                <label>Schedule <span class="text-danger">*</span></label>
                                <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="{{ old('start_date') }}"
                                            style="background-color:#ffffff">
                                    </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="{{ old('expired_date') }}"
                                            style="background-color:#ffffff">
                                    </div>
                                </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. By default, it will be automatically set 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. It will be automatically set to <strong>24 hours after</strong> the start date (editable if needed).
                                </small>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="alert alert-info" id="assignmentInfo">
                                <i class="fa fa-info-circle"></i>
                                <span id="assignmentDescription">This greeting will be automatically set as active. You can
                                    assign or change assignments later from the main list.</span>
                            </div>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-custom" id="submitBtn">
                                <i class="fa fa-save"></i> Create Welcome Greeting
                            </button>
                            <a href="{{ route('welcome_greetings.index') }}" class="btn btn-custom">
                                <i class="fa fa-arrow-left"></i> Back to List
                            </a>
                        </div>
                    </form>
                </div>
            </div>
            </div>
        <a href="javascript:;" class="btn btn-icon btn-circle btn-custom btn-scroll-to-top fade" data-click="scroll-top">
            <i class="fa fa-angle-up"></i>
        </a>
        </div>

    <style>
        .room-selection-container {
            border: 1px solid #ddd;
            border-radius: 4px;
            padding: 10px;
            background-color: #f9f9f9;
        }

        .room-item {
            border-bottom: 1px solid #eee;
        }

        .room-item:last-child {
            border-bottom: none;
        }

        .form-check {
            margin-bottom: 0.5rem;
        }

        .form-check-label {
            font-weight: normal;
        }

        .form-check-label i {
            margin-right: 0.5rem;
        }

        #imagePreview {
            background-color: #f8f9fa;
            border-radius: 4px;
        }

        .text-danger {
            color: #dc3545 !important;
        }

        /* Ensure panel title is black */
        .panel-title {
            color: #000000 !important;
        }

        /* Room item styles - matching index.blade.php */
        .room-item.disabled {
            color: #999;
            text-decoration: line-through;
            cursor: not-allowed;
        }

        .room-item.disabled label {
            cursor: not-allowed;
        }

        .room-assigned-notice {
            font-size: 0.75rem;
            margin-top: 2px;
            display: block;
        }

        /* Loading state for room validation */
        .room-validation-loading {
            position: relative;
        }

        .room-validation-loading::after {
            content: '';
            position: absolute;
            top: 50%;
            right: 10px;
            width: 16px;
            height: 16px;
            border: 2px solid #ccc;
            border-top-color: #007bff;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
            transform: translateY(-50%);
        }

        @keyframes spin {
            to {
                transform: translateY(-50%) rotate(360deg);
            }
        }
    </style>

    <script>
        // Note: The CSRF token is usually in a meta tag or passed via a global JS variable.
        // If not in a meta tag, ensure you include it in your layout: <meta name="csrf-token" content="{{ csrf_token() }}">
        const csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector(
            'meta[name="csrf-token"]').getAttribute('content') : '{{ csrf_token() }}';
        let roomAssignmentData = null;

        document.addEventListener('DOMContentLoaded', function() {
            // Handle assignment type change
            document.querySelectorAll('input[name="assignment_type"]').forEach(radio => {
                radio.addEventListener('change', handleAssignmentTypeChange);
            });

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

            let startPicker;
            let endPicker;

            startPicker = flatpickr("#schedule_from", {

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

                defaultDate: nowPlus(5),

                minDate: "today",
                minTime: new Date().getHours() + ":" + new Date().getMinutes(),

                onOpen: function(selectedDates, dateStr, instance){

                    const now = new Date();

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

                },

                onChange: function(selectedDates){

                    if(selectedDates.length){

                        const start = selectedDates[0];

                        const endDefault = new Date(start.getTime() + (24*60*60*1000));

                        endPicker.set("minDate", start);
                        endPicker.setDate(endDefault);

                    }
                }
            });

            endPicker = flatpickr("#schedule_to", {

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

            });

            // Realtime Validation Time
            function validateRealtimeTime(){

                const startInput = document.getElementById("schedule_from").value;

                const selected = new Date(startInput);
                const now = new Date();

                if(selected <= now){

                    alert("Selected time is already in the past. Please refresh the time.");
                    return false;
                }

                return true;

            }

            // function formatLocalDate(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());
            // }

            // function addBufferTime(value, minutes = 2){

            //     const date = new Date(value);
            //     date.setMinutes(date.getMinutes() + minutes);

            //     return formatLocalDate(date);
            // }

            function handleAssignmentTypeChange() {
                const assignmentType = document.querySelector('input[name="assignment_type"]:checked').value;
                const roomSelection = document.getElementById('roomSelection');
                const scheduleSection = document.getElementById('scheduleSection');
                const assignmentDescription = document.getElementById('assignmentDescription');
                const submitBtn = document.getElementById('submitBtn');

                // Reset visibility
                roomSelection.style.display = 'none';
                scheduleSection.style.display = 'none';

                // Reset required attributes
                document.getElementById('timezone').required = false;
                document.getElementById('schedule_from').required = false;
                document.getElementById('schedule_to').required = false;

                if (assignmentType === 'personal') {
                    roomSelection.style.display = 'block';
                    scheduleSection.style.display = 'block';

                    document.getElementById('timezone').required = true;
                    document.getElementById('schedule_from').required = true;
                    document.getElementById('schedule_to').required = true;

                    assignmentDescription.innerHTML =
                        '<strong>Personal Assignment:</strong> This greeting will be assigned only to selected rooms and active based on the scheduled time.';
                    submitBtn.innerHTML = '<i class="fa fa-save"></i> Create & Assign to Selected Rooms';

                    loadRoomAssignments();
                } 
                else if (assignmentType === 'general') {
                    assignmentDescription.innerHTML =
                        '<strong>General Assignment:</strong> This greeting will be assigned to ALL rooms without scheduling.';
                    submitBtn.innerHTML = '<i class="fa fa-save"></i> Create & Assign to All Rooms';
                    clearRoomDisabledStates();
                } 
                else {
                    assignmentDescription.innerHTML =
                        '<strong>No Assignment:</strong> Greeting will be saved without room assignment or schedule.';
                    submitBtn.innerHTML = '<i class="fa fa-save"></i> Save Welcome Greeting';
                    clearRoomDisabledStates();
                }
            }

            // Initial setup
            handleAssignmentTypeChange();

            // Room search functionality
            document.getElementById('roomSearch').addEventListener('input', function() {
                const searchTerm = this.value.toLowerCase();
                document.querySelectorAll('.room-item').forEach(item => {
                    const checkbox = item.querySelector('.room-checkbox');
                    const roomName = checkbox.dataset.roomName;
                    const roomType = checkbox.dataset.roomType;

                    if (roomName.includes(searchTerm) || roomType.includes(searchTerm)) {
                        item.style.display = 'block';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });

            // Update selected count
            function updateSelectedCount() {
                // Only count checked rooms that are NOT disabled
                const selected = document.querySelectorAll('.room-checkbox:checked:not(:disabled)').length;
                document.getElementById('selectedCount').textContent = selected;
            }

            document.querySelectorAll('.room-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedCount);
            });

            // Initial count update
            updateSelectedCount();

            // Image preview handler with enhanced security validation
            document.getElementById('image').addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // Validate file size (5MB = 5 * 1024 * 1024 bytes)
                    if (file.size > 5 * 1024 * 1024) {
                        alert('File size exceeds 5MB limit. Please choose a smaller image.');
                        this.value = '';
                        document.getElementById('imagePreview').style.display = 'none';
                        return;
                    }

                    // Enhanced MIME type validation
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif',
                        'image/webp'
                    ];
                    if (!allowedTypes.includes(file.type)) {
                        alert('Invalid file type. Please choose a JPEG, PNG, GIF, or WebP image.');
                        this.value = '';
                        document.getElementById('imagePreview').style.display = 'none';
                        return;
                    }

                    // Additional file extension validation for security
                    const fileName = file.name.toLowerCase();
                    const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                    const fileExtension = fileName.split('.').pop();

                    if (!allowedExtensions.includes(fileExtension)) {
                        alert('Invalid file extension. Please choose a file with a valid image extension.');
                        this.value = '';
                        document.getElementById('imagePreview').style.display = 'none';
                        return;
                    }

                    // Create FileReader for preview
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        // Additional validation: check if it's actually an image
                        const img = new Image();
                        img.onload = function() {
                            document.getElementById('preview').src = e.target.result;
                            document.getElementById('imagePreview').style.display = 'block';
                        };
                        img.onerror = function() {
                            alert('The selected file is not a valid image.');
                            document.getElementById('image').value = '';
                            document.getElementById('imagePreview').style.display = 'none';
                        };
                        img.src = e.target.result;
                    };
                    reader.onerror = function() {
                        alert('Error reading the selected file.');
                        document.getElementById('image').value = '';
                        document.getElementById('imagePreview').style.display = 'none';
                    };
                    reader.readAsDataURL(file);

                } else {
                    document.getElementById('imagePreview').style.display = 'none';
                }
            });

            // Enhanced form validation with security checks
            document.getElementById('createForm').addEventListener('submit', function(e) {
                // Check title
                const title = document.getElementById('title').value.trim();
                if (!title) {
                    e.preventDefault();
                    alert('Please enter a title for the welcome greeting.');
                    document.getElementById('title').focus();
                    return false;
                }

                // Check assignment type
                const assignmentType = document.querySelector('input[name="assignment_type"]:checked');
                if (!assignmentType) {
                    e.preventDefault();
                    alert('Please select an assignment type.');
                    return false;
                }

                // If personal assignment, check if available rooms are selected
                if (assignmentType.value === 'personal') {
                    const selectedRooms = document.querySelectorAll('.room-checkbox:checked:not(:disabled)');
                    if (selectedRooms.length === 0) {
                        e.preventDefault();
                        alert('Please select at least one room.');
                        return false;
                    }

                    const timezone = document.getElementById('timezone').value;
                    const from = document.getElementById('schedule_from').value;
                    const to = document.getElementById('schedule_to').value;

                    if (!timezone || !from || !to) {
                        e.preventDefault();
                        alert('Please complete timezone and schedule.');
                        return false;
                    }

                    if (new Date(from) >= new Date(to)) {
                        e.preventDefault();
                        alert('Schedule "From" must be earlier than "To".');
                        return false;
                    }

                    if(!validateRealtimeTime()){
                        e.preventDefault();
                        return false;
                    }

                    // This for add buffer time 2 minutes from front end to backend
                    // const startInput = document.getElementById("schedule_from");

                    // startInput.value = addBufferTime(startInput.value, 2);
                }

                // Disable submit button to prevent double submission
                const submitBtn = document.getElementById('submitBtn');
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Creating...';
            });

            // Room assignment loading and validation functions
            function loadRoomAssignments() {
                const roomSelection = document.getElementById('roomSelection');
                roomSelection.classList.add('room-validation-loading');

                // Fetches ALL room IDs assigned to *any* personal greeting
                fetch('{{ route('welcome_greetings.roomsWithAssignments') }}', {
                        method: 'GET',
                        headers: {
                            'Accept': 'application/json',
                            'X-CSRF-TOKEN': csrfToken
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            roomAssignmentData = data.rooms_with_assignments;
                            updateRoomAvailability();
                        } else {
                            console.error('Failed to load room assignments:', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error loading room assignments:', error);
                    })
                    .finally(() => {
                        roomSelection.classList.remove('room-validation-loading');
                    });
            }

            function updateRoomAvailability() {
                if (!roomAssignmentData) return;

                // In create view, all previously assigned rooms are 'externally assigned'
                const assignedRoomIds = roomAssignmentData.map(room => room.room_id);

                document.querySelectorAll('.room-checkbox').forEach(checkbox => {
                    const roomId = parseInt(checkbox.value);
                    const roomItem = checkbox.closest('.room-item');
                    const assignedNotice = roomItem.querySelector('.room-assigned-notice');

                    // Check if this room is assigned to any existing active personal greeting
                    if (assignedRoomIds.includes(roomId)) {
                        // Disable the room
                        checkbox.disabled = true;
                        checkbox.checked = false; // Force uncheck if disabled
                        roomItem.classList.add('disabled');
                        assignedNotice.style.display = 'inline';
                        assignedNotice.textContent = `(Assigned to another greeting)`;
                    } else {
                        // Enable the room
                        checkbox.disabled = false;
                        roomItem.classList.remove('disabled');
                        assignedNotice.style.display = 'none';
                    }
                });

                // Update count after changes
                updateSelectedCount();
            }

            function clearRoomDisabledStates() {
                document.querySelectorAll('.room-checkbox').forEach(checkbox => {
                    const roomItem = checkbox.closest('.room-item');
                    const assignedNotice = roomItem.querySelector('.room-assigned-notice');

                    checkbox.disabled = false;
                    roomItem.classList.remove('disabled');
                    assignedNotice.style.display = 'none';
                });

                updateSelectedCount();
            }
        });
    </script>
@endsection