<?php  if ($permissions->hasPermission('add_deal_pipeline')) {
    include 'Views/crm/deal_modal.php';
}
include 'Views/crm/reason_modal.php';
?>
<script src="<?php echo VIEWS_PATH; ?>crm/common.js"></script>
<link href="<?php echo THEME_PATH; ?>plugins/icheck/icheck.css" rel="stylesheet" type="text/css"/>
<script src="<?php echo THEME_PATH; ?>plugins/icheck/icheck.min.js" type="text/javascript"></script>
<script src="<?php echo THEME_PATH; ?>js/loadingoverlay.min.js"></script>
<script src="<?php echo THEME_PATH; ?>js/loadingoverlay_progress.min.js"></script>
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/core/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/daygrid/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/timegrid/main.css' rel='stylesheet' />
<link href='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/list/main.css' rel='stylesheet' />
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/core/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/interaction/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/daygrid/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/timegrid/main.js'></script>
<script src='<?php echo THEME_PATH; ?>plugins/fullcalendar-4.2.0/packages/list/main.js'></script>

<style>
    .lostdeal{
        color: white !important;
    }
</style>

<!--
<style>
a.btn-complete{
margin-bottom: 0px;
width: 272px;
margin-left: 0px;
}
.popover {
z-index: 3;
}
.popover .popover-title {
width: 100%;
padding: 10px;
}
.popover .row {
width: 100% !important;
}
.popover h5 {}
.popover p {
width: 100%;
}
.list-group {
margin-bottom: 0px;
padding-bottom: 0px;
}
.list-group-item:first-child {
border-radius: 0px;
}
.list-group-item:last-child {
border-radius: 0px;
}
.list-group-item.text-center.btn.specialeffect {
font-size: 20px;
background: #EEE;
color: lightblue;
text-shadow: 1px 1px 2px blue;
}
.iconright {
position: relative;
top: 5px;
}
.activityEditor__form,
.editActivityDialog .activityEditor__form,
.flowActivity .activityEditor__form {
overflow: hidden;
box-sizing: border-box;
border-left: 1px solid #e0e4e7;
height: 32px;
max-height: inherit
}
.flowActivity {
padding: 0px !important
}
label.widget-radio.active {
background: #e0e4e7;
box-shadow: inset 0 1px 2px rgba(38,41,44,0.1);
}
.flowActivity .activityEditor__form {
border-left: 0px
}
div.activityEditor__form{
overflow: hidden !important;
}
.table tbody tr.greenfont{
color: green !important;
}
.table tbody tr.redfont{
color: red !important;
}
.table tbody tr.redfont td[class*='sorting_'] {
color:    red !important;
}
.table tbody tr.greenfont td[class*='sorting_'] {
color:    green !important;
}
.label {
cursor: pointer;
}
.activetype{
background: #eee !important;
}
.activedate{
background: #eee !important;
}
.pagination>li>a, .pagination>li>span{
padding: 9px 18px;
font-size: 18px;
}
#eventtable tbody tr td:first-child{
text-align: center;
}
.
</style>
-->
<style>
    #eventcheckbox{
        display:inline;
    }
    .increaseheight {
        min-height: 420px;
    }
    .panel .panel-heading {
        margin-bottom: 0 !important;
    }
    .panel.panel-default.sortitem {
        width: 100%;
    }
    .panel-default {
        border-color: #ddd !important;
    }
    .panel-default>.panel-heading {
        color: white;
        background-color: #4c0870 !important;
        border-color: #4c0870 !important;
    }
    page-inner{
        min-height: 100% !important;
    }
    .popover-content{
        padding:0!important;
    }
    #container .fa.fa-blue {
        color: #09ace8 !important;
    }
    #container .fa.fa-green {
        color: #09e844 !important;
    }
    #container .fa.fa-red {
        color:#e00202 !important;
    }
    #container .fa-comment{
        cursor:pointer;
    }
    .panel.panel-default.deals{
        margin-bottom: 5px;
    }
    .panel.panel-default{
        margin-bottom:5px;
    }
    .page-footer {
        z-index: 10000 !important;
        top: 85%;
        background: white;
        padding-top: 20px;
        padding-bottom: 25px;
        padding-right: 20px;
        position: relative;
        width: 100%;
    }
    .page-footer .fa {
        color: black !important;
    }
    .fill .wondeal>h1,.fill .lostdeal>h1 {
        margin-top:0px!important;
    }
    .border-left {
        border-left: 3px solid #cad1d9;
        min-height: 100%;
    }
    @media only screen and (min-width: 1204px) {
        .row.increaseheight {
            display: -webkit-box;
            display: -webkit-flex;
            display: -ms-flexbox;
            display: flex;
            flex-wrap: wrap;
        }
        .row.increaseheight>[class*='col-'] {
            display: flex;
            flex-direction: column;
        }
    }
    .popover.left{
        margin-left:-15px !important;
    }
