@extends('layouts.app')
@section('title', 'View Lead Info')


@section('content')
<style>
      html{
       height: auto;
    min-height: 100%;
    
    overflow-y: auto;
      }
      #preloader {
            background-color: black;
            bottom: 0;
            left: 0;
            position: fixed;
            right: 0;
            top: 0;
            z-index: 2147483647;
        }
        #preloader-status {
            background: center center no-repeat;
            height: 80px;
            left: 50%;
            top: 50%;
            position: absolute;
            width: 80px;
            margin: -40px 0 0 -40px;
        }
        #activity{
    max-height: 250px; /* Adjust the height as needed */
    overflow-y: auto;
    padding-right: 15px; /* To avoid content hidden by scrollbar */
        }
        #settings{
    max-height: 250px; /* Adjust the height as needed */
    /* overflow-y: auto; */
    padding-right: 15px;   
        }
        #usertimeline{
    max-height: 250px; /* Adjust the height as needed */
    overflow-y: auto;
    padding-right: 15px;   
        }
       
        .status-Approved {
    background-color: green;
    color: white;
}

.status-Declined {
    background-color: red;
    color: white;
}

.status-Waiting {
    background-color: yellow;
    color: black;
}
/* Lower the z-index of the select2 field when modal is open */
.select2 {
    z-index: 1 !important; /* Lower the z-index of the select2 input */
}

  </style>
    
    <style>
    section.waiting-section {
        display: none; /* Initially hidden */
        text-align: center;
        background-color: #ffffffbd;
        position: fixed; /* Use fixed to ensure it stays in the viewport */
        width: 100%;
        height: 100vh; /* 100% of the viewport height */
        top: 0;
        left: 0;
        z-index: 2;
        display: flex;
        justify-content: center; /* Horizontally center */
        align-items: center; /* Vertically center */
    }

    section.waiting-section div.waiting-box {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    section.waiting-section p {
        font-size: 16px;
    }

    section.waiting-section .payment-completed-text, section.waiting-section .redirect-timer {
        font-size: 26px;
    }

    /* Chrome, Safari, Edge, Opera */
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
        -webkit-appearance: none;
        margin: 0;
    }

    /* Firefox */
    input[type=number] {
        -moz-appearance: textfield;
    }
</style>
<!-- CSS -->
<!-- CSS -->
<style>
    .time-control {
        position: relative;
        width: 80px; /* Adjust width as needed */
    }

    .time-control input {
        width: 100%;
        text-align: center;
        padding-right: 30px; /* Space for buttons */
    }

    .arrow-buttons {
        position: absolute;
        top: 50%;
        right: 5px;
        transform: translateY(-50%);
        display: flex;
        flex-direction: column;
        gap: 2px;
    }

    .arrow-btn {
        border: none;
        background: none;
        cursor: pointer;
        font-size: 12px;
        line-height: 1;
        padding: 0;
        width: 20px;
        height: 15px;
    }

    .arrow-btn:focus {
        outline: none;
    }
  
</style>

<style>
    #tickets td:nth-child(3) {
        /* white-space: pre-wrap;   */
        word-wrap: break-word;   /* break long words if necessary */
        max-width: 230px;        
        overflow-wrap: break-word;
    }
</style>


<!-- Main content -->

  <link rel="stylesheet" href="{{asset('assets/plugins/select2/css/select2.min.css')}}">
  <link rel="stylesheet" href="{{asset('assets/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css')}}">
  <script src="{{asset('assets/plugins/select2/js/select2.full.min.js')}}"></script>

<section class="content">

     <div class="row">       
    <div class="col-12">
        <div class="box" style="margin-bottom:10px;">
          <div id="preloader"style="display:none;">
                      <div id="preloader-status">
                        <img  src="{{asset('assets/images/loader-30px.gif')}}">
                        </div>  
                        </div>
        <div class="box-body">   
            <div class="d-flex flex-column flex-md-row align-items-start align-items-md-center justify-content-between mb-3">
    <h4 class="box-title text-info mb-0">
        <i class="fa fa-user fa-sx"></i>
        @if(isset($lead) && isset($lead['id']) && $lead_id == $lead['id'])
            @if(!empty($lead['company_name']))
                View Lead Details For {{ $lead['company_name'] }}({{$lead_id}})
            @else
                View Lead Details for lead id-{{$lead_id}}
            @endif
        @else
            View Lead Details for lead id-{{$lead_id}}
        @endif
    </h4>

    <div class="mt-2 mt-md-0 d-flex gap-2">
        <a href="{{url('leads')}}" type="button"
           class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm">
           <i class="fa fa-eye"></i> Leads
        </a>          
        <a id="copy-lead" href="javascript:void(0);" type="button"
           class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm">
           <i class="fa fa-copy"></i> Copy
        </a>
    </div>
</div>

        <!-- <h4 class="box-title text-info mb-0"><i class="fa fa-user fa-sx"></i>
    @if(isset($lead) && isset($lead['id']) && $lead_id == $lead['id'])
        @if(!empty($lead['company_name']))
            View Lead Details For {{ $lead['company_name'] }}({{$lead_id}})
        @else
            View Lead Details for lead id-{{$lead_id}}
        @endif
    @else
        View Lead Details for lead id-{{$lead_id}}
    @endif
