@extends('layouts.app')
@section('title', 'Edit Lead')
@section('content')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
    .footer-actions {
    display: flex;
    justify-content: flex-end; /* right aligned */
    flex-wrap: nowrap;         /* ek hi row me rakhe */
    gap: 10px;                 /* buttons ke beech gap */
}

.footer-actions .btn {
    min-width: 100px;          /* buttons ek size ke दिखें */
    text-align: center;
    white-space: nowrap;       /* text wrap na ho */
}

    </style>
<section class="content">
  <div class="row">       
    <div class="col-lg-12 col-12">
      <div class="box">


                              <form method="post">



                                @csrf
          <div class="box-body"><!--bg-lightest-->

            
            <h4 class="box-title text-info mb-0"><i class="fa fa-plus"></i> Edit Lead Info</h4>
           <a href="{{url('/leads/view?id=')}}{{$lead['id']}}" style="float:right;margin-top:0px;margin-right:0px;"class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5" >
                  <!-- <button class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5">  --> <i class="fa fa-eye fa-sx" aria-hidden="true"></i> View
                </a> 
                  <a href="{{url('/leads')}}" type="button" style="float:right" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-eye fa-sx"></i> Leads</a>&nbsp; &nbsp; &nbsp; &nbsp;

            <hr class="my-15">

              <div class="gap-items gap-y fs-20">
                  
                  @if(empty($labels))
                  <div class="text-info ">Please Add Labels before add Lead from here <a target="_blank" href="/crm-labels" style="text-decoration: none;" class="btn btn-info btn-sm">CRM Labels</a> </div>
                  @endif

                  @if(empty($lead_status))
                  <div class="text-warning ">Please Add Lead Status before add Lead from here <a target="_blank" href="/lead-status" style="text-decoration: none;" class="btn btn-warning btn-sm">Lead Status</a> </div>
                  @endif

                  @if(empty($users))
                  <div class="text-primary ">Please Add User before add Lead from here <a target="_blank" href="/add-extension" style="text-decoration: none;" class="btn btn-primary btn-sm">Users</a> </div>
                  @endif

                  @if(empty($lead_source))
                  <div class="text-danger">Please Add Lead Source before add Lead from here <a target="_blank" href="/lead-source" style="text-decoration: none;" class="btn btn-danger btn-sm">Lead Source</a> </div>
                  @endif

                </div>


                @if(!empty($labels) && !empty($lead_status) && !empty($users) && !empty($lead_source))
            <div class="row">
                                                    <div class="col-md-9">

                                                        <div class="box">
                    <div class="box-body">

            <div class="row">



          

              

                @if(!empty($labels))
                                            @foreach($labels as $label)
                                                @if($label->status == 1)
                                                 @if($label->column_name != 'unique_url')
                                                    <div class="col-md-3">
                                                        <div class="form-group">
                                                            <label
                                                                class="form-label">@if($label->data_type == 'select_option')
                                                                    Select
                                                                @endif {{$label->title}} @if($label->data_type == 'date') (mm/dd/yyyy) @endif @if($label->required == 1)
                                                                    <span style="color: red;">*</span>
                                                                @endif</label>

                                                                <div class="input-group mb-3">
                                                                
                    <span class="input-group-text @error('last_name') text-danger border-danger @enderror"><i class="{{$label->icons}}"></i></span>

                                                            @if($label->label_title_url == 'country')
                                                                <select class="form-select" name="country" id="country"
                                                                        data-country="{{$lead['country']}}">
                                                                    <option value="US">United States</option>
                                                                    <!-- <option value="IN">India</option> -->
                                                                </select>

                                                            @elseif($label->label_title_url == 'state' || $label->data_type=='select_state')
                                                                <select class="form-select" @if($label->label_title_url == 'state') name="state" @endif @if($label->data_type == 'select_state') name="{{$label->column_name}}" @endif  id="state"
                                                                        data-country="{{$lead['state']}}">

                                                                        <option value="">Select State</option>


                                                                         @if(!empty($state_list))
                                                                        @foreach($state_list as $state)
                                                                        <option @if($lead[$label->column_name] == $state->state_name) selected @endif value="{{$state->state_name}}">{{$state->state_name}}</option>
                                                                        @endforeach
                                                                        @endif
                                                                  
    
                                                                </select>
                                                            
                                                            @elseif($label->data_type == 'select_option')
                                                                @php
                                                                    $values = $label->values;
                                                                    $arr = json_decode($values);
                                                                @endphp
                                                                @if(!empty($arr))
                                                                    <select class="form-select"
                                                                            name="{{$label->column_name}}">

                                                                             <option value="">Select Option</option>
                                                                            
                                                                        @php
                                                                            foreach($arr as $val)
                                                                            {
                                                                        @endphp
                                                                        <option @if($lead[$label->column_name] == $val) selected @endif
                                                                            value="{{$val}}">{{ucwords($val)}}</option>
                                                                        @php
                                                                            }
                                                                        @endphp
                                                                    </select>
                                                                @endif

                                                                @elseif($label->data_type == 'date')
    @php
        $dateValue = (!empty($lead[$label->column_name]) && $lead[$label->column_name] !== '0000-00-00')
                     ? \Carbon\Carbon::parse($lead[$label->column_name])->format('m/d/Y')
                     : '';
    @endphp
    <input type="text" name="{{$label->column_name}}"
           class="form-control"
           value="{{ $dateValue }}"
           @if($label->required == 1) required @endif
           placeholder="Enter {{$label->title}}"
           data-inputmask="'alias': 'mm/dd/yyyy'"
           data-mask />








                                                                @elseif($label->data_type == 'datetime-local')
                                                                <input type="datetime-local" name="{{$label->column_name}}"
                                                                       
                                                                       class="form-control" value="{{$lead[$label->column_name]}}"
                                                                       
                                                                       @if($label->required == 1) required
                                                                       @endif placeholder="Enter {{$label->title}}"/>

                                                                @elseif($label->data_type == 'email')
                                                                <input type="email" name="{{$label->column_name}}"
                                                                       
                                                                       class="form-control" value="{{$lead[$label->column_name]}}"
                                                                       
                                                                       @if($label->required == 1) required
                                                                       @endif placeholder="Enter {{$label->title}}"/>


                                                                @else
                                                                <input style="text-transform: capitalize;" maxlength="{{$label->number_length}}" type="text" name="{{$label->column_name}}" @if($label->required == 1) required @endif
                                                                       @if($label->data_type == 'number' || $label->data_type == 'currency') oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" @endif
                                                                       @if(!empty($lead[$label->column_name])) value="{{$lead[$label->column_name]}}" @endif

                                                                       class="form-control @if($label->data_type == 'date') datepicker @endif 
                                                                        @if($label->required == 1) required
                                                                        @endif placeholder="Enter {{$label->title}}" @if($label->data_type == 'phone_number') data-inputmask="'mask':[ '(999) 999-9999']" data-mask 
                                                                       @endif/>

                                                            @endif

                                                        </div>
                                                        </div>

                                                    </div>
                                                @endif

                                                @endif
                                            @endforeach
                                        @endif
                                        <div class="col-md-3 form-group">
    <label class="">Group</label>
    @php
