@extends('layouts.csd.app')

@section('content')

@php
$siteDtl = App\Http\Helper::get_site_info(strtolower($data->sitename));
//echo Session::get('permissions.user_type');
@endphp
<div class="container-fluid">
    <div class="row">
        <!-- column -->
        <div class="col-lg-4">
            
            <div class="card">
                <div class="card-body">
                <h4 class="card-title m-b-0"> 

                    @if('https://admin.rightflorist.org/csd/bulk/sitelabels/'.strtolower($data->sitename) == $siteurl)
                    <a href="{{url('/csd/bulk/sitelabels')}}/{{strtolower($data->sitename)}}">
                        <i class="mdi mdi-arrow-left-box leftarrow"></i>
                    </a>
                    @elseif('https://admin.rightflorist.org/csd/bulk/bulk-inbox' == $siteurl)
                    <a href="{{url('/csd/bulk/bulk-inbox')}}">
                        <i class="mdi mdi-arrow-left-box leftarrow"></i>
                    </a>
                    @else
                    <a href="{{url('/csd/bulk/trash/')}}">
                        <i class="mdi mdi-arrow-left-box leftarrow"></i>
                    </a>
                    @endif

                    <span class="ticketid">Ticket ID: {{$data->ticket_id}} </span>
                    <span>
                        @if($data->is_block == 'N')
                            <button type="button" class="btn btn-success">OPEN</button>
                        @else
                            <button type="button" class="btn btn-danger">CLOSED</button>
                        @endif
                    </span>
                    </h4>
                </div>
                <table class="table">
                    
                    <tbody>
                        @if($data->spam == 1) 
                            @if((Session::get('permissions.user_type') == 'SU'))
                            <tr>
                                <td colspan="2"><b>Delete this Conversation </b><a class="btn btn-danger" href="{{ url('/csd/view/delete') }}/{{ strtolower($data->sitename) }}/{{ base64_encode($data->id) }}" style="margin-left:10px;">Delete Forever</a></td>
                            </tr>
                            @endif
                        @endif
                        <tr>
                            <td style="width:35%"><b>Website :</b></td>
                            <td style="width:65%" class="text-info">{{$data->sitename}}</td>
                        </tr>
                        <tr>
                            <td><b>Name :</b></td>
                            <td class="text-info">{{$data->name}}</td>
                        </tr>
                        <tr>
                            <td><b>Email :</b></td>
                            <td class="text-info">{{$data->email}}</td>
                        </tr>
                        <tr>
                            <td><b>Mobile :</b></td>
                            <td class="text-info">{{$data->mobile}}</td>
                        </tr>
                        <tr>
                            <td><b>Staus Update</b></td>
                            <td>
                                <!-- <div style="display:flex;">
                                    <input type="radio" id="is_block_open"  name="status" value="N">
                                    <label for="is_block_open">Open</label><br>
                                    <input type="radio" id="is_block_close" name="status" value="Y" style="margin-left:25px;">
                                    <label for="is_block_close">Close</label><br>
                                </div> -->
                                <div class="custom-control custom-radio">
                                <input type="radio" id="is_block_open" name="status" class="bulk_product_update bulk_hide custom-control-input" {{$data->is_block == 'N' ? 'checked' : ''}} value="N">
                                    <label class="custom-control-label" for="is_block_open">OPEN</label>
                                </div>

                                <div class="custom-control custom-radio">
                                    <input type="radio" id="is_block_close" name="status" class="bulk_product_update bulk_show custom-control-input" {{$data->is_block == 'Y' ? 'checked' : ''}} value="Y">
                                    <label class="custom-control-label" for="is_block_close">CLOSED</label>
                                </div>
                            </td>
                        @if($data->spam == 0)
                        <tr>
                            <td colspan="2" style="font-size:13px; font-weight:600">Do you want to move this mail to Trash ? <button class="btn btn-danger btn-sm" id="btn_spam">Move to Trash</button></td>
                        </tr>
                            @if((Session::get('permissions.user_type') == 'SU'))
                            <tr>
                                <td colspan="2" style="font-size:13px; font-weight:600">Do you want to parmanent delete this mail ? <a href="{{url('/csd/bulk/view/delete')}}/{{ strtolower($data->sitename) }}/{{ base64_encode($data->id) }}" class="btn btn-danger btn-sm" id="btn_dlt">Delete</a></td>
                            </tr>
                            @endif
                        @endif
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>
        <div class="col-lg-8">
            <div class="card">
                <div class="card-body">
                    <h4 class="card-title">Conversion Subject : </h4>
                    <hr>
                    <div class="chat-box scrollable" id="chat-messages" style="height:400px;">
                        <!--chat Row -->
                        <ul class="chat-list">
                            <!--chat Row -->

                            @foreach($conversations as $index => $value )
                                @if($data->id == $value->bulk_id && $value->created_by == '')
                                    
                                    <li class="chat-item">
                                        <div class="chat-img"><img src="{{ asset('admin/assets/images/users/1.jpg') }}" alt="{{$data->name}}"></div>
                                        <div class="chat-content">
                                            <h6 class="font-medium">{{$data->name}}</h6>
                                            <div class="box bg-light-info">
                                                @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}}"><img src="{{ $siteDtl->site_link }}contact_attachment/{{$value->dfile}}" style="width: 200px;"></a>
                                                    @else 
                                                        {{-- <a href="{{ asset('contact_attachment/' . $value->dfile) }}" class="btn btn-warning"><i class="mdi mdi-download" title="Download"></i>Download File</a> --}}
                                                        <a href="{{ $siteDtl->site_link }}contact_attachment/{{$value->dfile}}" class="btn btn-warning"><i class="mdi mdi-download" title="Download"></i>Download File</a>
                                                    @endif
                                                    <br>
                                                @endif
                                                {!!$value->message!!}
                                            </div>
                                        </div>
                                        <div class="chat-time">{{ date('jS M,y g:i a', strtotime($value->created_at)) }}</div>
                                    </li>

                                @elseif($data->id == $value->bulk_id && $value->created_by != '')

                                    @php
                                        $adminName = App\Http\Helper::adminName($value->created_by);

                                    @endphp
                                    
                                    <li class="odd chat-item">
                                        <div class="chat-content">
                                            <h6 class="font-medium">{{$adminName}}</h6>
                                            <div class="box bg-light-inverse">
                                                @if($value->dfile != null)
                                                   
                                                    @php
                                                        $checkMineType = App\Http\Helper::getFileExtensionFromBase64($value->dfile);
                                                       
                                                        //dd($checkMineType);
                                                    @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">
                                                            <img src="{!! $value->dfile !!}" style="width: 290px;">
                                                        </a>
                                                    @elseif($checkMineType == 'pdf')
                                                        <a href="" ds-value="downloadBase64File('{{ $value->dfile }}', 'downloaded_image.pdf', 'pdf');" class="btn btn-warning btn_download"><i class="mdi mdi-download" title="Download"></i>Uploaded File</a>
                                                    @else
                                                        <a href="" ds-value="downloadBase64File('{{ $value->dfile }}', 'downloaded_image.xls', 'excel');" class="btn btn-warning btn_download"><i class="mdi mdi-download" title="Download"></i>Uploaded File</a>

                                                    @endif
                                                    <br>
                                                @endif
                                                {!!$value->message!!}
                                            </div>
                                            <br>
                                        </div>
                                        <div class="chat-time">{{ date('jS M,y g:i a', strtotime($value->created_at)) }}</div>
                                    </li>

                                @endif
                            @endforeach

                        </ul>
                    </div>
                </div>
                @if($data->spam == 0)
                <div class="card-body border-top">
                    <form action="{{url('/csd/bulk/view/')}}/{{strtolower($data->sitename)}}/{{base64_encode($data->id)}}" method="post" enctype="multipart/form-data">
                    @csrf
                        <div class="row">
                            <div class="col-9">
                                <div class="input-field m-t-0 m-b-0">
                                    <input type="file" name="img" id="img" class="form-control" >
                                    <textarea name="adminmsg" id="adminmsg" placeholder="Type and enter" class="form-control border-0" required></textarea>
                                </div>
                            </div>
                            <div class="col-3">
                                <button type="submit" class="btn-circle btn-lg btn-cyan float-right text-white"><i class="fas fa-paper-plane"></i></button>
                            </div>
                        </div>
                    </form>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<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: -15%;}
</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_bulkstatus")}}',
                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.bulkspam')}}",
                type:'get',
                data:{
                    id:"{{$data->id}}",
                    sitename:"{{$data->sitename}}",
                },
                success:function(response){
                    window.location.replace("https://admin.rightflorist.org/csd/bulk/bulk-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);
    }
}


    // function downloadBase64File(base64String, filename, fileType) {
    //     try {
    //         var base64Data = base64String.split(',')[1]; // Remove the header
    //         var binaryData = atob(base64Data); // Decode base64 (binary)
    //         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;
    //         }

    //         // Create a temporary URL
    //         var url = URL.createObjectURL(blob);

    //         // Create a link element, set the download attribute and simulate click
    //         var a = $('<a style="display: none;"></a>');
    //         a.attr('href', url);
    //         a.attr('download', filename);
    //         $('body').append(a);
    //         a[0].click();
    //         // Clean up
    //         setTimeout(function() {
    //             URL.revokeObjectURL(url);
    //             a.remove();
    //         }, 0);
    //     } catch (error) {
    //         console.error('Error downloading file:', error);
    //     }
    // }
</script>

@endsection