</h4>

              <a style="float: right;" href="{{url('leads')}}" type="button" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-eye"></i> Leads</a>          
              <a id="copy-lead"style="float: right;margin-right:10px;" href="javascript:void(0);" type="button" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-copy"></i> Copy</a>           -->

             <hr class="my-15">
       
           
   
    <div class="row">
    <div class="col-xl-4 col-lg-6 col-12" style="padding-right:1px;">
        <div class="box box-widget widget-user-2">
           <!--  <div class="widget-user-header bg-primary d-flex align-items-center" style="padding:5px 10px 5px 20px;">

                <i class="fa fa-user-plus" style="font-size:20px;"></i>
                <h6 class="widget-user-username" style="margin-left:10px;padding:0px;font-size:20px;"> Christopher &nbsp;Heatherly
                </h6>
                <span style="font-size:15px;display:none;" id="userEmail"><i class="fa fa-envelope"></i> abhi2112mca@gmail.com</span>
                <div style="margin-left:68px;">

                    <a class="btn btn-primary btn-sm" href="https://portal.voiptella.com/lead-data/0/9024412385"><i class="fa fa-edit"></i></a>
                </div>

            </div> -->

            <!-- Add the bg color to the header using any of the bg-* classes -->




            <div class="box box bt-3 border-primary">
                <div class="box-body box-profile" style="padding-top:0.5rem;min-height: unset !important;">
                    <div class="row">
                        <div>
                            <div class="table-responsive ">
                                <table id="tickets" class="table table-hover no-padding dataTable">
                                    <tbody>
                                        @php

                                        $fields_remove = ["Use Of Funds","Owner 2 First Name","Owner 2 Last Name","Owner 2 Home Address","Owner 2 Email","Owner 2 Cellphone","Owner 2 Date Of Birth","Owner 2 Ownership %","Owner 2 Credit Score","Owner 2 SSN","Owner 2 City","Owner 2 State","Owner 2 Zip","Credit Score","Fax","Entity Type"
                                        ];



                                       $in_array =array();
                                        $array1 = array();
                                        @endphp
                                        @if(!empty($labels))
                                        @foreach($labels as $label)
                                        @if($label->status == 1)

                                        @php 
                                        $in_array[]  = $label->title 
                                        @endphp

                                        @if($label->column_name != 'unique_url')

                                        @if(empty($lead[$label->column_name]))
                                        @php

                                        $array1[] =$label->title;
                                        @endphp

                                        @endif



                                        <tr @if($label->label_title_url != 'email') style="text-transform: capitalize;" @endif>
                                            <th style="white-space: nowrap;padding:0.5rem;">
                                                {{$label->title}}
                                            </th>
                                            <td style="padding:0.5rem;"> 
                                               @if($label->data_type == 'phone_number') 
                                               @php
                                                $value = \App\Helper\Helper::phone_number($lead[$label->column_name]) ;
                                                @endphp


                                               @if($value == '0')
                                               @else
                                               {{  $value }}
                                               @endif


                                                
                                                
                                                




                                            @elseif($label->data_type == 'currency') 

                                            @if(empty($lead[$label->column_name]))
                                            
                                            @else
                                               {{number_format($lead[$label->column_name])}}
                                            @endif
                                            @elseif($label->data_type == 'date')
                                            @php
        $value = \App\Helper\Helper::formatDateMMDDYYYY($lead[$label->column_name])
    @endphp
    @if($value !== '')
        {{ $value }}
    @endif
                                            @else
                                            @if(isset($lead[$label->column_name]))

                                              @if($lead[$label->column_name] == '0')
                                               @else
                                               {{$lead[$label->column_name]}}
                                               @endif
                                            
                                            @endif
                                            @endif
                                            


                                            </td>

                                        </tr>
                                        @endif


                                        @endif
                                        @endforeach

                                        @php

                                       // echo "<pre>";print_r($in_array);

                                        $remaining_values = array_diff($in_array, $fields_remove);

                                        $exists = '';
                                        $status_value = '0';
                                        $l=1;
                                        foreach ($array1 as $value) {
                                            if (in_array($value, $remaining_values)) {
                                                $exists .= "<b>" .$l.". ". $value . "</b><br>";
                                                $status_value = '1';
                                            $l++;
                                            }
                                        }

                                        // Print the values inside an HTML heading with separate lines
                                        //echo "<h3>Please fill the  <b>" . nl2br($exists) . "</b></h3> value";

                                        //echo $status_value;
                                       






                                        $old_created = strtotime($lead['created_at']);
                                        $new_created = date('m/d/Y h:i:s A', $old_created);
                                        $old_modified = strtotime($lead['updated_at']);
                                        $new_modified = date('m/d/Y h:i:s A', $old_modified);
                                        $lead_type = $lead['lead_type'];
                                        if( $lead_type == 'hot')
                                        {
                                            $style ="background-color:#a90329!important;color:#fff;text-align:center;";
                                        }
                                        else if( $lead_type == 'warm')
                                        {
                                            $style ="background-color:#c79121!important;color:#fff;text-align:center;";
                                        } 
                                        else if( $lead_type == 'cold')
                                        {
                                            $style ="background-color:#12679b!important;color:#fff;text-align:center;";
                                        }
                                        else
                                        {
                                            $style="text-align:center;";
                                        } 
                                        @endphp



                                        <tr>
                                            <th style="white-space: nowrap;padding:0.5rem;">Created At</th>
                                            <td style="padding:0.5rem;"> {{$new_created}}
                                            </td>
                                        </tr>

                                         <tr>
                                            <th style="white-space: nowrap;padding:0.5rem;">Updated At</th>
                                            <td style="padding:0.5rem;"> {{$new_modified}}
                                            </td>
                                        </tr>


                                        @endif
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>


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


    </div>


<!-- Button to Open Modal -->
<!-- <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal">
  Show Required Fields
</button> -->

