@extends('layouts.company')
@section('content')
    <!-- start page title -->
    <div class="row">
        <div class="col-12">
            <div class="page-title-box d-sm-flex align-items-center justify-content-between bg-galaxy-transparent">
                <h4 class="mb-sm-0">Create Challenge</h4>

                <div class="page-title-right">
                    <ol class="breadcrumb m-0">
                        <li class="breadcrumb-item"><a href="javascript: void(0);">Home</a></li>
                        <li class="breadcrumb-item"><a href="javascript: void(0);">Challenge</a></li>
                        <li class="breadcrumb-item active">Create Challenge</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    <!-- end page title -->

    <div class="row">
        <div class="col-lg-12">
            <div class="card" id="orderList">
                <div class="card-body">
                    <form class="tablelist-form" autocomplete="off" id="challengeForm" method="post" action="{{ route('company.challenges') }}">
                        <div class="row">
                            <div class="mb-3 col-lg-4">
                                <label for="customername-field" class="form-label">Challenge Name</label>
                                <input type="text" id="customername-field" class="form-control" placeholder="Enter name" required name="name"/>
                            </div>

                            <div class="mb-3 col-lg-4">
                                <label for="orderId" class="form-label">Target</label>
                                <div class="d-flex gap-2">
                                    <input type="text" class="form-control number-only" placeholder="Target" name="target_value"/>
                                    <div style="width: 180px;">
                                        <select class="form-select js-example-basic-single" data-placeholder="Target Type" name="target_type">
                                            <option></option>
                                            <option value="1">KM</option>
                                            <option value="2">Floors</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4 mb-3">
                                <label for="customername-field" class="form-label">Start Date: </label>
                                <input type="text" class="form-control" placeholder="Start Date" data-provider="flatpickr" data-date-format="d-m-Y" name="start_date" id="start_date" />
                            </div>

                            <div class="col-lg-4 mb-3">
                                <label for="customername-field" class="form-label">End Date: </label>
                                <input type="text" class="form-control" placeholder="End Date" data-provider="flatpickr" data-date-format="d-m-Y" name="end_date" id="end_date" />
                            </div>



                            <div class="col-lg-4 mb-3">
                                <label for="customername-field" class="form-label">Status</label>
                                <select class="form-select js-example-basic-single" data-placeholder="Select Status" name="status">
                                    <option value=""></option>
                                    <option value="1">Active</option>
                                    <option value="0">Inactive</option>
                                </select>
                            </div>
                        </div>



                        <div class="hstack gap-2 justify-content-end">
                            <button type="submit" class="btn btn-success">Create Challenge</button>
                            <!-- <button type="button" class="btn btn-success" id="edit-btn">Update</button> -->
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
@endsection
@section('script')
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/jquery.validate.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.5/dist/additional-methods.min.js"></script>
    <script type="text/javascript" src="{{ asset('assets/js/custom.js') }}"></script>
    <script type="text/javascript" language="javascript">

        $(document).ready(function () {

            const startDatePicker = flatpickr("#start_date", {
                enableTime: false, // Set to true if you need a time picker
                dateFormat: "Y-m-d", // Customize the format (e.g., YYYY-MM-DD)
                minDate: "today",
                onChange: function(selectedDates, dateStr) {
                    // Set the minimum date for the End Date picker
                    endDatePicker.set('minDate', dateStr);
                    document.getElementById("end_date").value = "";
                }
            });

            const endDatePicker = flatpickr("#end_date", {
                enableTime: false, // Set to true if you need a time picker
                dateFormat: "Y-m-d", // Customize the format (e.g., YYYY-MM-DD)
                minDate: "today"
            });

            $("#challengeForm").validate({
                rules: {
                    name: {
                        required: true,
                        minlength: 3,
                    },
                    target_type: {
                        required: true,
                    },
                    target_value:{
                        required:true
                    },
                    start_date: {
                        required: true,
                        date: true
                    },

                    end_date: {
                        required: true,
                        date: true,
                        greaterThan: "#start_date"
                    },
                    status: {
                        required: true,
                    }
                },
                messages: {
                    name: {
                        required:"Challenge Name is required."
                    },

                    target_type: {
                        required: "Target Type is required",
                    },
                    target_value: {
                        required: "Target is required.",
                    },
                    start_date: {
                        required: "Please select a start date.",
                        date: "Please enter a valid date."
                    },
                    end_date: {
                        required: "Please select an end date.",
                        date: "Please enter a valid date.",
                        greaterThan: "End date must be after or equal to the start date."
                    },
                    status: {
                        required: "Please select the status.",
                    },
                },
                errorPlacement: function (error, element) {
                    error.insertAfter(element); // Place error message after the input field
                },
                submitHandler: function (form) {
                    let formData = new FormData(form);

                    // AJAX submission
                    $.ajax({
                        url: form.action,
                        type: "POST",
                        data: formData,
                        processData: false,
                        contentType: false,
                        headers: {
                            "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
                        },
                        success: function (response) {
                            if(response.status == "success") {
                                Swal.fire({
                                    text: response.message,
                                    icon: "success",
                                    confirmButtonText: "OK"
                                }).then(() => {
                                    window.location.href = "{{ route('company.challenges') }}"; // Redirect to company list
                                });
                            } else {
                                Swal.fire({
                                    text: response.message,
                                    icon: "error",
                                    confirmButtonText: "OK"
                                });
                            }

                        },
                        error: function (xhr) {
                            if (xhr.status === 422) {
                                let errors = xhr.responseJSON.errors;

                                // Display validation errors from the server
                                $.each(errors, function (key, value) {
                                    let field = $(`[name="${key}"]`);
                                    field.addClass("error"); // Add error class to the field
                                    field.after(`<label class="error">${value[0]}</label>`); // Add error message
                                });
                            } else {
                                Swal.fire({
                                    text: "Something went wrong. Please try again later.",
                                    icon: "error",
                                    confirmButtonText: "OK"
                                });
                            }
                        }
                    });

                    return false; // Prevent default form submission
                }
            });
        });
    </script>
@endsection