</style>
<div class="page-inner panel-body">
    <?php  if ($permissions->hasPermission('add_deal_pipeline')) {?>
    <a style="color:white !important;" class="btn bg-complete-dark" id="add_deal" data-origin="pipeline" data-modal-name="add" data-toggle="modal" data-target="#deal_modal"><?php print CommonLanguage::getMessage('add_deal'); ?>
    </a>
    <?php }?>
    <div class="containpage m-t-10">
        <div id="main-wrapper">
            <div class="row increaseheight " id="container">
                <?php echo Forms::ModalLoader('pipelineDisabler'); ?>
                <?php $stages_length = count($deal_stages); $width= 100/$stages_length; foreach($deal_stages as $stage){?>
                <div class="col-md-2 state stages_top" id="<?php  echo preg_replace('/\s+/', '_',$stage['stage_title']);?>" data-progress="<?php  echo $stage['stage_id'];?>" style="width:<?php  echo $width;?>%"></div>
                <?php }?>
            </div>
            <div class="page-footer" style="position: fixed; display: none;">
                <div class="row" id="actionodeals">
                    <div class="col-lg-4 fill">
                        <div class="deletedeal a text-center" data-action="delete">
                            <i class="fa fa-trash fa-4x"></i>
                        </div>
                    </div>
                    <div class="col-lg-4 fill">
                        <div class="wondeal a text-center" data-action="Won">
                            <h1  style="color:white !important;"><?php print CommonLanguage::getMessage('won'); ?></h1>
                        </div>
                    </div>
                    <div class="col-lg-4 fill">
                        <div class="lostdeal a text-center"  style="color: white;"  data-action="Lost">
                            <h1><?php print CommonLanguage::getMessage('lost'); ?></h1>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var divid = "",check,dropid,indexofitem,actId,dealId,reason_modal_flag = 0,
        arg = ['deal_title', 'deal_id', 'deal_state', 'Name', 'activities', 'organization_customer_name', 'contact_name'];
    $(function(){
        getPipelineData();
        $("#container").on("click", "[data-type=popover]", function (e) {
            //get it of the row to fill the event in the popup
            e.stopPropagation();
            getactivity($(this).attr("data-id"), this);
        });
        $("#container").on("ifClicked", 'input[type=checkbox]', function (event) {
            event.stopPropagation();
            $(this).parent().toggleClass("checked");
            $.ajax({
                url: "crmAjax/updateActivityStatus",
                type: "POST",
                data: { activity_id: $(this).attr("data-check-id"),activity_checked: 1 },
                success: function () {
                    closeallpopup();
                    getPipelineData();
                }
            });
        });
        $("#container").on("shown.bs.popover", function () {
            checkbox();
        });
    });
    function getPipelineData(){
        $("#pipelineDisabler").removeClass('hidden')
        $.ajax({
            url: "crmAjax/pipelineData",
            dataType: "JSON",
            success: function(data) {
                //specify part we want to display
                //specify data soucre and element and part displayed and the count
                iteratethroughdata(data);
                //creating a callback
                makedraggable(data)
                makethemdroppable1($(".a"));
                makethemdroppable2($(".state"));
                $(".page-footer").hide();
                $("#pipelineDisabler").addClass('hidden')
            }
        })
    }
    function iteratethroughdata(stages) {
        $.each(stages, function (index, element) {
            var name= stages[index]['stage_title'],select_name= stages[index]['stage_title'].replace(/ /g, "_")
            //initialize the selector
            $('#'+select_name).html("");
            //variables
            var count = 0;
            //iterate through json data
            if('deals' in element){
                var data =  element['deals'];
                $.each(data, function (index, element) {
                    //count rows
                    count++;
                    //append rows
                    var icon="fa fa-2x ";
                    var icon = getIcon(element[arg[4]]);
                    var text="";
                    if(element[arg[5]]!="" && element[arg[5]])
                        text+="<i class='fa fa-building'></i> "+element[arg[5]]+"&nbsp;";
                    if(element[arg[6]]!="" && element[arg[6]])
                        text+="<i class='fa fa-user'></i> "+element[arg[6]]+"&nbsp;";
                    $('#'+select_name).append(
                        "<div class='panel panel-default deals sortitem ' data-state='" + element[arg[2]] + "'data-row-id='" + element[arg[1]] + "' data-org-id='" + element['organization_id'] + "'><div class='panel-body'><div><span class=''> " + text+ " <br><b>" + element[arg[0]] + " "+(element['deal_value'] ?  (" - "+element['deal_value']+" "+element['Currency_Symbol']) : '')+"</b></span></div><div>	<span class='pull-right iconright' data-type='popover'  data-id='" + element[arg[1]] + "'><i class='fa fa-2x "+icon+"' aria-hidden='true'></i></span><a class='pull-left iconright' href='"+site_link+"crm/dealDetails/"+element[arg[1]]+"' ><i class='fa fa-2x fa-info-circle' aria-hidden='true'></i></a></div></div></div>"
                    );
                });
            }
            //append header
            $('#'+select_name).prepend("<div class='panel panel-default'><div class='panel-heading'>" + name + " <span id='" + name + "'count class='pull-right'>" + count + "</span></div></div>");
        });
    }
    function getIcon(activities){
        var icon = "";
        if(activities.length == 0){
            icon = "fa-blue fa-comment ";
        }else{
            let current_obj = activities.find(activity => moment(activity['end_date']).format('YYYY-MM-D hh:mm:ss') <= moment().format('YYYY-MM-D hh:mm:ss'));
            if(current_obj){
                icon = "fa-red fa-comment  ";
            }else{
                icon = "fa-green fa-comment  ";
            }
        }
        return icon;
    }
    function makedraggable(stages){
        $.each(stages,function(i,stage){
            if('deals' in stage){
                var deals = stage['deals'];
                $.each(deals, function (index, element) {
                    $('.sortitem').draggable({
                        //start of drag
                        delay:250,
                        revert: function (socketObj) {
                            var state = $(socketObj).attr("data-progress");
                            var targetstate = $(divid).parent().attr("data-progress");
                            $('.state').css("background", "#FAFAFA");
                            if ($(socketObj).hasClass('.page-footer') || (targetstate == state) || typeof (targetstate) == "undefined" || typeof (state) == "undefined" || check == false) {
                                // Drop was rejected, revert the helper.
                                return true;
                            } else {
                                // Drop was accepted, don't revert.
                                return false;
                            }
                        },
                        containment: "document",
                        opacity: 0.5,
                        stop: function (e, ui) {
                            $(divid).css("cursor", "default");
                            $('.page-footer').hide();
                            $(this).css("z-index", "2");
                        },
                        start: function (e, ui) {
                            $(this).css("z-index", "100002");
                            check = true;
                            divid = this;
                            closeallpopup();
                            $('.page-footer').show();
                        },
                    });
                });
            }
        });
        initializeallpopup();
    }
    function initializeallpopup(){
        $("[data-type=popover]").each(function () {
            $(this).popover({
                content: "",
                html: true,
                delay: {
                    show: "200",
                    hide: "100"
                },
                placement: 'left',
                template: '<div class="popover popover-medium"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>',
            });
        });
    }
    function closeallpopup(){
        $("[data-type=popover]").each(function () {
            $(this).popover("hide");
        });
        //stop dragging
        $(".sortitem").draggable("enable");
    }
    function makethemdroppable1(selectors, cb) {
        //drop containers
        selectors.each(function () {
            $(this).droppable({
                //on pointing
                tolerance: "pointer",
                //drop start
                over: function (event, ui) {
                    $(divid).css("cursor", "default");
                    check = false;
                },
                out: function (event, ui) {
                    check = true;
                    $(divid).css("cursor", "no-drop");
                },
                drop: function (event, ui) {
                    //enabled add button
                    $("#modalbuttonreason").prop("disabled", false);
                    //save the object we will drop into it the item
                    dropid = this;
                    //save it of the incoming object
                    var id = $(divid).attr("data-row-id"),org_id =$(divid).attr("data-org-id");
                    //check current state of the  dragged  item
                    var state = $(dropid).attr("data-action");
                    //take state of drop container
                    check = false;
                    if (state == "delete") {
                        deletedeal(id);
                    } else {
                        if (state == "Lost") {
                            //show reason modal
                            showModalReasonForLoss(id);
                        } else if (state == "Won") {
                            // update the state	
                            updatestate(id, state,org_id);
                        }
                    }
                }
            });
        });
    }
    function showModalReasonForLoss(id){
        $("#reason_deal_id").val(id)
        $("#reason-modal").modal("show")
    }
    function deletedeal(id){
        $.ajax({
            url: 'crmAjax/deleteDeal',
            type: 'POST',
            beforeSend: function () {
                $("#pipelineDisabler").removeClass('hidden')
                $(divid).fadeOut();
            },
            data: {
                //sending the id of the row we want to delete
                deal_id: id
            },
            success: function () {
                getPipelineData()
                $("#pipelineDisabler").addClass('hidden')
            },
            error: function () {
                $("#pipelineDisabler").addClass('hidden')
            }
        });
    }
    function updatestate(id, state,org_id){
        $.ajax({
            type: "POST",
            url: "crmAjax/submitDealState",
            data: {
                //id of the deal
                deal_id: id,
                deal_state:state,
                org_id:org_id
            },
            beforeSend: function () {
                $(divid).fadeOut();
                $("#pipelineDisabler").removeClass('hidden')
            },
            success: function () {
                //refilling data
                getPipelineData()
                $("#pipelineDisabler").addClass('hidden')
            },
            error: function () {
                $("#pipelineDisabler").addClass('hidden')
            }
        });
    }
    function makethemdroppable2(selectors,cb){//drop containers
        selectors.each(function () {
            $(this).droppable({
                //on pointing
                tolerance: "pointer",
                //drop start
                over: function (e, ui) {
                    $(this).css("background", "lightgray");
                    dropdiv = $(this);
                },
                out: function (e, ui) {
                    $(this).css("background", "#FAFAFA");
                    dropdiv = $(this);
                },
                drop: function (event, ui) {
                    $(this).css("background", "#FAFAFA");
                    $('.page-footer').hide();
                    var state = $(this).attr("data-progress");
                    var targetstate = $(divid).parent().attr("data-progress");
                    var index = $(divid).prevAll().length;
                    var numberofitem = $("div.panel-body", $(this)).length;
                    if (typeof (targetstate) != "undefined" && typeof (state) != "undefined" && state != targetstate) {
                        if (check == true) {
                            indexofitem = (numberofitem + 1);
                            //save it of the incoming object
                            var id = $(divid).attr("data-row-id");
                            updateStage(id, state);
                        }
                    }
                }
            });
        });
    }
    function updateStage(id,target){
        $.ajax({
            type: "POST",
            beforeSend: function () {
                $("#pipelineDisabler").removeClass('hidden')
            },
            url: "crmAjax/updateDealStage",
            data: {
                //id of the deal
                deal_id: id,
                order_id: indexofitem,
                //new state
                stage_id: target,
            },
            success: function () {
                //refilling data
                getPipelineData()
                $("#pipelineDisabler").addClass('hidden')
            }
        })
    }
    function checkbox(){
        $('.page-inner input[type=checkbox]').iCheck({
            checkboxClass: 'icheckbox_square-blue'
        });
    }
    function getPlannedOverdueActivities(id,popover){
        $.ajax({
            dataType: "JSON",
            type: "POST",
            url: "crmAjax/getPlannedOverDueActivity",
            data: { deal_id: id },
            beforeSend: function () {
                $(popover).popover({
                    placement: "left"
                });
                $("#container .popover").LoadingOverlay('show');
            },
            success: function (data) {
                var contentplanned = [];
                var contentoverdue = [];
                var countplanned = data['main']['planned'].length;
                var countoverdue = data['main']['overdue'].length;
                var deal_details = data['deal_details'];
                if (countplanned != 0) {
                    $.each(data['main']['planned'], function (index, element) {
                        contentplanned.push("<a class='add list-group-item edit_activity' data-id='" + element['id'] + "' data-origin='pipeline' data-event-name='edit' data-toggle='modal' data-target='#activity_modal'>\
<h5>	<input   data-check=checkactivty data-check-id='" + element['id'] + "'  type=checkbox /> <b> " + element['title'] + " </b></h5><p><b>Notes: </b>" +element['activity_notes']+ "</p>\
    </a>");
                    });
                    contentplanned.unshift("<div class='list-group'><a  class='list-group-item disabled'>Planned</a>");
                }
                if (countoverdue != 0) {
                    $.each(data['main']['overdue'], function (index, element) {
                        contentoverdue.push("<a class='list-group-item add edit_activity' data-id='" + element['id'] + "' data-origin='pipeline' data-event-name='edit' data-toggle='modal' data-target='#activity_modal'>\
<h5>	<input   data-check=checkactivty data-check-id='" + element['id'] + "'  type=checkbox / ><b> " + element['title'] + "</b></h5><p><b>Notes: </b>" + element['activity_notes'] + "</p>\
    </a> ");
                    });
                    contentoverdue.unshift("<div class='list-group'><a  class='list-group-item disabled'>Overdue </a>");
                }
                contentoverdue.push("<a class='center-block btn btn-complete text-center add add_activity' data-origin='pipeline' data-toggle='modal' data-target='#activity_modal' data-event-name='add'  data-deal-id='" + id+ "' data-deal-title='"+deal_details['deal_title']+"' data-contact-id='"+deal_details['contact_id']+"' data-contact-name='"+deal_details['contact_name']+"' data-customer-id='"+deal_details['organization_id']+"' data-customer-name='"+deal_details['organization_customer_name']+"'>Add Activity</a></div>");
                $(popover).attr("data-content", contentplanned.join("") + contentoverdue.join(""));
                checkbox();
                dealId= id;
            }
        }).complete(function () {
            $("#container .popover").LoadingOverlay('hide');
        });
    }
    function getactivity(id,popover){
        if ($(".popover").hasClass("in")) {
            //close opened popup
            $(".popover").popover("hide");
            //fetch data and open popup
            getPlannedOverdueActivities(id, popover);
        } else {
            $(".popover").popover("hide");
            getPlannedOverdueActivities(id, popover);
        }
    }
</script>
<?php 

include 'Views/crm/activity_modal.php';