<!-- Bootstrap Modal -->
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Please Update the Below Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <?php echo nl2br($exists);  ?>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

        <div class="col-12 col-lg-6 col-xl-6" style="padding-right:1px;">
        
        <div class="nav-tabs-custom">
                    <ul class="nav nav-tabs" role="tablist">


                        <li class="nav-item"> <a class="nav-link active"  data-bs-toggle="tab" href="#usertimeline" role="tab" aria-controls="home5" aria-expanded="true"><span class="hidden-sm-up"><i class="ion-home"></i></span> <span class="hidden-xs-down">Notes</span></a> </li>
                        <input type="hidden" name="lead-detail-class-box" class="lead-detail-class-box" value="">
                        <li class="nav-item"> <a class="nav-link"  data-bs-toggle="tab" href="#activity" role="tab" aria-controls="profile" id="btn_send_sms" data-contact="{{Request::get('phone_number')}}" ><span class="hidden-sm-up"><i class="ion-person"></i></span> <span class="hidden-xs-down">Updates</span></a></li>
                        <li class="nav-item"> <a class="nav-link"  data-bs-toggle="tab" href="#settings" role="tab" aria-controls="profile" data-emailid="" data-leadid="" data-listid="39"><span class="hidden-sm-up"><i class="ion-person"></i></span> <span class="hidden-xs-down">Submissions Update</span></a></li>
                        <li class="nav-item"> <a class="nav-link"  data-bs-toggle="tab" href="#api_logs" role="tab" aria-controls="profile" data-emailid="" data-leadid="" data-listid="39"><span class="hidden-sm-up"><i class="ion-person"></i></span> <span class="hidden-xs-down">Api Logs</span></a></li>

                        @if($is_copied==1)
                        <li class="nav-item"> <a class="nav-link"  data-bs-toggle="tab" href="#related" role="tab" aria-controls="profile" data-emailid="" data-leadid=""><span class="hidden-sm-up"><i class="ion-person"></i></span> <span class="hidden-xs-down">Related</span></a></li>
                        @endif



                    </ul>
  

        <div class="tab-content " style="padding: 0.50rem !important;min-height: unset !important;background: unset !important;">

        <div class=" active tab-pane" id="usertimeline">
           


       <div class="col-md-12">
                        <div class="jarviswidget jarviswidget-sortable" role="widget">
                            <div role="content">
                                <div class="updates">
                                                                                            <div class="jarviswidget jarviswidget-sortable" role="widget">
                                                    <div role="content" class="no-border no-padding clearfix">
                                                        <div class="widget-body no-padding no-margin clearfix">
                                                            <form class="customerNotes oh form-vertical" id="notes-form-1"  method="post">                                                                <input type="hidden" value="" id="notes_user_emails" name="EmployeeNotes[user_emails]">
                                                                <div class="row">
                                                                <div class="col-md-10">
                                                                

                                                                <textarea type="text" name="notes" class="form-control" id="notes" required placeholder="Write Notes" ></textarea>
                                                            </div>
                                                            <div class="col-md-2">
                                                                
                                                                <button class="btn btn-primary btn-sm btn submitNotes"  style="margin:8px 8px 8px 8px;"  name="yt1" type="button">Save</button>                   </div>


                                                                </div>

                                                                                                             </form>                                                        </div>
                                                    </div>
                                                </div>
                                                                                        <div id="lead-notes"><input type="hidden" id="nextSibling" value="6859"><input type="hidden" id="prevSibling" value="">
            <ul style="">

                @if(!empty($notification))
                                        @foreach($notification as $message)
                <li><div>
                <span class="notes-align">

                    @if($message->user_id != '0')
                    <strong  class="">@if(!empty($users))
                        @foreach($users as $list)
                        @if($list->id == $message->user_id)<?php echo "@"; ?>{{strtolower($list->first_name)}}
                        @endif
                        @endforeach
                        @endif
                        @else
                        @endif
                    </strong>@if($message->type == '1')  {!! $message->message !!} @elseif($message->type == '0') {!! $message->message !!} @endif
                    
                </span>
                <span class="pull-right date-update" style="font-size:10px;">
            
                                                                                        <!-- @php

                                                                                        $formattedDate = App\Helper\Helper::formatDateMMDDYYYY($message->created_at);
                                                                                        $old_date_timestamp = strtotime($message->created_at);
                                                                                        $time = date('h:i:s A', $old_date_timestamp);
                                                                                        @endphp
                                                {{$formattedDate}}
                                                {{--{{$date}}&nbsp;{{$time}}--}} {{$time}}</span> -->
                                                {{\Carbon\Carbon::parse($message->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}

                                                <!-- {{ \Carbon\Carbon::parse($message->created_at)->format('m/d/Y H:i A')}} -->
        
                                            </div>
                </li>

                @endforeach
                @endif
                
                
                
                </ul>    <div class="text-center"></div>    
              </div>
      </div>

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


            </div>    
            <!-- /.tab-pane -->
             <!--related-->
             <div class=" tab-pane" id="related">           

<div class="box no-shadow">             
  <div class="col-md-12 ">
            <div class="jarviswidget jarviswidget-sortable" role="widget">
                <div role="content">
                    <div class="updates">
                                                                               
<div id="lead-notes"><input type="hidden" id="nextSibling" value="6859"><input type="hidden" id="prevSibling" value="">
<ul style="">
<!-- Please click on this <a href="{{ url('leads/view?id=' . $previous_id) }}">Link</a> to go to original lead.< -->
<a href="{{ url('leads/view?id=' . $previous_id) }}">Lead ID - {{$previous_id}}</a>
&nbsp; {{ strtoupper(str_replace('_', ' ', $preLeadStatus)) }} &nbsp;
{{ \Carbon\Carbon::parse($preLeadUpdated)->format('m/d/Y') }}



</ul>
      <div class="text-center"></div>    
</div>
</div>

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

</div>
         <!--related-->
             <div class=" tab-pane" id="api_logs">           

<div class="box no-shadow">             
  <div class="col-md-12 ">
            <div class="jarviswidget jarviswidget-sortable" role="widget">
                <div role="content">
                    <div class="updates">
                                                                               
<div id="lead-notes"><input type="hidden" id="nextSibling" value="6859"><input type="hidden" id="prevSibling" value="">
 <ul style="list-style: none;padding: 0px;"> 
    @if(!empty($submission_logs))
                                            @foreach($submission_logs as $message)
                    <li>
                    <div>
                    <span class="notes-align">

                        @if($message->user_id != '0')
                        <strong  class="">
                            @if(!empty($users))
                            @foreach($users as $list)
                            @if($list->id == $message->user_id)<?php echo "@"; ?>{{strtolower($list->first_name)}}  
                            @php
                            // Extract lender names from the message using regex that can handle HTML tags and multiple names separated by commas
                            $lenderNames = [];

                            // Adjust the regex to extract lender names inside <b> tags after "to lender" and split by comma
                            if (preg_match('/to lender\s*<b>([\w\s,]+)<\/b>/', $message->message, $matches)) {
                                $lenderNames = array_map('trim', explode(',', $matches[1])); // Split by comma and trim each name
                            }

                            // Debugging to ensure we have extracted the lender names correctly
                            if (empty($lenderNames)) {
                                //dd("Lender names not found in message: " . $message->message);
                            }

                            // Iterate over all lender names and try to match each one
                            $statuses = [];
                            foreach ($lenderNames as $lenderName) {
                                // Find the matched lender by lender name
                                $matchedLender = collect($SendlendersList)->first(function($lender) use ($lenderName) {
                                    return stripos($lender->lender_name, $lenderName) !== false; // Case-insensitive comparison
                                });

                                // If a lender is matched, find the status
                                if ($matchedLender) {
                                    $matchedSendLead = collect($matchedLender->crm_send_lead_to_lender)
                                        ->where('lead_id', $lead_id)
                                        ->first(function($sendLead) use ($message) {
                                            return $sendLead->user_id == $message->user_id;
                                        });

                                    // If we found a valid send lead entry, add the status to the list
                                    if ($matchedSendLead) {
                                        $status = $matchedSendLead->lender_status_id;
                                        $statuses[$lenderName] = collect($lender_status)->where('id', $status)->first()->title ?? 'Unknown';
                                    } else {
                                        $statuses[$lenderName] = 'Unknown'; // No status found for this lender
                                    }
                                } else {
                                    $statuses[$lenderName] = 'Unknown'; // No lender found
                                }
                            }
                        @endphp
                        
                        </span>
                            @endif
                            @endforeach
                            @endif
                            @else
                            @endif
                        </strong>@if($message->type == '3')  {!! $message->message !!}  @endif
                            <!-- Display the statuses for each lender, excluding those with unknown status -->
                            @if (!empty($statuses))
                                @foreach ($statuses as $lenderName => $status)
                                    @if ($status !== 'Unknown') <!-- Only display if the status is known -->
                                        <span class="status-label" style="margin-left: 10px;">
                                        ( Lender: {{ $lenderName }}, Status: {{ $status }})
                                        </span>
                                    @endif
                                @endforeach
                            @endif


                        <!-- Add status from SendlendersList if user_id and lead_id match -->
                        
                    </span>
                    <span class="pull-right date-update" style="font-size:10px;">
                
                    <!-- {{ \Carbon\Carbon::parse($message->created_at)->format('m/d/Y H:i A')}} -->
                    {{\Carbon\Carbon::parse($message->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}

                    </span></div>
                    </li>

                    @endforeach
                    @endif
                    </ul>        
      <div class="text-center"></div>    
</div>
</div>

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

</div>
            <div class=" tab-pane" id="activity">           

            <div class="box no-shadow">             
              <div class="col-md-12 ">
                        <div class="jarviswidget jarviswidget-sortable" role="widget">
                            <div role="content">
                                <div class="updates">
                                                                                           
        <div id="lead-notes"><input type="hidden" id="nextSibling" value="6859"><input type="hidden" id="prevSibling" value="">
                    <ul style="">@if(!empty($updates))
                                                @foreach($updates as $message)
                        <li><div>
                        <span class="notes-align">

                            @if($message->user_id != '0')
                            <strong  class="">@if(!empty($users))
                                @foreach($users as $list)
                                @if($list->id == $message->user_id)<?php echo "@"; ?>{{strtolower($list->first_name)}}
                                @endif
                                @endforeach
                                @endif
                                @else
                                @endif
                            </strong>@if($message->type == '2')  {!! $message->message !!} @elseif($message->type == '1')  {!! $message->message !!} @elseif($message->type == '0') {!! $message->message !!} @endif
                            
                        </span>
                        <span class="pull-right date-update" style="font-size:10px;">
       
            {{\Carbon\Carbon::parse($message->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}

        </span>
        </div>
                </li>

                @endforeach
                @endif
               </ul>    <div class="text-center"></div>    
</div>
</div>

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

            </div>
            <!-- /.tab-pane -->

            <div class="tab-pane" id="settings">        

            <div class="box no-shadow"> 
             <div class=" active tab-pane" id="usertimeline">
           


       <div class="col-md-12">
                        <div class="jarviswidget jarviswidget-sortable" role="widget">
                            <div role="content">
                                <div class="updates">
                                                                                            <div class="jarviswidget jarviswidget-sortable" role="widget">
                                                    <div role="content" class="no-border no-padding clearfix">
                                                        <div class="widget-body no-padding no-margin clearfix">
                                                            <form class="customerNotes oh form-vertical" id="notes-form-1"  method="post">                                                                <input type="hidden" value="" id="notes_user_emails" name="EmployeeNotes[user_emails]">
                                                              <!--   <div class="row">
                                                                <div class="col-md-10">
                                                                <textarea placeholder="Submission Updates" style="width: 100%;border:revert;" rows="2" cols="2" class="publisher-input auto-expand" id="append_customer_notes" name="EmployeeNotes[notes]"></textarea>
                                                            </div>
                                                            <div class="col-md-2">
                                                                `
                                                                <button class="btn btn-primary btn-sm btn" id="saveCustomerNotes" style="margin:8px 8px 8px 8px;"  name="yt1" type="button">Save</button>                   </div>
                                                                </div> -->

                                                                                                             </form>                                                        </div>
                                                    </div>
                                                </div>
                                                                                        <div id="lead-notes"><input type="hidden" id="nextSibling" value="6859"><input type="hidden" id="prevSibling" value="">
            
                                                                                         <ul style="overflow-y-scroll">@if(!empty($submission))
                                        @foreach($submission as $message)
                <li><div>
                <span class="notes-align">

                    @if($message->user_id != '0')
                    <strong  class="">
                        @if(!empty($users))
                        @foreach($users as $list)
                        @if($list->id == $message->user_id)<?php echo "@"; ?>{{strtolower($list->first_name)}}  
                        @php
                      // Extract lender names from the message using regex that can handle HTML tags and multiple names separated by commas
                     $lenderNames = [];

                         // Adjust the regex to extract lender names inside <b> tags after "to lender" and split by comma
                       if (preg_match('/to lender\s*<b>([\w\s,]+)<\/b>/', $message->message, $matches)) {
                        $lenderNames = array_map('trim', explode(',', $matches[1])); // Split by comma and trim each name
                      }

                       // Debugging to ensure we have extracted the lender names correctly
                     if (empty($lenderNames)) {
                     //dd("Lender names not found in message: " . $message->message);
                          }

                   // Iterate over all lender names and try to match each one
                   $statuses = [];
                  foreach ($lenderNames as $lenderName) {
                    // Find the matched lender by lender name
                   $matchedLender = collect($SendlendersList)->first(function($lender) use ($lenderName) {
                return stripos($lender->lender_name, $lenderName) !== false; // Case-insensitive comparison
               });

        // If a lender is matched, find the status
        if ($matchedLender) {
            $matchedSendLead = collect($matchedLender->crm_send_lead_to_lender)
                ->where('lead_id', $lead_id)
                ->first(function($sendLead) use ($message) {
                    return $sendLead->user_id == $message->user_id;
                });

            // If we found a valid send lead entry, add the status to the list
            if ($matchedSendLead) {
                $status = $matchedSendLead->lender_status_id;
                $statuses[$lenderName] = collect($lender_status)->where('id', $status)->first()->title ?? 'Unknown';
            } else {
                $statuses[$lenderName] = 'Unknown'; // No status found for this lender
            }
        } else {
            $statuses[$lenderName] = 'Unknown'; // No lender found
        }
    }
@endphp




    




                       
                    </span>
                        @endif
                        @endforeach
                        @endif
                        @else
                        @endif
                    </strong>@if($message->type == '2')  {!! $message->message !!} @elseif($message->type == '1')  {!! $message->message !!} @elseif($message->type == '0') {!! $message->message !!} @endif
<!-- Display the statuses for each lender, excluding those with unknown status -->
@if (!empty($statuses))
    @foreach ($statuses as $lenderName => $status)
        @if ($status !== 'Unknown') <!-- Only display if the status is known -->
            <span class="status-label" style="margin-left: 10px;">
               ( Lender: {{ $lenderName }}, Status: {{ $status }})
            </span>
        @endif
    @endforeach
@endif


                       <!-- Add status from SendlendersList if user_id and lead_id match -->
                    
                </span>
                <span class="pull-right date-update" style="font-size:10px;">
            
                <!-- {{ \Carbon\Carbon::parse($message->created_at)->format('m/d/Y H:i A')}} -->
                {{\Carbon\Carbon::parse($message->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}

                 </span></div>
                </li>

                @endforeach
                @endif</ul>        <div class="text-center"></div>    
</div>
</div>

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

           
            </div>            
            </div>
          
            <!-- /.tab-pane -->
        </div>
        <!-- /.tab-content -->
        </div>
        <!-- /.nav-tabs-custom -->
    </div>
    <div class="row">
<div class="table-responsive">
@if(!empty($SendlendersList))


<?php
$lenderStatusCollection = $lender_status instanceof \Illuminate\Support\Collection ? $lender_status : collect($lender_status);

usort($SendlendersList, function($a, $b) use ($lead_id, $lenderStatusCollection) {
    $statusA = collect($a->crm_send_lead_to_lender)->where('lead_id', $lead_id)->first();
    $statusB = collect($b->crm_send_lead_to_lender)->where('lead_id', $lead_id)->first();

    $statusIdA = $statusA ? $statusA->lender_status_id : '';
    $statusIdB = $statusB ? $statusB->lender_status_id : '';

    // Get the status objects using the ID from $lenderStatusCollection
    $statusObjA = $lenderStatusCollection->where('id', $statusIdA)->first();
    $statusObjB = $lenderStatusCollection->where('id', $statusIdB)->first();

    // Get the status titles or fallback to an empty string if not found
    $titleA = $statusObjA ? $statusObjA->title : '';
    $titleB = $statusObjB ? $statusObjB->title : '';

    // Define the sorting order for statuses between "Approved" and "Declined" (including a default option)
    $sortingOrder = ['Approved', 'Default', 'Declined'];

    // Get the index of status titles in the sorting order array
    // If title is not in the sorting order, set the index to count($sortingOrder) to sort them between "Approved" and "Declined"
    $indexA = in_array($titleA, $sortingOrder) ? array_search($titleA, $sortingOrder) : 1;
    $indexB = in_array($titleB, $sortingOrder) ? array_search($titleB, $sortingOrder) : 1;

    // Compare the indexes for sorting
    return $indexA - $indexB;
});
?>


<table id="tickets" class="table mt-0 table-hover table-bordered">
    <tr>
        <th >Lender's Name</th>
        <th >Status</th>
        <th >Last Added Note</th>
        <th>Notes</th>
    </tr>
    @foreach($SendlendersList as $list)
    <tr id="lender_note_{{ $list->id }}_{{ $lead_id }}">
        <td>
            {{ $list->lender_name }}
 
        </td>
        <td>
         @php
        $sendLead = collect($list->crm_send_lead_to_lender)->where('lead_id', $lead_id)->first();
        $selectedStatus = $sendLead ? $sendLead->lender_status_id : '';
        @endphp
 
       <select class="form-select lender-status-select" name="lender_status" id="lender_status_{{ $list->id }}_{{ $lead_id }}" data-original-value="{{ $selectedStatus }}" onchange="submitLenderStatus({{ $list->id }}, {{ $lead_id }}, this.value)">
        <option value="">Select </option>
         @foreach($lender_status as $status)
            @if ($status->title !== 'Waiting')
                <option value="{{ $status->id }}" {{ $status->id == $selectedStatus ? 'selected' : '' }} data-color="{{ $status->color }}">{{ $status->title }}</option>
            @endif
         @endforeach
       </select>
        </td>
          @php
            $lastAddedNote = collect($list->crm_send_lead_to_lender)->where('lead_id', $lead_id)->sortByDesc('created_at')->first();
           @endphp
         <td style="width:150px"> {{ $lastAddedNote->notes }}
         </td>
        <td>
         <div class="row">
           <div class="col-md-12">
                    <textarea type="text" name="notes" class="form-control"  placeholder="Add Notes" id="addLenderNotes_{{$list->id}}" required disabled></textarea>
                     <button class="EditLenderNotes btn btn-primary btn-sm" data-lender-id="{{ $list->id }}" id="editLenderNotesBtn_{{$list->id}}"style="display:none;">Edit</button>
                     <button class="SaveEditLenderNotes btn btn-primary btn-sm" data-lender-id="{{ $list->id }}" id="SaveEditLenderNotes_{{$list->id}}" style="display: none;margin-top:10px">Save for Edit</button>
                     <button class="addLenderNotes btn btn-primary btn-sm" data-lender-id="{{ $list->id }}" id="addLenderNotesBtn_{{$list->id}}" style="margin-top:10px">Add Note</button>
                     <button class="submitLenderNotes btn btn-primary btn-sm btn" data-lender-id="{{ $list->id }}" id="SubmitLenderNotes_{{$list->id}}"style="display:none;margin-top:10px"  name="yt1" type="button">Save</button>
                    <a id="lenderNotes" data-lender-id="{{ $list->id }}" data-lender-name="{{ $list->lender_name }}"class="btn btn-primary btn-sm viewButton" style="margin-top:10px">View</a>
            </div>
   </td>
    </tr>
@endforeach
    
</table>
@endif
</div>
 </div>
</div>

      

   

<div class="col-xl-2 col-lg-6 col-12 ">

    <div class="box bt-3 border-primary">
                    <!--  <div class="box-header with-border bg-primary">
                     <h4 class="box-title">Lead Summary</h4> -->
                      <!-- <ul class="box-controls pull-right " style="position: unset;">
                        <li><a class="box-btn-slide" href="#" style="color: white;font-weight: bold;"></a></li> 
                      </ul>
                    </div>-->
                    <div class="box-body no-padding mailbox-nav" style="padding: 5px !important;">
                      <div class="col-md-12" >


                        <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror"style="margin:5px;">
                  <label class="form-label">Created By </label> 
                  <div class="input-group">
                                               
                                                    <!-- @if(!empty($users))
                                                        @foreach($users as $list)
                                                        @if($list->id == $lead['created_by'])
                                                            <option
                                                                value="{{$list->id}}">{{ucwords($list->first_name)}} {{ucwords($list->last_name)}}</option>
                                                    @endif
                                                                
                                                        @endforeach
                                                    @endif -->
                        <select class="form-control" disabled="disabled" style="width: 100%;">
                        @if(!empty($users))
                                                        @foreach($users as $list)
                                                        @if($list->id == $lead['created_by'])
                                                            <option
                                                                value="{{$list->id}}">{{ucwords($list->first_name)}} {{ucwords($list->last_name)}}</option>
                                                    @endif
                                                                
                                                        @endforeach
                                                    @endif
                        </select>
                  </div>
                </div>
              </div>

                        
                <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror"style="margin:5px;">
                  <label class="form-label">Lead Status * </label> 
                  <div class="input-group">
                                                <select class="form-select" 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"style="margin:5px;">
                  <label class="form-label">Assigned To </label> 
                  <div class="input-group">
                  <select class="form-select" 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"style="margin:5px;">
                  <label class="form-label">Opener </label> 
                  <div class="input-group">
                  @php
                        // Convert opener_id to an array if it's not already one
                        $openerIds = is_array($lead['opener_id']) ? $lead->opener_id : json_decode($lead['opener_id'], true);
                        //dd($openerIds);
                    @endphp
                  <select class="select2 form-control" multiple="multiple" name="opener[]" 
                   autocomplete="off" data-placeholder="Select opener" id="opener">
                   @if(!empty($users))
    @foreach($sortedUsers as $list)
        @if($list->role == 2)
            <option value="{{ $list->id }}"
                @if(isset($lead['opener_id']))
             
                    @if(is_array($openerIds) && in_array($list->id, $openerIds))
                        selected
                    @endif
                @endif>
                {{ ucwords($list->first_name) }} {{ ucwords($list->last_name) }}
            </option>
        @endif
    @endforeach
@endif

    
</select>




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

              <!-- <div class="col-md-12">
    <div class="form-group @error('last_name') has-error @enderror" style="margin:5px;">
        <label class="form-label">Closer</label>
        <div class="input-group">
        @php
// Decode $lead->closer_id if it exists and ensure it's always an array
$closerIds = isset($lead['closer_id']) ? (is_array($lead['closer_id']) ? $lead['closer_id'] : json_decode($lead['closer_id'], true)) : [];

// 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 integers
$leadGroupIds = array_map('intval', $leadGroupIds);

// Get all extensions that match any of the group IDs in $lead->group_id
$matchedExtensions = collect($map)->whereIn('group_id', $leadGroupIds)->pluck('extension');
@endphp

<select class="select2 form-control" multiple="multiple" name="closer[]" autocomplete="off" data-placeholder="Select Closer" id="closer">
    @if(!empty($users) && $matchedExtensions->isNotEmpty())
        @foreach($users as $user)
            @php
                // Check if user's extension matches any in the matched extensions list
                $userExtension = $user->extension ?? null;
            @endphp

            @if($matchedExtensions->contains($userExtension))
                <option value="{{ $user->id }}"
                    @if(in_array($user->id, $closerIds))
                        selected
                    @endif
                >
                    {{ ucwords($user->first_name) }} {{ ucwords($user->last_name) }} ({{ $userExtension }})
                </option>
            @endif
        @endforeach
    @endif
</select>






        </div>
    </div>
</div> -->
              <div class="col-md-12">
                <div class="form-group @error('last_name') has-error @enderror"style="margin:5px;">
                  <label class="form-label">Select Lead Type </label> 
                  <div class="input-group">
                  <select class="form-select" 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  style="background-color:red;"@if($lead['lead_type'] == 'hot') selected="selected" @endif value="hot">Hot</option>
                                                    <option style="background-color:yellow;"@if($lead['lead_type'] == 'warm') selected="selected" @endif value="warm">Warm</option>
                                                    <option style="background-color:blue;"@if($lead['lead_type'] == 'cold') selected="selected" @endif value="cold">Cold</option>

                                                </select>
                  </div>
                </div>
              </div>
              </div>
              <div class="col-md-12">
                <div class="form-group @error('lead_source_id') has-error @enderror">
                  <label class="form-label"> Lead Source</label> 
                  <div class="input-group mb-3">
                                                <select class="form-select"  name="lead_source_id" id="lead_source_id"disabled>
                                                    <option value="">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 class="clearfix">
                                <a href="/leads/{{$lead_id}}/edit" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-primary btn-sm mb-5"><i class="fa fa-edit"></i> Edit Lead Details</a>
                                <a data-email="{{$lead['email']}}" data-leadid="{{$lead['id']}}" style="width:95%;text-align:left;margin:5px;height:vertical-align:middle;" class="waves-effect waves-light btn btn-success btn-sm mb-5 btn_send_email"><i class="fa fa-envelope"></i> Send Email</a>

                                <a  onclick="ShowSmsPopUpLeadSms('{{$lead['phone_number']}}','{{$lead['id']}}')" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-primary btn-sm mb-5"><i class="fa fa-edit"></i> Send SMS</a>

                                <a data-email="{{$lead['email']}}" data-leadid="{{$lead['id']}}" style="width: 95%;text-align:left;margin:5px;height:vertical-align:middle;" <?php if($status_value == '1') { ?> data-bs-toggle="modal" data-bs-target="#myModal" <?php }?> class="waves-effect waves-light btn btn-info btn-sm mb-5 <?php if($status_value == '0') { ?> btn_send_lenders <?php }?>"><i class="fa fa-envelope"></i> Send To Lender</a>

                                <a data-email="{{$lead['email']}}" data-leadid="{{$lead['id']}}" style="width: 95%;text-align:left;margin:5px;height:vertical-align:middle;" class="waves-effect waves-light btn btn-info btn-sm mb-5 btn_send_general"><i class="fa fa-envelope"></i> Share Lead via Email</a>

                                <a href="/document/{{$lead_id}}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Documents</a>

                                 <a target="_blank" href="{{$company_domain}}merchant/customer/app/index/{{Session::get('parentId')}}/{{$lead_id}}/{{$lead['unique_token']}}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Merchant Link</a>
                               
                                <a target="_blank" href="{{ url('leads/fcs-data/' . $lead_id) }}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> FCS Link</a>
                                <a target="_blank" href="{{ url('leads/reminder/' . $lead_id) }}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Set Reminder</a>


                                <a target="_blank" href="{{ url('/signed-application-pdf-crm/1/1/' . $lead_id) }}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Generate PDF</a>

                               

                              {{--   <a target="_blank" href="/affiliate/customer/user/app/index/{{Session::get('parentId')}}/{{Session::get('extension')}}/{{$lead['unique_token']}}" type="button" style="width: 95%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Affiliate Link</a>


                                <a target="_blank" href="/signed-application-crm/1/1/{{$lead_id}}" type="button" style="width: 100%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Signed App View</a>

                                  <a target="_blank" href="/signed-application-pdf-crm/1/1/{{$lead_id}}" type="button" style="width: 100%;text-align:left;margin:5px;vertical-align:middle;" class="waves-effect waves-light btn btn-secondary btn-sm mb-5"><i class="fa fa-plus"></i> Signed App PDF</a>
                                  --}}


                                <!-- <a style="cursor: pointer;font-size:13px;"  data-email="{{$lead['email']}}" data-leadid="{{$lead['id']}}"  class="btn btn-primary btn-block btn-sm btn_send_email1 "><i class="fa fa-envelope "></i> Send Email</a> -->

                                <!-- <button type="button" style="width: 100%;" class="waves-effect waves-light btn btn-danger btn-sm mb-5"><i class="fa fa-plus"></i> Generate Invoice</button> -->

                                <!-- <a style="cursor: pointer;font-size:13px;"  data-email="{{$lead['email']}}" data-leadid="{{$lead['id']}}"  class="btn btn-primary btn-block btn-sm btn_send_lenders "><i class="fa fa-envelope "></i> Submit Lenders</a> -->
                            </div>

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

                   <!-- <div class="box">
                    <div class="box-header with-border bg-primary">
                      <h4 class="box-title">CRM Utilities</h4>
                      <ul class="box-controls pull-right " style="position: unset;">
                        <li><a class="box-btn-slide" href="#" style="color: white;font-weight: bold;"></a></li> 
                      </ul>
                    </div>
                    <div class="box-body no-padding mailbox-nav" style="padding: 5px !important;">
                     <div class="col-md-12" style="text-align: center;">


                                <button type="button" class=" btn btn-primary-light btn-flat mb-5"><i class="fa fa-edit"></i> Send Lenders</button>
                                
                            </div>

                      <div class="col-md-12" style="text-align: center;">

                                <button type="button" class=" btn btn-danger-light btn-flat mb-5"><i class="fa fa-edit"></i> Send Email</button>
                            </div>

                            
                      <div class="col-md-12" style="text-align: center;">


                                <button type="button" class=" btn btn-primary-light btn-flat mb-5"><i class="fa fa-edit"></i> Generate Invoice</button>
                                
                            </div>
                    </div>
                  </div> -->
                    

                   
                <div class="modal fade" id="viewLenderNotes" role="dialog">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h4 class="modal-title" id="myModalLabel">View notes for lender <span id="lenderName"></span></h4>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <form class="form-horizontal">
                                    <div class="row">   
                                    <div class="box">
                                        <div class="box-body">
         
                                            <!-- <div class="row">
                                            <div class="col-md-10 form-group">
                                                <label class="form-label">Select Lender Status</label>
                                                <select class="form-select" id="lenderStatusSelect" name="lender_status_id"onchange="submitLenderStatus1({{$lead_id}}, this.value)">
                                                    <option value="">Select Status</option>
                                                    @foreach($lender_status as $status)
                                                    @if($status->status == 1)
                                                    <option value="{{ $status->id }}">
                                                        {{ $status->title }}
                                                        </option>
                                                        @endif
                                                        @endforeach

                                                </select>
                                            </div>
                                                <div class="col-md-10 form-group "style="display:none;"id="editNoteDiv"> 
                                                <label class="form-label">Edit Notes</label>
                                                    <textarea type="text" name="notes" class="form-control" style="width:100%;" placeholder="Write Notes"id="editLenderNotes"required ></textarea>
                                                </div>
                                                <div class="col-md-2 form-group"style="display:none;"id="SaveEditLenderNotes">  
                                                    <button class="SaveEditLenderNotes btn btn-primary btn-sm btn"  style="margin:38px;"  name="yt1" type="button"id="SaveEditLenderNotes">Save</button>   
                                                    </div>
                                                </div>
                                            </div> -->
                                            <div >
            <ul style="list-style: none;padding: 10px;">
            <input type="hidden" value="" id="lenderNotes_id">

@if(!empty($lender_notes))
    @foreach($lender_notes as $message)
    @if(!is_null($message->notes) && $message->notes !== '')
        <li class="lender-note" data-lender-id="{{ $message->lender_id }}"data-notes="{{$message->notes}}">
            <div>
                <span class="notes-align">
                    
                    <!-- @if($message->lender_id != '0') -->
                       
                            <!-- @if(!empty($lenders))
                                @foreach($lenders as $list)
                                    @if($list->id == $message->lender_id)
                                    <?php echo "@"; ?>  <strong> {{$name}}</strong> added note for lender <strong> {{ strtolower($list->lender_name) }}</strong>
                                    @endif
                                @endforeach
                            @endif
                      
                    @endif -->
                     @if($message->lender_id != '0')
                    @if(!empty($lenders))
    @foreach($lenders as $lender)
        @if($lender->id == $message->lender_id)
            @php
                $userName = '';
                foreach ($users as $user) {
                    if ($user->id == $message->user_id) {
                    $userName = $user->first_name . ' ' . $user->last_name;                        
                    break;
                    }
                }
            @endphp
            <?php echo "@"; ?><strong>{{ strtolower($userName) }}</strong> added note for lender <strong>{{ strtolower($lender->lender_name) }}</strong>
        @endif
    @endforeach
@endif
@endif

                    <strong>   -{!! $message->notes !!} </strong>
                    @if(!empty($lender_status))
                            @foreach($lender_status as $status)
                                @if($status->id == $message->lender_status_id)
                                    <strong> - {!! $status->title !!} </strong>
                                @endif
                            @endforeach
                        @endif
               
                </span>
                <span class="pull-right date-update" style="font-size:10px;">
                    <!-- @php
                        $formattedDate = $message->created_at;
                        $old_date_timestamp = strtotime($message->created_at);
                        $time = date('h:i:s A', $old_date_timestamp);
                    @endphp
                    {{ $formattedDate }} {{ $time }} -->
                    {{\Carbon\Carbon::parse($message->created_at)->setTimezone($timezone)->format('m/d/Y H:i A')}}
                </span>
            </div>
        </li>
        @endif
    @endforeach
@endif

                
                </ul>    <div class="text-center"></div>    
</div>
                                        </div>
                                    </div>
                                    </div>
                                </form>
                             
                            </div>
                            <div class="modal-footer text-end">
                            <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                            <!-- <button class="editLenderNotes btn btn-primary  float-end" type="button">Edit</button>                   -->

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

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


<section class="waiting-section" style="display: none">
        <div class="waiting-box">
            <div class="payment-processing">
                <img src="{{asset ('assets/images/loader-30px.gif')}}"/>
                <p>Please wait while Copying...</p>
            </div>
        </div>
</section>


    @include("leads.send-email-popup") 
    @include("leads.email-lenders-popup")
    @include("leads.email-general-popup")
    @include("leads.send-message-view")




@push('scripts')
                <script>
                    var base_url = "<?php echo URL::to('/'); ?>";
                </script>
                <script type="text/javascript" src="{{ URL::asset ('asset/js/send_sms_component_crm_lead.js') }}"></script>
            @endpush
 <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>

 <script>
     
      function ShowSmsPopUpLeadSms(phone,lead_id) {

        //alert(phone);

            //$('#preview_sms_id').val("");
            //$("#sms_template_list").prop('selectedIndex','');
            //let cont_number_sms = $(this).attr('data-contact');
            $('#send_phone_crm').val(phone);
            $('#lead_id_crm').val(lead_id);


            //var popup = $("#popup_value").val();

           // $("#send_phone").val(popup);

            $('#myModal_open').modal('show');
        }
 </script>


<script>

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


    $('.show_confirm').click(function(event)
    {
        var form =  $(this).closest("form");
        var name = $(this).data("name");
        event.preventDefault();

        swal(
        {
            title: `Are you sure you want to delete this record?`,
            //text: "If you delete this, it will be gone forever.",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willDelete)=>
        {
            if (willDelete)
            {
                form.submit();
                $('#loading').show();
            }
        }
        );
    });

    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
        {
            $("#lead_status").val(sel);
            $("#lead_type").val(type);

        }*/
    }
    $(document).on("click", ".submitNotes", function ()
    {
        var flag = 1;
        var notes = $("#notes").val();
        var el = this;

        swal("Success!", "Notes Added Successfully", "success")
        setTimeout(function()
        {
            window.location.reload(1);
        }, 1000);

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: '/notification/add',
            data:
            {
                message: notes,
                type: 1,
                lead_id: {{$lead_id}}
            },

            type: 'get',
            dataType:"json",
            success: function (response)
            {
                //alert(response);
                if (response =='1')
                {
                    swal("Success!", "Notes Added Successfully", "success")
                    setTimeout(function()
                    {
                        window.location.reload(1);
                    }, 2000);
                }
                else
                {
                //$('#loading').hide();
                swal("Warning!", "Something Went Wrong", "warning")
            }
        }
    });
    });
   
    function submitLenderStatus(lender_id, lead_id, lender_status) {
    const selectElement = $(`#lender_status_${lender_id}_${lead_id}`);
    const originalStatus = selectElement.data('original-value');
    const rowElement = $(`#lender_note_${lender_id}_${lead_id}`);

    swal({
        title: `Are you sure you want to change the Lender's status?`,
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willChange) => {
        if (willChange) {
            $("#loading").show();
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: "/submitLenderStatus",
                method: 'post',
                data: {
                    lender_id: lender_id,
                    lead_id: lead_id,
                    lender_status: lender_status
                },
                success: function(result) {
                    $("#loading").hide();
                    swal("Success!", "Lender's Status Changed Successfully", "success")
                        .then(() => {
                            // Apply the correct color to the row
                            const selectedOption = selectElement.find('option:selected');
                            const statusColor = selectedOption.data('color'); // Assuming you have a data-color attribute for each option

                            rowElement.css('background-color', statusColor);
                            window.location.reload();
                        });
                },
                error: function() {
                    $("#loading").hide();
                    swal("Error!", "There was an error changing the Lender's status.", "error");
                    // Revert to the original status if there is an error
                    selectElement.val(originalStatus);
                }
            });
        } else {
            // Revert to the original status if the action is canceled
            selectElement.val(originalStatus);
        }
    }).catch((error) => {
        // Do nothing if an error occurs
    });
}

// Initial setup to apply the correct color to each row based on the selected status
$(document).ready(function() {
    $('.lender-status-select').each(function() {
        const selectElement = $(this);
        const lender_status = selectElement.val();
        const lender_id = selectElement.attr('id').split('_')[2];
        const lead_id = selectElement.attr('id').split('_')[3];
        const rowElement = $(`#lender_note_${lender_id}_${lead_id}`);

        // Retrieve the color from localStorage
        const statusColor = localStorage.getItem(`statusColor_${lender_id}_${lead_id}`);

        if (statusColor) {
            rowElement.css('background-color', statusColor);
            // Remove the color from localStorage after applying it
            localStorage.removeItem(`statusColor_${lender_id}_${lead_id}`);
        } else {
            const selectedOption = selectElement.find('option:selected');
            const initialStatusColor = selectedOption.data('color'); // Assuming you have a data-color attribute for each option

            rowElement.css('background-color', initialStatusColor);
        }
    });
});




//     function submitLenderStatus(lender_id, lead_id, lender_status) {
//     const selectElement = $(`#lender_status_${lender_id}_${lead_id}`);
//     const originalStatus = selectElement.data('original-value');

//     swal({
//         title: `Are you sure you want to change the Lender's status?`,
//         icon: "warning",
//         buttons: true,
//         dangerMode: true,
//     }).then((willChange) => {
//         if (willChange) {
//             $("#loading").show();
//             $.ajaxSetup({
//                 headers: {
//                     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
//                 }
//             });

//             $.ajax({
//                 url: "{{ url('/submitLenderStatus') }}",
//                 method: 'post',
//                 data: {
//                     lender_id: lender_id,
//                     lead_id: lead_id,
//                     lender_status: lender_status
//                 },
//                 success: function(result) {
//                     $("#loading").hide();
//                     swal("Success!", "Lender's Status Changed Successfully", "success")
//                         .then(() => {
//                             window.location.reload();
//                         });
//                 },
//                 error: function() {
//                     $("#loading").hide();
//                     swal("Error!", "There was an error changing the Lender's status.", "error");
//                     // Revert to the original status if there is an error
//                     selectElement.val(originalStatus);
//                 }
//             });
//         } else {
//             // Revert to the original status if the action is canceled
//             selectElement.val(originalStatus);
//         }
//     }).catch((error) => {
//         // Do nothing if an error occurs
//     });
// }

</script>
<script>
     $(document).on("click", "#lenderNotes", function ()
    {
        $("#viewLenderNotes").modal("show");
        var lenderId = $(this).data('lender-id');
        $("#lenderNotes_id").val(lenderId); 
        var lenderName = $(this).data('lender-name');
        $('#lenderName').text(lenderName);
//alert(lenderName);
    });
    </script>
    <!-- lender notes -->
    <script>
         $('form').on('submit', function(e) {
        e.preventDefault(); // Prevent the default form submission
    });

    // Event listener for Edit button to enable textarea and show Save button
    $('.addLenderNotes').on('click', function(e) {
        e.preventDefault(); // Prevent the default form submission

        var lenderId = $(this).data('lender-id');
        var notesTextarea = $("#addLenderNotes_" + lenderId);
        var addButton = $("#addLenderNotesBtn_" + lenderId);
        var saveButton = $("#SubmitLenderNotes_" + lenderId);

        notesTextarea.prop('disabled', false);
        addButton.hide();
        saveButton.show();
    });
            $(document).on("click", ".submitLenderNotes", function (e)
    {
        e.preventDefault(); // Prevent the default form submission
        var flag = 1;
        var lenderId = $(this).data('lender-id');
        //alert(lenderId);
        var notesTextarea = $("#addLenderNotes_" + lenderId); 
        //alert(notesTextarea); // Check the textarea ID
    if (notesTextarea.length === 0) {
        alert("Textarea not found for lender ID: " + lenderId);
        return;
    }
    var notes = notesTextarea.val(); // Get the value of the textarea
    var lenderStatus = $("#lender_status").val(); 
     // Get the value of the textarea

    //alert("Notes: " + notes);
    if (notes === '') {
        swal("Warning!", "Notes cannot be empty", "warning");
        return; // Exit the function if notes are empty
    }

        //alert(lender);
        var el = this;

 

        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: '/lender/notes/add',
            data:
            {
                message: notes,
                lead_id: {{$lead_id}},
                lender_id:lenderId,
                lender_status:lenderStatus,
            },

            type: 'get',
            dataType:"json",
            success: function (response) {
            $("#loading").show(); // Show loading indicator

            if (response.success == true) { // Check for true response
                swal("Success!", "Lender's Note Added Successfully", "success");
                // Close the modal after successful response
                $('#viewLenderNotes').modal('hide');
                setTimeout(function () {
                    window.location.reload(1);
                }, 2000);
            } else {
                $("#loading").hide(); // Hide loading indicator
                swal("Warning!", "Something Went Wrong", "warning");
            }
        },
        error: function (xhr, status, error) {
            $("#loading").hide(); // Hide loading indicator
            swal("Error!", "An error occurred while processing your request", "error");
            console.log(xhr.responseText); // Log detailed error message
        }
    });
    });
        </script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    const viewButtons = document.querySelectorAll('.viewButton');
    
    viewButtons.forEach(button => {
        button.addEventListener('click', function () {
            const lenderNotesId = this.getAttribute('data-lender-id');
            document.getElementById('lenderNotes_id').value = lenderNotesId;

            const lenderNotes = document.querySelectorAll('.lender-note');

            lenderNotes.forEach(note => {
                const lenderId = note.getAttribute('data-lender-id');
                if (lenderId !== lenderNotesId) {
                    note.style.display = 'none';
                } else {
                    note.style.display = '';
                }
            });
        });
    });
});

