<?php
$condition = ' isActive =  "Y"  ';
$users = User::getUserModels();

function randomColor() {
    $result = array('rgb' => '', 'hex' => '');
    foreach (array('r', 'b', 'g') as $col) {
        $rand = mt_rand(0, 255);
        $result['rgb'][$col] = $rand;
        $dechex = dechex($rand);
        if (strlen($dechex) < 2) {
            $dechex = '0' . $dechex;
        }
        $result['hex'] .= $dechex;
    }
    return "#" . $result['hex'];
}

function random_color_part() {
    $dt = '';
    for ($o = 1; $o <= 3; $o++) {
        $dt .= str_pad(dechex(mt_rand(0, 127)), 2, '0', STR_PAD_LEFT);
    }
    return "#" . $dt;
}
?>
<script>
    const DISPLAY_ITEM_LIMIT = 5000;
    function reloadCalendar() {
        $.ajax({
            url: "index.php?r=workspace/space/getlist",
            type: 'POST',
            dataType: 'json',
            data: {
                "through_id": $("#through_id").val(),
                "group_id": $("#group_id").val(),
                "from_date": $("#from_date").val(),
                "to_date": $("#to_date").val(),
                "search_word": $("#search_word").val()
            },
            beforeSend: function (xhr) {
                $("#loader").show();
            },
            success: function (data, textStatus, jqXHR) {
            
                $(".card-body").html("");
                $(data).each((i, el) => {
                 
                    addItem(el);
                    console.log(el);
                });
                updateTotalAmount();
                $("#loader").hide();
            }
        });
    }
</script>
<section class="panel">
    <header class="panel-heading clearfix panel-theame">
        <div class="pull-left">
            <i class="fa fa-users"></i> Workspace
        </div>
       <!--  <div  ondrop="dropLead(event)"    ondragover="allowDrop(event)"  id ="lead_drop" class="pull-left" style="">Lead</div>
        <div  ondrop="dropQuotation(event)"    ondragover="allowDrop(event)"  id ="quotation_drop" class="pull-left" style="">Quotation</div> -->

        <div class="pull-right">
            <?php 
            $user_id = (int)Yii::app()->user->id;
            if ((Yii::app()->user->authorised_user != 1) && (Yii::app()->user->havePermissionOn['workspace_view_all'] != 1)) {
                echo CHtml::hiddenField("through_id", $user_id);
            }else{
                echo CHtml::dropDownList("through_id", $user_id, User::getUser(), ['empty' => "All", 'onchange' => "reloadCalendar()"]);
            }?>
            <?php echo CHtml::dropDownList("group_id", "", MasSalesGroup::getSalesGroups(), ['empty' => "All", 'onchange' => "reloadCalendar()"]);
            ?>
            <?php
            echo CHtml::textField("from_date", date("01/01/Y"), ['style' => "width:120px", "class" => "datepicker", 'onblur' => 'reloadCalendar()', 'placeholder' => 'From']);
            echo '&nbsp;';
            echo CHtml::textField("to_date", date("d/m/Y"), ['style' => "width:120px", "class" => "datepicker", 'onblur' => 'reloadCalendar()', 'placeholder' => 'To']);
            echo '&nbsp;';
            echo CHtml::textField("search_word", "", ['style' => "width:120px", 'onkeyup' => 'reloadCalendar()', 'placeholder' => 'Search']);
            ?>

            <button class="btn btn-sm btn-theme" onclick="loadPopupModal('workspace/space/create', 'Add New Workspace', 'lg')"><i class="fa fa-plus"></i> ADD</button>
        </div>
    </header>
    <div class="panel-body">
        <div class="panel-body" style="display: none;">

            <?php foreach ($users as $value) {
                ?>
                <div  draggable="true" ondragstart="dragUser(event)"   title="<?= $value->getFullname() ?>" style="display: none; background: <?= random_color_part() ?>" class="ws-avatar" id="wsavatar_<?= $value->id ?>" data-id="<?= $value->id ?>">
                    <?= $value->getAvatar() ?>
                </div>
            <?php }
            ?>
        </div>
        <?php
        $workspacelist = Workspace::model()->findAll(array('condition' => $condition, 'order' => 'sort_order'));
        foreach ($workspacelist as $value) {
            ?>
            <style>
                .card<?= $value->id ?> .noDrop{
                    background-color:<?= $value->color_code ?> !important;
                    color:#808080;
                }

             
            </style>
            <div class="workspace-card card"   >
                <div class="card-header panel-theame " style=" background-color:<?= $value->bg_color_code ?>"><b style="color: #3f3f3f; "><?= $value->name ?><br><span id="ws_total_<?= $value->id ?>">00.00</span></b>

                </div>
                <div id="workspace_id_<?= $value->id ?>" class="card-body card<?= $value->id ?>"style="width: 100%;height: 100%;"  ondrop="drop(event)" ondragover="allowDrop(event)" >


                </div>
            </div>
        <?php } ?>
    </div>
