@extends('layouts.csd.app')

@section('content')

@php
$siteDtl = App\Http\pagginationHelper::get_site_info(strtolower($data->sitename));
echo($siteurl);
@endphp

<main id="main" class="main">
    <div class="pagetitle">
        <h1>MASSEGES</h1>
        <nav>
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{{route('csd.home')}}">Home</a></li>
                <li class="breadcrumb-item"><a href="{{$siteurl}}">Inbox</a></li>
                <li class="breadcrumb-item">Massege</li>
            </ol>
        </nav>
    </div><!-- End Page Title -->

    <section class="section">
        <div class="row">
            <!-- Left Column - Ticket Details -->
            <div class="col-lg-4">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title m-b-0"> 
                            {{--@if('https://ofadmin.rightflorist.org/csd/sitelabels/'.strtolower($data->sitename) == $siteurl)
                                <a href="{{url('/csd/sitelabels/')}}/{{strtolower($data->sitename)}}" class="text-decoration-none">
                                    <i class="bi bi-arrow-left-square-fill"></i>
                                </a>
                            @elseif('https://ofadmin.rightflorist.org/public/csd/inbox' == $siteurl)
                                <a href="{{url('/csd/inbox/')}}" class="text-decoration-none">
                                    <i class="bi bi-arrow-left-square-fill"></i>
                                </a>
                            @else
                                <a href="{{url('/csd/trash/')}}" class="text-decoration-none">
                                    <i class="bi bi-arrow-left-square-fill"></i>
                                </a>
                            @endif--}}
                            <a href="{{$siteurl}}" class="text-decoration-none">
                                <i class="bi bi-arrow-left-square-fill"></i>
                            </a>

                            <span class="ticketid ms-2">Ticket ID: {{$data->ticket_id}}</span>
                            <span class="float-end">
                                @if($data->is_block == 'N')
                                    <span class="badge bg-success" style="color:white;">OPEN</span>
                                @else
                                    <span class="badge bg-danger" style="color:white;">CLOSED</span>
                                @endif
                            </span>
                        </h4>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <tbody>
                                @if($data->spam == 1) 
                                    @if((Session::get('permissions.user_type') == 'C'))
                                    <tr class="table-danger">
                                        <td colspan="2"><strong>Delete this Conversation</strong> 
                                            <a class="btn btn-sm btn-danger float-end" href="{{ url('/csd/view/delete') }}/{{ strtolower($data->sitename) }}/{{ base64_encode($data->id) }}">
                                                Delete Forever
                                            </a>
                                        </td>
                                    </tr>
                                    @endif
                                @endif
                                
                                <tr>
                                    <td class="w-25"><strong>Website:</strong></td>
                                    <td class="text-primary">{{$data->sitename}} </td>
                                </tr>
                                <tr>
                                    <td class="w-25"><strong>Country:</strong></td>
                                    <td class="text-primary">{{$data->country_name}}</td>
                                </tr>
                                <tr>
                                    <td><strong>Contact Type:</strong></td>
                                    <td class="text-primary">{{ucwords($data->contact_type)}}</td>
                                </tr>
                                @if($data->query_related != '')
                                <tr>
                                    <td><strong>Related Query:</strong></td>
                                    <td class="text-primary">{{$data->query_related}}</td>
                                </tr>
                                @endif
                                @if($data->order_id != '')
                                <tr>
                                    <td><strong>Order ID:</strong></td>
                                    <td class="text-primary">{{$data->order_id}}</td>
                                </tr>
                                @endif
                                <tr>
                                    <td><strong>Name:</strong></td>
                                    <td class="text-primary">{{$data->name}}</td>
                                </tr>
                                <tr>
                                    <td><strong>Email:</strong></td>
                                    <td class="text-primary">{{$data->email}}</td>
                                </tr>
                                <tr>
                                    <td><strong>Mobile:</strong></td>
                                    <td class="text-primary">{{$data->mobile}}</td>
                                </tr>
                                <tr>
                                    <td><strong>Status Update</strong></td>
                                    <td>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" id="is_block_open" name="status" {{$data->is_block == 'N' ? 'checked' : ''}} value="N">
                                            <label class="form-check-label text-success" for="is_block_open">OPEN</label>
                                        </div>
                                        <div class="form-check form-check-inline">
                                            <input class="form-check-input" type="radio" id="is_block_close" name="status" {{$data->is_block == 'Y' ? 'checked' : ''}} value="Y">
                                            <label class="form-check-label text-danger" for="is_block_close">CLOSED</label>
                                        </div>
                                    </td>
                                </tr>
                                
                                @if($data->spam == 0)
                                <tr class="table-warning">
                                    <td colspan="2">
                                        <small class="fw-bold">Do you want to move this mail to Trash?</small> 
                                        <button class="btn btn-sm btn-danger float-end" id="btn_spam">Move to Trash</button>
                                    </td>
                                </tr>
                                @if((Session::get('permissions.user_type') == 'C'))
                                <tr class="table-danger">
                                    <td colspan="2">
                                        <small class="fw-bold">Permanently delete this mail?</small> 
                                        <a href="{{url('/csd/view/delete')}}/{{ strtolower($data->sitename) }}/{{ base64_encode($data->id) }}" class="btn btn-sm btn-danger float-end" id="btn_dlt">Delete</a>
                                    </td>
                                </tr>
                                @endif
                                @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Right Column - Conversation -->
            <div class="col-lg-8">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Subject: {{$data->subject}} </h4>
                        <hr>
                        
                        <div class="chat-box scrollable" style="height: 400px; overflow-y: auto;" id="chat-messages">
                            <ul class="list-unstyled">
                                @foreach($conversations as $index => $value)
                                    @if($data->id == $value->contact_id && $value->created_by == '')
                                        <!-- Customer Message -->
                                        <li class="d-flex mb-4">
                                            <div class="flex-shrink-0 me-3">
                                                <img src="{{ asset('admin/assets/images/users/1.jpg') }}" alt="{{$data->name}}" class="rounded-circle" width="50">
                                            </div>
                                            <div class="flex-grow-1">
                                                <h6 class="fw-bold mb-1">{{$data->name}}</h6>
                                                <div class="bg-light p-3 rounded">
                                                    @if($value->dfile != null)
                                                        @if (in_array(pathinfo($value->dfile, PATHINFO_EXTENSION), ['jpg', 'jpeg', 'png', 'gif', 'webp']))
                                                            <a href="{{ $siteDtl->site_link }}contact_attachment/{{$value->dfile}}" download="{{$data->name}}" class="d-block mb-2">
                                                                <img src="{{ $siteDtl->site_link }}contact_attachment/{{$value->dfile}}" class="img-thumbnail" style="max-width: 200px;">
                                                            </a>
                                                        @else 
                                                            <a href="{{ asset('contact_attachment/' . $value->dfile) }}" class="btn btn-sm btn-warning mb-2">
                                                                <i class="mdi mdi-download me-1"></i>Download File
                                                            </a>
                                                        @endif
                                                    @endif
                                                    {!!$value->message!!}
                                                </div>
                                                <small class="text-muted d-block mt-1 text-end">{{ date('jS M,y g:i a', strtotime($value->created_at)) }}</small>
                                            </div>
                                        </li>
                                    @elseif($data->id == $value->contact_id && $value->created_by != '')
                                        @php
                                            $adminName = App\Http\pagginationHelper::adminName($value->created_by);
                                        @endphp
                                        <!-- Admin Message -->
                                        <li class="d-flex mb-4 flex-row-reverse">
                                            <div class="flex-grow-1 text-end">
                                                <h6 class="fw-bold mb-1">{{$adminName}}</h6>
                                                <div class="bg-primary text-white p-3 rounded">
                                                    @if($value->dfile != null)
                                                        @php
                                                            $checkMineType = App\Http\pagginationHelper::getFileExtensionFromBase64($value->dfile);
                                                        @endphp

                                                        @if (in_array($checkMineType, ['jpg', 'jpeg', 'png', 'gif', 'webp']))
                                                            <a href="" download="{{ $data->name }}" ds-value="downloadBase64File('{{ $value->dfile }}', 'downloaded_image.png', 'image');" class="btn_download d-block mb-2">
                                                                <img src="{!! $value->dfile !!}" class="img-thumbnail" style="max-width: 200px;">
                                                            </a>
                                                        @elseif($checkMineType == 'pdf')
                                                            <a href="" ds-value="downloadBase64File('{{ $value->dfile }}', 'downloaded_image.pdf', 'pdf');" class="btn btn-sm btn-light btn_download mb-2">
                                                                <i class="mdi mdi-download me-1"></i>Uploaded File
                                                            </a>
                                                        @else
                                                            <a href="" ds-value="downloadBase64File('{{ $value->dfile }}', 'downloaded_image.xls', 'excel');" class="btn btn-sm btn-light btn_download mb-2">
                                                                <i class="mdi mdi-download me-1"></i>Uploaded File
                                                            </a>
                                                        @endif
                                                    @endif
                                                    {!!$value->message!!}
                                                </div>
                                                <small class="text-muted d-block mt-1">{{ date('jS M,y g:i a', strtotime($value->created_at)) }}</small>
                                            </div>
                                        </li>
                                    @endif
                                @endforeach
                            </ul>
                        </div>
                    </div>
                    
                    @if($data->spam == 0)
                    <div class="card-footer bg-light">
                        <form action="{{url('/csd/view/')}}/{{$data->sitename}}/{{base64_encode($data->id)}}" method="post" enctype="multipart/form-data">
                            @csrf
                            <div class="input-group">
                                <input type="file" name="img" id="img" class="form-control" style="max-width: 150px;">
                                <textarea name="adminmsg" id="adminmsg" placeholder="Type your message here..." class="form-control" rows="1" required></textarea>
                                <button type="submit" class="btn btn-primary">
                                    <i class="ri-send-plane-fill"></i> Send
                                </button>
                            </div>
                        </form>
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </section>
</main>