</script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const viewButtons = document.querySelectorAll('.viewButton');
        const modalSelect = document.getElementById('lenderStatusSelect');

        viewButtons.forEach(button => {
            button.addEventListener('click', function () {
                const selectedStatus = this.getAttribute('data-selected-status');

                // Set the selected status in the modal dropdown
                modalSelect.value = selectedStatus;
            });
        });
    });
</script>
    <script>
    $(document).ready(function(){
    // Event listener for Edit button
    // Event listener for Edit button
    $('.editLenderNotes').on('click', function() {
        // Get the lender_id from the hidden input
        var lenderId = $('#lenderNotes_id').val();

        // Find the note related to the lender_id
        var lenderNote = $('.lender-note').filter(function() {
            return $(this).data('lender-id') == lenderId;
        }).first(); // Get the first note
        if (lenderNote.length > 0) {
            var notes = lenderNote.data('notes');
            $('#editLenderNotes').val(notes);
            $('#editNoteDiv').toggle();
            $('#SaveEditLenderNotes').toggle();
        }
    });
    $('form').on('submit', function(e) {
        e.preventDefault(); // Prevent the default form submission
    });

    // Event listener for Edit button to enable textarea and show Save button
    $('.EditLenderNotes').on('click', function(e) {
        e.preventDefault(); // Prevent the default form submission

        var lenderId = $(this).data('lender-id');
        var notesTextarea = $("#editLenderNotes_" + lenderId);
        var editButton = $("#editLenderNotesBtn_" + lenderId);
        var saveButton = $("#SaveEditLenderNotes_" + lenderId);

        notesTextarea.prop('disabled', false);
        editButton.hide();
        saveButton.show();
    });
      // Event listener for Save button
    $('.SaveEditLenderNotes').on('click', function(e) {
        e.preventDefault(); // Prevent the default form submission
    
        var lenderId = $(this).data('lender-id');
        //alert(lenderId);
        var notesTextarea = $("#editLenderNotes_" + lenderId); 
        //alert(notesTextarea); // Check the textarea ID
    if (notesTextarea.length === 0) {
        alert("Textarea not found for lender ID: " + lenderId);
        return;
    }
    var notes = notesTextarea.val(); // Get the value of the textarea
    //alert("Notes: " + notes);
    if (notes === '') {
        swal("Warning!", "Notes cannot be empty", "warning");
        return; // Exit the function if notes are empty
    }

        //alert(lender);
        var el = this;
        // Perform AJAX request to save the edited notes
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: '/lender/edit-notes', // Your endpoint to save notes
            type: 'POST',
            data: {
                lead_id:{{$lead_id}},
                lender_id: lenderId,
                notes: notes,
            },
            success: function(response) {
                // Handle successful save
                swal("Success!", "Lender's Note updated Successfully", "success");
                $("#loading").show(); // Show loading indicator

                window.location.reload();
                // // Optionally update the note in the list
                // var lenderNote = $('.lender-note').filter(function() {
                //     return $(this).data('lender-id') == lenderId;
                // }).first();
                // lenderNote.data('notes', editedNotes);
                // lenderNote.find('.notes-align').html('-' + editedNotes);
            },
            error: function(xhr) {
                $("#loading").hide(); // Show loading indicator

                // Handle save error
                swal("Warning!", "Something Went Wrong", "warning");

            }
        });
    });
    });

