@extends('layouts.admin')
@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">{{ (!empty($promo->id)) ? 'Update Promo Code' : 'Create Promo Code'  }}</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);">Promo Code</a></li>
                    <li class="breadcrumb-item active">{{ (!empty($promo->id)) ? 'Update Promo Code' : 'Create Promo Code'  }}</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 {{ !empty($promo->id) ? 'edit-form' : '' }}" autocomplete="off" name="cityForm" id="cityForm" method="post" novalidate enctype="multipart/form-data" action="{{ route('admin.promos.store') }}">
                <input type="hidden" name="id" id="id" value="{{ (!empty($promo->id)) ? $promo->id : '' }}" />
                    <div class="row">
                        <div class="col-lg-4 mb-3">
                            <label for="customername-field" class="form-label">Coupon Code</label>
                            <input type="text" id="code" name="code" class="form-control" placeholder="Enter Coupon Code" required value="{{ (!empty($promo->code)) ? $promo->code : '' }}" />
                        </div>
                        
                        <div class="col-lg-4 mb-3">
                            <label for="type-field" class="form-label">Plan</label>
                            <select class="form-select js-example-basic-multiple" id="type" name="pricing_plan_id[]" multiple>
                                    @foreach($plans as $plan)
                                    <option value="{{ $plan->id }}" {{ (!empty($promo->pricing_plan_id) && in_array($plan->id, json_decode($promo->pricing_plan_id,true))) ? 'selected' : '' }}>{{ $plan->name }}</option>\
                                    @endforeach
                            </select>
                        </div>
                    
                        <div class="col-lg-4 mb-3">
                            <label for="type-field" class="form-label">Type</label>
                            <select class="form-select" id="type" name="type" required>
                                <option value=""></option>
                                <option value="percentage" {{ (!empty($promo->type) && $promo->type == 'percentage') ? 'selected' : '' }}>Percentage</option>
                                <option value="fixed" {{ (!empty($promo->type) && $promo->type == 'fixed') ? 'selected' : '' }}>Fixed</option>
                            </select>
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="value-field" class="form-label">Value</label>
                            <input type="number" id="value" name="value" class="form-control" placeholder="Enter Value" required value="{{ (!empty($promo->value)) ? $promo->value : '' }}" />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="start-date-field" class="form-label">Start Date</label>
                            <input type="date" id="start_date" name="start_date" class="form-control" required value="{{ (!empty($promo->start_date)) ? $promo->start_date : '' }}" />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="end-date-field" class="form-label">End Date</label>
                            <input type="date" id="end_date" name="end_date" class="form-control" required value="{{ (!empty($promo->end_date)) ? $promo->end_date : '' }}" />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="total-limit-field" class="form-label">Total Limit</label>
                            <input type="number" id="total_limit" name="total_limit" class="form-control" placeholder="Enter Total Limit" required value="{{ (!empty($promo->total_limit)) ? $promo->total_limit : '' }}" />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="user-limit-field" class="form-label">User Limit</label>
                            <input type="number" id="user_limit" name="user_limit" class="form-control" placeholder="Enter User Limit" required value="{{ (!empty($promo->user_limit)) ? $promo->user_limit : '' }}" />
                        </div>

                        <div class="col-lg-4 mb-3">
                            <label for="daily-limit-field" class="form-label">Daily Limit</label>
                            <input type="number" id="daily_limit" name="daily_limit" class="form-control" placeholder="Enter Daily Limit" required value="{{ (!empty($promo->daily_limit)) ? $promo->daily_limit : '' }}" />
                        </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 status-select"  id="status" name="status">
                                <option value=""></option>
                                <option value="1" {{ (!empty($promo->status) && $promo->status == 1) ? 'selected' : '' }}>Active</option>
                                <option value="0" {{ (!empty($promo->status) && $promo->status == 0) ? 'selected' : '' }}>Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="hstack gap-2 justify-content-between"> 
                       <a href="{{ route('admin.promos') }}" class="btn btn-success">Back</a>
                        <button type="submit" class="btn btn-success" id="submitBtn">{{ (!empty($promo->id)) ? 'Update Promo Code' : 'Create Promo Code'  }}</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" language="javascript">
    $(document).ready(function () {
       
        $("#cityForm").validate({
            rules: {
                code: {
                    required: true,
                    minlength: 3,
                },
                type: {
                    required: true,
                },
                value: {
                    required: true,
                    number: true,
                },
                start_date: {
                    required: true,
                    date: true,
                },
                end_date: {
                    required: true,
                    date: true,
                },
                total_limit: {
                    required: true,
                    number: true,
                },
                user_limit: {
                    required: true,
                    number: true,
                },
                daily_limit: {
                    required: true,
                    number: true,
                },
                status: {
                    required: true,
                },
            },
            messages: {
                name: {
                    required: "Please enter the coupon code.",
                    minlength: "Company name must be at least 3 characters.",
                },
                status: {
                    required: "Please select the status.",
                },
            },
            onkeyup: function (element) {
                    $(element).valid(); // Real-time validation on keyup
                },
                onfocusout: function (element) {
                    $(element).valid(); // Validate when focus is lost
                },
            errorPlacement: function (error, element) {
                if (element.is("select")) {
                    error.insertAfter(element.next('.select2')); 
                } else {
                    error.insertAfter(element);
                }
            },
            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) {
                        // Show success message with Swal
                     

                        Swal.fire({
                                iconHtml: `<img src="{{ asset('assets/images/success-circle.svg') }}" class="img-fluid">`,
                               // title: "Success!",
                                text: response.message,
                                confirmButtonText: "OK",
                                customClass: {
                                    confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                }
                            }).then(() => {
                                window.location.href = "{{ route('admin.promos') }}"; // Redirect to company list
                            });
                    },
                    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 later",
                                    iconHtml: `<img src="{{ asset('assets/images/error-circle.svg') }}" class="img-fluid">`,
                                    confirmButtonText: "OK", // Optional: Change the text of the button
                                    customClass: {
                                        confirmButton: 'custom-ok-button-class w-sm' // Add your custom class here
                                    }
                             });
                        }
                    }
                });

                return false; // Prevent default form submission
            }, 
            invalidHandler: function(event, validator) {
                var firstInvalidField = $(validator.errorList[0].element);
                
                $('html, body').animate({
                    scrollTop: firstInvalidField.offset().top - 100 
                }, 500); 
            }
        });
    });
</script>
    
@endsection