// Decode $lead->group_id from JSON to an array
$leadGroupIds = isset($lead['group_id']) ? (is_array($lead['group_id']) ? $lead['group_id'] : json_decode($lead['group_id'], true)) : [];

// Ensure group IDs are treated as strings for comparison
$leadGroupIds = array_map('strval', $leadGroupIds); // Convert to strings if necessary

// Get the extension from the session
$sessionExtension = session()->get('extension');

// Get all group_ids from $map where the extension matches the session extension
$matchedGroups = collect($map) // Ensure $map is a collection
    ->filter(function ($item) use ($sessionExtension) {
        return $item->extension === $sessionExtension; // Adjust this according to your data structure
    })
    ->pluck('group_id');

// Get the unique group IDs
$uniqueGroupIds = $matchedGroups->unique()->values(); // Ensure we have a collection

// Fetch group names based on matched group IDs
$matchedGroupNames = collect($group) // Ensure $group is a collection
    ->whereIn('id', $uniqueGroupIds)
    ->pluck('title', 'id'); // Assuming 'title' is the field for group name
@endphp

<select class="select2 form-control" multiple="multiple" name="group_id[]" autocomplete="off" data-placeholder="Select Group" id="group_id">
    @if($matchedGroupNames->isNotEmpty()) <!-- Check if collection is not empty -->
        @foreach($matchedGroupNames as $groupId => $groupName)
            <option value="{{ $groupId }}"
                @if(in_array(strval($groupId), $leadGroupIds)) 
                    selected
                @endif
            >
                {{ ucwords($groupName) }}
            </option>
        @endforeach
    @endif
</select>

</div>


                                    </div>
                                
                                </div>
                            
                            </div>
                          
                                    </div>


                                                    <div class="col-md-3">

                                                        <div class="box">
                    <div class="box-body">

           <div class="row">

              <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror" >
                  <label class="form-label">Created By </label> 
                  <div class="input-group mb-3" style="background: blue;color: white;font-size: 15px; font-weight: bold;height: 34px;text-align: center;padding: 5px;">

                  @php
    // Convert the array to a collection
    $usersCollection = collect($users);
    // Find the user with the matching ID
    $createdByUser = $usersCollection->firstWhere('id', $lead['created_by']);
@endphp

@if($createdByUser)
    <option value="{{ $createdByUser->id }}">
        {{ ucwords($createdByUser->first_name) }} {{ ucwords($createdByUser->last_name) }}
    </option>
