@extends('layouts.app')
@section('title', 'Project')
@section('pages')
<style type="text/css">
    .add_btn {
        height: 30px;
        width: 30px;
        border-radius: 100%;
        padding: 0;
        margin-left: 5px;
        margin-right: 15px;
        margin-top: 5px
    }

    .intl-tel-input {
        width: 100%;
    }

    .more-less {
        float: right;
        color: #212121;
    }
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet/less" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css')}}" rel="stylesheet" />
<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Project List</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Add New Project</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{{route('projects.index')}}" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->
<div class="row auto">
    <div class="col-xl-12 mx-auto">
        <div class=" shadow-none radius-5 min-height">
            <div class="">
                <div class="">
                    <form class="row g-3 auto-width " action="{{ route('projects.store') }}" method="post" enctype='multipart/form-data' id="projects">
                        @csrf
                        <!-- validated columns -->
                        <!-- <form class="row g-3 was-validated"> -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Project Details</h5>
                                    <hr class="mb-0">

                                     <!-- recieve date -->
                                     <div class="col-md-6">
                                        <div>
                                            <label for="receive_date" class="form-label">Project Recieve Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="text" name="receive_date" class="form-control" id="receive_date" autocomplete="off" placeholder="Select Recieve Date" readonly style="cursor: pointer;">
                                        </div>
                                        @if ($errors->has('receive_date'))
                                            <span class="text-danger">{{ $errors->first('receive_date') }}</span>
                                        @endif
                                        <span class="text-danger error_recieve_date" style="display: none;">This field is required.</span>
                                    </div>
                                    <!-- project_type_id -->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="project_type_id" class="form-label">Project Type <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group col-md-4">
                                            <select class="form-control" name="project_type_id">
                                                <option value=""> -- Select Project Type  -- </option>
                                                @foreach($projectType as $list)
                                                <option value="{{ $list->id }}">{{ $list->title }}</option>
                                                @endforeach
                                            </select>
                                            <div class="input-group-append col-md-1">
                                                <button class="btn btn-success add_btn" id="create_project_type" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" style="margin-right: 10px;">+ </button>
                                            </div>
                                        </div>
                                        <span class="text-danger error_project_type_id" style="display: none;">This field is required.</span>
                                    </div>
                                    <!-- Title -->
                                    <div class="col-md-12">
                                        <label for="title" class="form-label">Project Title </label>
                                        <input type="text" class="form-control" id="title" name="title" aria-describedby="inputGroupPrepend" required placeholder="Enter Project Title">
                                        <span class="text-danger error_title" style="display:none;">This field is required.</span>
                                    </div>
                                      <!-- about -->
                                      <div class="col-md-12">
                                        <label for="about" class="form-label">About</label>
                                        <textarea class="form-control" max=100 id="about" name="about" placeholder="About"></textarea>
                                    </div>
                                </div>
                                <div class="card-body g-3 row additional_fields">
                                </div>
                                <div class="card-body g-3 row">
                                    <div class="col-12" align="center">
                                        <div class="d-grid gap-2 with-100">
                                            <button class="btn btn-primary save_project">Save Record</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Additional Information</h5>
                                    <hr class="mb-0">

                                      <!-- Organization Department -->
                                      <div class="col-md-12" id="test_items">
                                        <label for="department_id" class="form-label"> Department </label>
                                    </div>
                                    <div class="input-group">
                                        <select class="multi-select-tests" multiple name="department_id[]">
                                            @foreach ($department as $list)
                                                <option value="{{ $list->id }}">{{ $list->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <span class="text-danger error_department_id" style="display: none;">This field is required.</span>
                                    <!-- product_category_id -->
                                     <div class="col-md-6">
                                        <div>
                                            <label for="product_category_id" class="form-label">Product Category </label>
                                        </div>
                                        <div class="input-group">
                                            <select class="form-control" name="product_category_id">
                                                <option value=""> -- Select Product Category  -- </option>
                                                @foreach($productCategory as $list)
                                                <option value="{{ $list->id }}">{{ $list->name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <span class="text-danger error_product_category_id" style="display: none;">This field is required.</span>
                                    </div>

                                    <!-- start date -->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="start_date" class="form-label"> Start Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" name="start_date" class="form-control" id="start_date" autocomplete="off" placeholder="Select Start Date" readonly style="cursor: pointer;">
                                        </div>
                                        @if ($errors->has('start_date'))
                                            <span class="text-danger">{{ $errors->first('start_date') }}</span>
                                        @endif
                                    </div>
                                    <!-- dead_line date -->
                                    <div class="col-md-6">
                                        <div>
                                            <label for="dead_line_date" class="form-label"> Dead Line Date </label>
                                        </div>
                                        <div class="input-group">
                                            <input type="" name="dead_line_date" class="form-control" id="dead_line_date" autocomplete="off" placeholder="Select Dead Line Date" readonly style="cursor: pointer;">
                                        </div>
                                        @if ($errors->has('dead_line_date'))
                                            <span class="text-danger">{{ $errors->first('dead_line_date') }}</span>
                                        @endif
                                    </div>

                                    <!-- priority -->
                                    <div class="col-md-12"  style="display: none;">
                                        <label for="priority" class="form-label">Priority <span class="text-danger"><b>*</b></span></label>
                                        <input type="number" class="form-control" name="priority" aria-describedby="inputGroupPrepend" required value="{!! $priority + 1 !!}">
                                        <span class="text-danger error_priority" style="display:none;">This field is required.</span>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!--end row-->
@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js')}}"></script>
    <script>
           $('.multi-select-tests').select2({
            theme: 'bootstrap4',
            dropdownParent: $("#test_items"),
            placeholder: "Select Departments",
            width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
            allowClear: Boolean($(this).data('allow-clear')),
        });

        function formatDate(date) {
            const options = { day: 'numeric', month: 'numeric', year: 'numeric' };
            return new Date(date).toLocaleDateString(undefined, options);
        }

        var currentDate = new Date().toISOString().split('T')[0];
        $('#receive_date').datepicker().val(formatDate(currentDate));

        $( function() {
            $('#start_date').datepicker();
        });
        $( function() {
            $('#dead_line_date').datepicker();
        });

         // Adding Project Type
         $(document).on('click', '#create_project_type', function() {
            $('#commonModalLabel').text('Add New Project Type');
            $('.save_button_span').text('Save Project Type');
            $.ajax({
                url: "{!! route('project-types.create') !!}",
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            })
        })

        $(document).on('click', '.save_button', function(event) {
            event.preventDefault();
            var error = 0;
            if ($('#commonModal').find('form').hasClass('project_types')) {
                $('.error_title').hide();
                if ($('#commonModal').find('form').find('input[name="title"]').val().trim() == '') {
                    $('.error_title').show();
                    error = 1;
                }

                if (error == 0) {
                    let formdata = new FormData($('#commonModal').find('form')[0]);

                    $.ajax({
                            url: $('#commonModal').find('form').attr('action'),
                            data: formdata,
                            processData: false,
                            contentType: false,
                            type: 'POST',
                            success: function(response) {


                                if (response.success === true) {
                                    toastr.success(response.message, 'Success.');
                                    $('[name="project_type_id"]').append(`<option value="${response.data.id}" selected>${response.data.title}</option>`);
                                    $('[name="project_type_id"]').trigger('change');

                                    // hide modal
                                    $('#commonModal').modal('hide');
                                    $('#commonModal').find('.modal-body').html('');
                                    setTimeout(function() {
                                        //  alert('test');
                                        $('#create').trigger('click');
                                    }, 1000);
                                } else {
                                    toastr.error(response.message, 'Error!');
                                }
                            }
                        })
                        .fail(function(jqXHR, textStatus, errorThrown) {
                            console.log('AJAX request failed:', textStatus, errorThrown);
                            toastr.error('An error occurred during the request.', 'Error!');

                            // hide modal
                            $('#commonModal').modal('hide');
                            $('#commonModal').find('.modal-body').html('');
                        });
                }

            }

        })
        $(document).on('click', '.save_project', function(e) {
            e.preventDefault();

            $('.error_title').hide();
            $('.error_project_type_id').hide();
            $('.error_email').hide();
            var error = 0;

            if ($('select[name="project_type_id"]').val() == null || $('select[name="project_type_id"]').val() == '') {
                $('.error_project_type_id').show();
                error = 1;

                // Hide the error message after 3 seconds
                setTimeout(function () {
                    $('.error_project_type_id').hide();
                }, 3000);
            }
            if ($('input[name="title"]').val() == null || $('input[name="title"]').val().trim() == '') {
                $('.error_title').show();
                error = 1;

                // Hide the error message after 3 seconds
                setTimeout(function () {
                    $('.error_title').hide();
                }, 3000);
            }

            if (error == 0) {
                let formdata = new FormData($('#projects')[0]);
                $('.save_project').prop('disabled', true);

                $.ajax({
                        url: "{{ route('projects.store') }}",
                        data: formdata,
                        processData: false,
                        contentType: false,
                        type: 'POST',
                        success: function(response) {
                            if (response.success === true) {
                                var redirectBack = "{{ request()->input('redirect_back') }}";
                                var callback = "{{ request()->input('callback') }}";
                                if (redirectBack === 'true') {
                                    window.history.back();
                                } else if (callback == 'license') {
                                    toastr.success(response.message, 'Success.');
                                    setTimeout(window.location.href = "{!! route('license-register.create') !!}", 3000);
                                }else{
                                    toastr.success(response.message, 'Success.');
                                    window.location.href = "{{ route('projects.index') }}";
                                }
                            } else {
                                toastr.error(response.message, 'Error!');
                            }
                        }
                    })
                    .fail(function(jqXHR, textStatus, errorThrown) {
                        console.log('AJAX request failed:', textStatus, errorThrown);
                        toastr.error('An error occurred during the request.', 'Error!');
                    });
            }
            error = 1;
        })
    </script>
@endsection