</section>
<style>
    .workspace-card{
        color:gray;
        width: 200px;
        float: left;
        /* min-height: 500px; */
        min-height: 5000px;
        
        margin: 5px;
        border: solid 1px #ebe3e3;
        padding-bottom: 30px;
        /*overflow: scroll;*/
    }
    .card-header{
        display: block;
        font-weight: 450;
        width: 100%;
        text-align: center;
        /*        background-color: gray;*/
        color: #828181;
    }
    .card-body{
        display: block;
        width: 100%;
        height: 100%;
        min-height:470px;
        /*background-color: #666666;*/
        /*overflow: scroll;*/
    }
    .label{
        /* height: 90px; */
        height: 102px;        
        margin: 2px;
        font-size: 14px
    }
    .itemclose{
        text-decoration: none;
        text-shadow: 0 1px 0 gray;
        opacity: 0.75;
    }
    .itemclose:hover{
        text-decoration: none;
        color: whitesmoke;
        opacity: 1;
    }
    .inner-card{
        top:16px;
        position: relative;
    }
    .label-list{
        text-align: start;
        margin: 0px;
        list-style: none;
        width: 100%;
        padding: 0px;
    }
    
</style>
<script>
    function allowDrop(ev) {
        ev.preventDefault();
    }

    function drag(ev) {
        ev.dataTransfer.setData("text", ev.target.id);
    }
    function dragUser(ev) {
        ev.dataTransfer.setData("user", ev.target.id);
    }

    function drop(ev) {
        var _target = $("#" + ev.target.id);
        var data = ev.dataTransfer.getData("text");
        




       
      


        if (data == "") {
            var user = ev.dataTransfer.getData("user");

            if (user != "") {
                addUserto(user, ev.target.id)
            }
            ev.preventDefault();
            return false;
        } else {

        }
        // console.log(data);
        // console.log(ev.target.id);
        var workspace_id = ev.target.id.split('_')[2];
        var item_id = data.split('_')[2];
        if ($(_target).hasClass("noDrop")) {
            //debugger;
            // console.log("no transfer");
            ev.preventDefault();
            var card_body = $(ev.target).parent('.card-body');
            // console.log(card_body);
            $(card_body).append(document.getElementById(data));
            var workspace_id = $(ev.target).parent('.card-body').prop('id').split('_')[2];

            updateItem(workspace_id, item_id);

        } else {
            ev.preventDefault();
            ev.target.appendChild(document.getElementById(data));
            updateItem(workspace_id, item_id);


        }
        $("#" + data).tooltip('hide');
        // var workspace_id = ev.target.id.split('_')[2];
        updateTotalAmount();
        rearrangeItems(workspace_id);
    }
    function rearrangeItems(workSpaceId) {
        var hasHiddenItems = false;
        var items = $("#workspace_id_" + workSpaceId).find(".note-item");
        var totalItems = items.length;
        var remaining = 0;
        if (totalItems > DISPLAY_ITEM_LIMIT) {
            hasHiddenItems = true;
            remaining = totalItems - DISPLAY_ITEM_LIMIT;
            var index = 0;
            for (var item in items) {
                try {
                    var id = "#" + items[index].id;
                    // debugger;
                    if (index < (totalItems - DISPLAY_ITEM_LIMIT)) {
                        $(id).hide();
                    } else {
                        $(id).show();
                    }
                } catch (exception) {

                }

                index++;
            }
        } else {
            hasHiddenItems = false;
            $("#workspace_id_" + workSpaceId).find(".note-item").show();
        }
        $("#show-all-" + workSpaceId).remove();
        if (hasHiddenItems) {
            var showMore = "<div style='text-align: center;' id ='show-all-" + workSpaceId + "' ><a href='#' onclick='showAll(" + workSpaceId + ")' >Show  All(+" + remaining + ")</a></div>";
            $("#workspace_id_" + workSpaceId).append(showMore);
            console.log(showMore);
        } else {
        }
        console.log("#workspace_id_ => " + workSpaceId);
    }
    function showAll(id) {
        var through_id =$("#through_id").val();
        loadPopupModal("workspace/space/viewall&ws_id=" + id+"&through_id="+through_id, "Workspace", "xl");
    }
    function dropOnCard(ev) {
        ev.preventDefault();
    }
    function updateItem(workspace_id, item_id) {

    
        $.ajax({
            url: "index.php?r=workspace/space/CheckQtnexist",
            type: 'POST',
            dataType: 'json',
            data: {
                workspace_id: workspace_id,item_id:item_id
            },
            success: function (data, textStatus, jqXHR) {
              
                if(data == '1'){
                    loadPopupModal('workspace/space/Changeworkspace&workspace_id='+workspace_id+'&item_id='+item_id,"Reason");
                  
                }else if(data == '2'){
                  $.ajax({
            url: "index.php?r=workspace/space/UpdateWorkspace",
            type: 'POST',
            dataType: 'json',
            data: {
                workspace_id: workspace_id, item_id: item_id
            },
            success: function (data, textStatus, jqXHR) {
                rearrangeItems(data.prev);
                updateTotalAmount();
            }
        });

                }else{
                    location.reload();
                }
                rearrangeItems(workspace_id);
                // rearrangeItems(data.prev);
                 updateTotalAmount();
            }
        });

        // $.ajax({
        //     url: "index.php?r=workspace/space/UpdateWorkspace",
        //     type: 'POST',
        //     dataType: 'json',
        //     data: {
        //         workspace_id: workspace_id, item_id: item_id
        //     },
        //     success: function (data, textStatus, jqXHR) {
        //         rearrangeItems(data.prev);
        //         updateTotalAmount();
        //     }
        // });
    }
    function addItem(data) {



        if ($("#note_id_" + data.id).length == 0) {
            var closeBtn='';
            if(data.lead_id > 0){
            closeBtn += '<span style=" float: left;font-size: 12px;color: '+data.bgcolor+'">'+data.lead_id+'</span>';
        }    


               //   ----------------------------

        if(data.status == "H"){
            closeBtn += '<a  title="High" class="itemclose noDrop" href="#" style=" margin-right: 8px;float: right;color: red;font-size: 14px;"><i class="fa fa-certificate"></i></a>';

        }else if(data.status == "N"){
            closeBtn += '<a  title="Normal" class="itemclose noDrop" href="#" style="margin-right: 8px;float: right;color: green;font-size: 14px;"><i class="fa fa-certificate"></i></a>';

        }else{
            closeBtn += '<a  title="Low" class="itemclose noDrop" href="#" style="margin-right: 8px;float: right;color: yellow;font-size: 14px;"><i class="fa fa-certificate"></i></a>';
        }
 //   ----------------------------



           //  closeBtn = '<a  onclick="loadPopupModal(\'activity/activity/detailsActivity&frm=WS&customer_id='+data.customer_id+'&header_id=' + data.id + '\',\'Activity\',\'xl\')" class="itemclose noDrop" href="#" style="margin-right: 8px;float: right;color: white;font-size: 14px;"><i class="fa fa-globe"></i></a>'+ closeBtn;
             <?php if(isset(Yii::app()->user->havePermissionOn['workspace_delete'])){?>
                closeBtn= '<a  onclick="deleteItem( ' + data.id + ', this);" class="itemclose noDrop" href="#" style="margin-right: 0px;float: right;color: '+data.bgcolor+';font-size: 14px;"><i class="fa fa-close"></i></a>' + closeBtn;
             <?php } ?>


         



             closeBtn+= '<a  onclick="loadPopupModal(\'activity/activity/history&frm=WS&customer_id='+data.customer_id+'&header_id=' + data.id + '\',\'Activity\',\'xl\')" class="itemclose noDrop" href="#" style="margin-right: 8px;float: right;color:'+data.bgcolor+' ;font-size: 14px;"><i class="fa fa-certificate"></i></a>';
       
             closeBtn+= '<a  onclick="loadPopupModal(\'workspace/space/getsummary&ws_id='+data.id+'&customer_id='+data.customer_id+'&header_id=' + data.id + '\',\'Summary - '+data.customer_name+'\',\'xl\')" class="itemclose noDrop" href="#" style="margin-right: 8px;float: right;color: '+data.bgcolor+';font-size: 14px;"><i class="fa fa-list"></i></a>';
             if (data.quotes_id > 0) {
               
              closeBtn+= '<a class="itemclose noDrop" title="Print Quotation" target="_blank" href="?r=quotation/PrintQuotationReportPDF&id='+data.quotes_id+'" style="margin-right: 8px;float: right;color: '+data.bgcolor+';font-size: 14px;"><i class="fa fa-file-pdf-o"></i></a>';
             }
             var share_html = getShareHtml(data.shared_to);
            // shred item

            var html = '<div ondblclick=\'loadPopupModal("workspace/space/create&id=' + data.id + '","Add New Workspace", "lg")\'  class="label noDrop note-item" style="display: block; border-style: solid; border: 1px solid grey; " draggable="true" ondragstart="drag(event)" id="note_id_' + data.id + '" >' + closeBtn + '<div  ondrop="return false;" id="note_innerid_' + data.id + '"   amount="' + data.amount + '" class="inner-card work-note-title noDrop">' + data.title + "</div>" + share_html + ' </div>';
            $("#workspace_id_" + data.workspace_id).append(html);
        } else {
            $("#note_innerid_" + data.id).html(data.title);
            var workspace_id = $("#note_id_" + data.id).prop('workspace');
            if (data.workspace_id != workspace_id) {
                var note = $("#note_id_" + data.id).detach();
                $("#workspace_id_" + data.workspace_id).append(note);
            }
            var share_html = getShareHtml(data.shared_to);
            //debugger;
            // avatar
            //  $("#note_id_" + data.id + " .share-container ").replaceWith(share_html);
        }
        var itemsCount = $("#workspace_id_" + data.workspace_id).find(".note-item").length;
        if (itemsCount > DISPLAY_ITEM_LIMIT) {
            $("#note_id_" + data.id).hide();
            rearrangeItems(data.workspace_id);
        }
        $("#note_id_" + data.id).prop('data-toggle', 'tooltip');
        $("#note_id_" + data.id).prop('title', data.tooltip);
        $("#note_id_" + data.id).prop('lead_id', data.lead_id);
        $("#note_id_" + data.id).prop('file_id', data.file_id);
        $("#note_id_" + data.id).prop('workspace', data.workspace_id);
        $("#note_id_" + data.id).prop('itemid', data.id);
        $("#note_id_" + data.id).attr('amount', data.amount);
        $("#note_id_" + data.id).prop('html', true);
        $("#note_id_" + data.id).tooltip({title: data.tooltip, html: true, placement: "bottom"});
    }
    function getShareHtml(shared_to) {
        var share_item_conatinter_div = document.createElement('div');
        $(share_item_conatinter_div).addClass('share-container')
        $(share_item_conatinter_div).css({'color': 'white', 'bottom': '0px', 'position': 'relative', 'top': '15px'});
        $(shared_to).each((index, el) => {
            var share_item_span = document.createElement('div');
            share_item_span.innerHTML = el.name;
            var avatar_id = "#wsavatar_" + el.id;
            var bgcolor = $(avatar_id).css('background-color');
            var title = $(avatar_id).prop('title');
            // console.log(avatar_id);
            $(share_item_span).css({
                'float': 'right',
                'border-radius': '50%',
                'border': 'solid 1px white',
                'font-size': '9px',
                'height': "20px",
                'padding': '6px',
                'width': '20px',
                'padding-left': '3px',
                'background': bgcolor,
                opacity: ' 0.8'
            }
            );
            $(shared_to).prop('ondragover', 'return false');
            $(shared_to).prop('title', title);
            share_item_conatinter_div.appendChild(share_item_span);
        });
        $(share_item_conatinter_div).prop('ondragover', 'return false');
        return "";
        // return share_item_conatinter_div.outerHTML;
    }
    $(document).ready(function () {
        reloadCalendar();
    });
    function deleteItem(id, evt) {
        var msg = "Are you sure you want to delete this item?";
        var dr = confirm(msg);
        if (dr) {
            $.ajax({
                url: "index.php?r=workspace/space/deleteItem",
                type: 'POST',
                dataType: 'json',
                data: {id: id},
                beforeSend: function (xhr) {
                    //$("#loader").show();
                },
                success: function (data, textStatus, jqXHR) {
                    $(evt).parent().tooltip('hide');
                    $(evt).parent().remove();
                    updateTotalAmount();
                    //$("#loader").hide();
                }
            });
        }
    }
    function dropLead(ev) {
        var id = ev.dataTransfer.getData("text");
        //console.log(ev.dataTransfer.getData("text"));
        var lead_id = $("#" + id).prop('lead_id');
        var note_id = id.split('_')[2];
        loadPopupModal("lead/create&id=" + lead_id + "&note_id=" + note_id, 'Lead', "lg");
        ev.preventDefault();
    }
    function dropQuotation(ev) {
        var id = ev.dataTransfer.getData("text");
        //console.log(ev.dataTransfer.getData("text"));
        var lead_id = $("#" + id).prop('lead_id');
        var file_id = $("#" + id).prop('file_id');
        var note_id = id.split('_')[2];
        if (lead_id == 0) {
            loadPopupModal("quotation/create&note_id=" + note_id, "Quotation", "xl");
        } else {
            loadPopupModal("quotation/create&lead_id=" + lead_id + "&file_id=" + file_id + '&note_id=' + note_id, "Convert To Quotation", "xl");
        }
        ev.preventDefault();
    }
    function addUserto(user, target) {
        var item_id = target.split('_')[2];
        var user_id = user.split('_')[1];
        $.ajax({
            url: "index.php?r=workspace/space/shareItem",
            type: 'POST',
            dataType: 'json',
            data: {id: item_id, 'user_id': user_id},
            beforeSend: function (xhr) {
                $("#loader").show();
            },
            success: function (data, textStatus, jqXHR) {
                $("#loader").hide();
                //console.log(data);
                addItem(data.item);
            }
        });
    }
    function updateTotalAmount() {
        var cardBodyArray = $('.card-body');
        $.each(cardBodyArray, (i, cardBody) => {
            //console.log(cardBody);
            var cardBodyId = $(cardBody).prop("id").toString();
            var cardBodyIdArray = cardBodyId.split("_");
            var workSpaceId = cardBodyIdArray[2];
            var noteItems = $(cardBody).find(".work-note-title");
            var totalAmount = 0;
            for (var i = 0; i < noteItems.length; i++) {
                var noteId = $(noteItems[i]).prop("id");
                //console.log(noteId);
                var _amountText = $("#" + noteId).attr("amount");
                var amount = parseFloat(_amountText);
                if (!isNaN(amount)) {
                    totalAmount += parseFloat(_amountText);
                }
            }
            var totalLabelId = "#ws_total_" + workSpaceId;
            $(totalLabelId).html(totalAmount.toLocaleString("en-IN"));
        });
    }
</script>
<style>
    #quotation_drop, #lead_drop{
        border: dashed 2px #6c8c96;
        padding: 8px;
        width: 220px;
        text-align: center;
        color: #4669ad;
        margin-left: 50px;
        background: #ecf5fd;
    }
    .ws-avatar{

        border-radius: 50%;
        font-size: 10px;
        opacity: 0.8;
        font-weight: 600;
        color:white;
        width: 30px;
        height: 30px;
        text-align: center;
        float: left;
        padding-top:  7px;
        margin: 2px;

    }
    .ws-avatar:hover{
        opacity: 1;
        padding-top:  8px;
        width: 34px;
        height: 34px;
        margin: 0px;
    }
</style>