@endif


                  </div>
                </div>
              </div>


                    <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror">
                  <label class="form-label">Lead Status * </label> 
                  <div class="input-group mb-3">
                                                <select class="form-select bg-danger" onchange="updateLeadStatus(this.value,{{$lead['id']}},'{{$lead['lead_type']}}','{{$lead['assigned_to']}}')"  name="lead_status" id="lead_status">
                                                    @if(!empty($lead_status))
                                                        @foreach($lead_status as $status)
                                                            <option value="{{$status->lead_title_url}}" @if($lead['lead_status'] == $status->lead_title_url) selected="selected" @endif >{{$status->title}}</option>
                                                        @endforeach
                                                    @endif
                                                </select>
                  </div>
                </div>
              </div>



               <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror">
                  <label class="form-label">Assigned To </label> 
                  <div class="input-group mb-3">
                                                <select class="form-select bg-info" onchange="updateLeadStatus('{{$lead['lead_status']}}',{{$lead['id']}},'{{$lead['lead_type']}}',this.value)" name="assigned_to" id="assigned_to">
                                                    @if(Session::get("level") > 5)
                                                    @if(!empty($users))
          
                                                        @foreach($sortedUsers as $list)
                @if($list->is_deleted == '0' && $list->user_level < 9)
                                                        
                                                            <option @if($lead['assigned_to'] == $list->id) selected="selected" @endif
                                                                value="{{$list->id}}">{{ucwords($list->first_name)}} {{ucwords($list->last_name)}}</option>
                                                    @endif
                                                                
                                                        @endforeach
                                                    @endif

                                                    @else
                                                    <option
                                                                value="{{Session::get("userId")}}">{{Session::get("first_name")}} {{Session::get("last_name")}}</option>

                                                    @endif

                                                </select>
                  </div>
                </div>
              </div>


          


               <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror">
                  <label class="form-label">Select Lead Type </label> 
                  <div class="input-group mb-3">
                                                <select class="form-select bg-warning" name="lead_type" id="lead_type" onchange="updateLeadStatus('{{$lead['lead_status']}}',{{$lead['id']}},this.value,'{{$lead['assigned_to']}}')">
                                                    <option value="">Select Lead Type</option>
                                                    <option @if($lead['lead_type'] == 'hot') selected="selected" @endif value="hot">Hot</option>
                                                    <option @if($lead['lead_type'] == 'warm') selected="selected" @endif value="warm">Warm</option>
                                                    <option @if($lead['lead_type'] == 'cold') selected="selected" @endif value="cold">Cold</option>

                                                </select>
                  </div>
                </div>
              </div>

              

           


               <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror">
                  <label class="form-label">Select Lead Source <span style="color: red;">*</span></label> 
                  <div class="input-group mb-3">
                                                <select class="form-select bg-primary" required name="lead_source_id" id="lead_source_id">
                                                    <option value="">Select Lead Source</option>

                                                    @if(!empty($lead_source))
                                                        @foreach($lead_source as $source)
                                                            <option @if($lead['lead_source_id'] == $source->unique_id) selected="selected" @endif
                                                                value="{{$source->unique_id}}">{{$source->source_title}}</option>
                                                        @endforeach
                                                    @endif
                                                </select>
                  </div>
                </div>
              </div>
              </div>
</div>
</div>

</div>
</div>

          
     <div class="box-footer">
  <div class="footer-actions">
    
    <a href="/leads" class="btn btn-warning">
      <i class="ti-trash"></i> Cancel
    </a>

    <a onclick="window.location.reload();" class="btn btn-danger">
      <i class="ti-reload"></i> Reset
    </a>

    <button type="submit" name="submit" value="add" class="btn btn-primary">
      <i class="ti-save-alt"></i> Submit
    </button>

  </div>
</div>

            </form>
                       
                
              </div>
              <!-- /.box-body -->
          
            <!-- /.box -->      
        </div>  
       
      </div>
  </section>

@endif

<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>


<script>

    var sel = $("#lead_status").val();
    var type = $("#lead_type").val();
    var assigned_to_old = $("#assigned_to").val();




    function updateLeadStatus(lead_status,lead_id,lead_type,assigned_to)
    {
        
        //alert(lead_type);
        /*var result = confirm("Want to Change?");
        if (result)
        {*/

             swal(
        {
            title: `Are you sure you want to change this record?`,
            //text: "If you change this, it will be gone changed.",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willDelete)=>
        {
            if (willDelete)
            {
                $("#loading").show();
        $.ajaxSetup({
            headers: 
            {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }});

        jQuery.ajax({
            url: "{{ url('/update/lead-status') }}",
            method: 'post',
            data:
            {
                lead_id: lead_id,lead_status:lead_status,lead_type:lead_type,assigned_to:assigned_to
            },
            success: function(result)
            {
        $("#loading").hide();

                swal("Success!", "Changed Successfully", "success")
                //window.location.reload(1);
            }});
            }
            else
            {
                //alert(assigned_to);
                $("#lead_type").val(type);
                $("#lead_status").val(sel);
                $("#assigned_to").val(assigned_to_old);


            }
        }
        );
            
        /*}
        else
        {
            $("#lead_status").val(sel);
            $("#lead_type").val(type);

        }*/
    }
</script>


         <script>
        // Automatically remove duplicates on page load
        (function removeDuplicates() {
            const select = document.getElementById('assigned_to');
            const seenValues = new Set();

            for (let i = select.options.length - 1; i >= 0; i--) {
                const value = select.options[i].value;
                if (seenValues.has(value)) {
                    select.remove(i); // Remove duplicate option
                } else {
                    seenValues.add(value); // Add unique value to the set
                }
            }
        })();
    </script>
    

     
@endsection