</script>
<!-- <script>
function submitLenderStatus1(lead_id, lender_status) {
    const lender_id = $('#lenderNotes_id').val();

    swal({
        title: "Are you sure you want to change the Lender's status?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willChange) => {
        if (willChange) {
            $("#loading").show();

            // Set up CSRF token for AJAX request
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            // Send AJAX request to update lender status
            $.ajax({
                url: "{{ url('/submitLenderStatus') }}",
                method: 'post',
                data: {
                    lender_id: lender_id,
                    lead_id: lead_id,
                    lender_status: lender_status
                },
                success: function(result) {
                    $("#loading").hide();

                    swal("Success!", "Lender's Status Changed Successfully", "success")
                    
                        .then(() => {
                            window.location.reload(); // Reload the page after successful update
                        });
                },
                error: function() {
                    $("#loading").hide();
                    swal("Error!", "There was an error changing the Lender's status.", "error");
                    // You can add code here to handle the error, such as reverting the status change
                }
            });
        }
    }).catch((error) => {
        // Do nothing if an error occurs
    });
}
</script> -->
<!--  <script src="{{asset('assets/plugins/select2/js/select2.full.min.js')}}"></script> -->
<script>
    $(document).on('click', '#copy-lead', function(e) {
    e.preventDefault();
    $("section.waiting-section").show();

    // Get the lead ID (You can either store it in a data attribute or pass it directly)
    var leadId = {{ $lead_id }};
    
    $.ajax({
        url: '/leads/copy/' + leadId,  // Your URL for copying the lead
        type: 'GET',  // Assuming the server expects a GET request
        success: function(response) {
            // Handle the successful response here (e.g., show a success message)
            $("section.waiting-section").hide();

            toastr.success('Lead copied successfully!');
            // Optionally, you can refresh part of the page or update UI elements
        },
        error: function(xhr, status, error) {
            // Handle any errors that occur during the AJAX request
            $("section.waiting-section").hide();
            toastr.error('Error copying lead: ' + error);
        }
    });
});

  
    </script>
     <script>