<style type="text/css">
    
    @import url("https://fonts.googleapis.com/css2?family=Abel&family=Quicksand:wght@400;500;600&display=swap");

    .container-fluid{font-family: 'Quicksand', sans-serif;}
    .card-body{padding: 1.25rem 0.7rem;}
    .card-title{display: flex; justify-content: space-between; align-items: center;}
    .table td {padding: 1rem 0.7rem;}
    .custom-control{display: inline-block!important; padding-right: 10px;}
    .text-info{word-break: break-all; font-weight: 500;}
    .chat-list .chat-item.odd .chat-time {text-align: right; margin-right: 15px;}
    .chat-list .chat-item.odd .chat-content {text-align: right; width: calc(98% - 0px);}
    .leftarrow{font-size: 30px; color: #435e7a;}
    .ticketid{margin-left: -22%;}
</style>

<script type="text/javascript">
    function scrollToBottom() {
        var chatContainer = document.getElementById('chat-messages');
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }
    window.onload = function() {
        scrollToBottom();
    };

    $(document).ready(function(){
        $('input:radio').change(function(){
        if (confirm("Are you sure?")) {
            var status = $("input[name='status']:checked").val()
            $.ajax({
                url:'{{route("csd.update_status")}}',
                type:'get',
                data:{
                    id:"{{$data->id}}",
                    sitename:"{{$data->sitename}}",
                    status:status,
                },
                success:function(response){
                    location.reload();
                },
                error:function(error){
                    console.log(error);
                },
            });
        }
        return false;
        });

        $('#btn_spam').click(function(){
        if (confirm("Do you really want to move this mail to Trash?")) {
            $.ajax({
                url:"{{route('csd.spam')}}",
                type:'get',
                data:{
                    id:"{{$data->id}}",
                    sitename:"{{$data->sitename}}",
                },
                success:function(response){
                    window.location.replace("https://ofadmin.rightflorist.org/public/csd/inbox");
                },
                error:function(error){
                    console.log(error);
                },
            });
        }
        return false;
        });

        $('#btn_dlt').click(function(event){
            event.preventDefault();
            var url = $(this).attr('href');
            if (confirm("Do you really want to Parmanent delete this mail?")) {
                window.location.href = url;
            }
            return false;

        });
    });
    $('.btn_download').on('click', function(event) {
        event.preventDefault(); 
        var dsValue = $(this).attr('ds-value');
        
        var functionCall = dsValue.match(/downloadBase64File\('(.*)', '(.*)', '(.*)'\)/);
        if (functionCall) {
            var base64String = functionCall[1];
            var filename = functionCall[2];
            var fileType = functionCall[3];
            downloadBase64File(base64String, filename, fileType);
        } else {
            console.error('Invalid ds-value format');
        }
    });

function downloadBase64File(base64String, filename, fileType) {
    try {
        
        var base64Data = base64String.split(',')[1];
        if (!base64Data) {
            console.error("Invalid base64 string");
            return;
        }

        var binaryData = atob(base64Data);
        var arrayBuffer = new ArrayBuffer(binaryData.length);
        var byteArray = new Uint8Array(arrayBuffer);
        for (var i = 0; i < binaryData.length; i++) {
            byteArray[i] = binaryData.charCodeAt(i);
        }

        var blob;
        switch (fileType) {
            case 'image':
                blob = new Blob([byteArray], { type: 'image/png' });
                break;
            case 'excel':
                blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                break;
            case 'pdf':
                blob = new Blob([byteArray], { type: 'application/pdf' });
                break;
            default:
                console.error('Unsupported file type');
                return;
        }

        var url = URL.createObjectURL(blob);

        var a = $('<a style="display: none;"></a>');
        a.attr('href', url);
        a.attr('download', filename);
        $('body').append(a);
        a[0].click();

        setTimeout(function() {
            URL.revokeObjectURL(url);
            a.remove();
        }, 0);
    } catch (error) {
        console.error('Error downloading file:', error);
    }
}
</script>

@endsection


<!-- <html>
<title>Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<body>

<div class="w3-container">
        <h2>Chat System</h2>
    <div class="w3-panel w3-card" style="width: 1000px;margin-left: auto;margin-right: auto;">
        Ticket Id: {{$data->ticket_id}}</br>
        Content Type: {{$data->contact_type}}</br>
        Content Realted : {{$data->query_related}}</br>
        Order Id: {{$data->order_id}}</br>
        Status: {{$data->is_block == 'Y'?"Not open":'open'}}</br>
        Sitename:{{$data->sitename}}</br>
        Name : {{$data->name}}</br>
        Email : {{$data->email}}</br>
        Mobile : {{$data->mobile}}</br>
       
        @foreach($conversations as $index => $value )
            @if($data->id == $value->contact_id && $value->created_by != $adminid)
                <div class="w3-panel w3-card-2" style="width: 672px;"><p>{!!$value->message!!}</p></div>
                @if($value->dfile != null)
                    <a href="{{url('/public/images')}}/{{$value->dfile}}" download="{{$data->name}}"><img src="{{url('/public/images')}}/{{$value->dfile}}" alt="not found" style="width: 290px; margin-left: 661px;"></a>                
                @endif
            @elseif($data->id == $value->contact_id && $value->created_by == $adminid)
                <div class="w3-panel w3-card-2" style="width: 672px; margin-left: 290px!important;"><p>{!!$value->message!!}</p></div>  
                @if($value->dfile != null)
                    <a href="{{url('/public/images')}}/{{$value->dfile}}" download="{{$data->name}}"><img src="{{url('/public/images')}}/{{$value->dfile}}" alt="not found" style="width: 290px; margin-left: 661px;"></a>
                @endif   
            @endif
        @endforeach

        <form action="{{url('/csd/view/')}}/{{strtolower($data->sitename)}}/{{base64_encode($data->id)}}" method="post" enctype="multipart/form-data">
            @csrf
            <div class="w3-panel w3-card-2">
                <table>
                    <tr>
                        <th></th>
                        <th></th>
                    </tr>
                    <tr>
                        <td><input type="file" name="img" id="img" class="form-control" ></td>
                        <td style="width: 565px;"><input type="text" name="send" id="send" class="form-control" required></td>
                    </tr>
                    <tr>
                        <td><b>Status</b></td>
                    </tr>
                    <tr>
                        <td>
                            <input type="radio" id="open" name="status" value="open" >
                              <label for="html">Open</label>
                            <input type="radio" id="close" name="status" value="close" style="margin-left:15px;">
                              <label for="close">Close</label>
                        </td>
                        <td>
                            
                        </td>
                    </tr>
                </table>
                <div style="text-align:center">
                    <button type="submit" class="btn btn-primary" style="margin-bottom:20px;">Send</button>
                    <button type="submit" class="btn btn-danger"  style="margin-bottom:20px;">Cancel</button>
                </div>
            </div>
        </form>
    </div>
</div>

</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>-->

<!-- <script>
    
</script> -->