// Attach event listener to select2 for the 'close' event
let closerSelectTimeout;
let openerSelectTimeout;

$(document).ready(function() {
    // Initialize select2 for both select elements
    $('#closer').select2();
    $('#opener').select2();

    // Listen for changes in the closer select2 input
    $('#closer').on('change', function() {
        clearTimeout(closerSelectTimeout); // Clear any previous timeouts

        // Set a delay before triggering the function to ensure the user has finished selecting
        closerSelectTimeout = setTimeout(function() {
            addCloser();  // Call addCloser after the delay
        }, 2000);  // Adjust the delay (in milliseconds) if needed
    });

    // Listen for changes in the opener select2 input
    $('#opener').on('change', function() {
        clearTimeout(openerSelectTimeout); // Clear any previous timeouts

        // Set a delay before triggering the function to ensure the user has finished selecting
        openerSelectTimeout = setTimeout(function() {
            addOpener();  // Call addOpener after the delay
        }, 2000);  // Adjust the delay (in milliseconds) if needed
    });
});

function addCloser() {
    // Get selected values from the closer select field
    var closer = $('#closer').val();  // This will be an array of selected values



    // Ask for confirmation after all selections are made
    swal({
        title: `Are you sure you want to add the closer(s) for this record?`,
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $("#loading").show();
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            // Get the lead ID from PHP
            var leadId = {{ $lead_id }}; 

            jQuery.ajax({
                url: "{{ url('leads/add/closer') }}",
                method: 'POST',
                data: {
                    lead_id: leadId,
                    closer: closer,  // Sending selected closer values (as an array)
                },
                success: function(result) {
                    $("#loading").hide();
                    swal("Success!", "Added Successfully", "success");
                    window.location.reload(1);
                }
            });
        }
    });
}

function addOpener() {
    // Get selected values from the opener select field
    var opener = $('#opener').val();  // This will be an array of selected values


    // Ask for confirmation after all selections are made
    swal({
        title: `Are you sure you want to add the opener(s) for this record?`,
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((willDelete) => {
        if (willDelete) {
            $("#loading").show();
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            // Get the lead ID from PHP
            var leadId = {{ $lead_id }}; 

            jQuery.ajax({
                url: "{{ url('leads/add/opener') }}",
                method: 'POST',
                data: {
                    lead_id: leadId,
                    opener: opener,  // Sending selected opener values (as an array)
                },
                success: function(result) {
                    $("#loading").hide();
                    swal("Success!", "Added Successfully", "success");
                    window.location.reload(1);
                }
            });
        }
    });
}




   
        </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>
        <!-- JavaScript -->
<!-- JavaScript -->


@endsection
