<link href="<?php echo THEME_PATH; ?>css/pipeline.css" rel="stylesheet" type="text/css"/>
<link href="<?php echo THEME_PATH; ?>plugins/tooltipster/tooltipster.bundle.min.css" rel="stylesheet" type="text/css"/>
<script src="<?php echo THEME_PATH; ?>plugins/tooltipster/tooltipster.bundle.min.js" type="text/javascript"></script>
<div class="modal  fade" id="deal_modal" role="dialog" aria-hidden="false">
    <div class="modal-dialog modal-md" >
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('add_deal'); ?></h5>
                <h5 class="edit-label h-labels text-left bold hidden"><?php echo CommonLanguage::getMessage('edit_deal'); ?></h5>
            </div>
            <div class="modal-body">
                <?php echo Forms::AlertDiv('deal_alert'); ?>
                <form id="deal_form" method="POST" onsubmit="return false">
                    <input type="hidden" name="deal_id" id="modal_deal_id">
                    <div class="row form-group">
                        <div class="col-md-6">
                            <label for="country"><?php print CommonLanguage::getMessage('organization'); ?></label>
                            <span class="red-star">*</span>
                            <input class="deal_organization_id full-width" id="deal_organization_id" name="deal_organization_id" type="hidden" value="" data-select-name=''  required/>
                        </div>
                        <div class="col-md-6">
                            <label for="person-deal"><?php print CommonLanguage::getMessage('contact'); ?></label>
                            <span class="red-star">*</span>
                            <input class="deal_contact_id full-width" id="deal_contact_id" name="deal_contact_id" type="hidden" value="" data-select-name='' required/>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-6">
                            <label for="title-input"><?php print CommonLanguage::getMessage('title'); ?></label>
                            <span class="red-star">*</span>
                            <input type="text" id="deal_title" name="deal_title" class="form-control" required data-container="body" />
                        </div>
                        <div class="col-md-6">
                            <label for="person-deal"><?php print CommonLanguage::getMessage('Category'); ?></label>
                            <span class="red-star">*</span>
                            <input class="Cat_ID full-width" autocomplete="off" id="Cat_ID" name="Cat_ID" type="hidden"  required/>
                        </div>
                    </div>
                    <div class="row form-group">
                        <div class="col-md-3">
                            <label for="Value"><?php print CommonLanguage::getMessage('deal_prob'); ?></label>
                            <input type="number" step="0.01" id="deal_probability" name="deal_probability" class="form-control"  />
                        </div>
                        <div class="col-md-3">
                            <label for="Value"><?php print CommonLanguage::getMessage('value'); ?></label>
                            <input type="number" step="0.01" id="deal_value" name="deal_value" class="form-control"  />
                        </div>
                        <div class="col-md-6">
                            <label for="currency"><?php print CommonLanguage::getMessage('currency'); ?></label>
                            <select id="currency_id"  name="currency_id" class="full-width " data-init-plugin="select2">
                                <option value=""><?php print CommonLanguage::getMessage('select'); ?></option>
                                <?php foreach ($currencies as $currency): ?>
                                <option value="<?php echo $currency['Currency_ID']; ?>" <?php echo $currency['Currency_ID'] == "84" ? 'selected' :'';?> ><?php echo $currency['Currency_Name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="row stages form-group">
                        <div class="field">
                            <label for="stage-1otURQwd"><?php print CommonLanguage::getMessage('pipeline_stage'); ?></label>
                            <span class="input stageOptionWrapper">
                                <div class="plainStages">
                                    <span class="options" id="pipe_stage">
                                        <?php foreach($deal_stages as $stage){?>
                                        <label class="widget-radio <?php print $stage['stage_id'] == 1 ? 'active'  :''; ?> tooltip"   title="<?php print $stage['stage_title']; ?>">
                                            <input type="radio" name="stage_id" value="<?php print $stage['stage_id']; ?>"  tabindex="0" data-title="<?php print $stage['stage_title']; ?>" >
                                        </label>
                                        <?php }?>
                                    </span>
                                </div>
                            </span>
                        </div>
                    </div>
                    <div class="row m-t-10 form-group">                  
                        <div class="col-md-12">     
                            <label class="">Allowed File Extensions: .jpg, .gif, .jpeg, .png, .pdf, .txt, .csv,  .zip, .log, .docx</label>
                            <input type="file" id="deal_attachments" class="form-control" name="deal_attachments[]" multiple onchange="ValidateForNewAttachment(this,['.jpg', '.gif', '.jpeg', '.png', '.pdf', '.txt', '.csv',  '.zip', '.log', '.docx'])">
                            <div class="display-flex deal_attachments_div" >
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('cancel'); ?></button>
                <button style="color:white !important;" type="button" id="submit_deal" class="btn bg-complete-dark"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
        </div>
        <?php echo Forms::ModalLoader('deal_loader'); ?>
    </div>
</div>
<script>
    var deal_stage = 1,deal_origin,default_category_data =<?php echo json_encode($default_category_data);?>,
        deleted_attachments = [];
    $(function(){
        build_select2($("#Cat_ID"), "xhr/CommonSearch?col_name=Cat_Name&col_id=Cat_ID&table=tbl_product_cat",1);
        build_select2($("#deal_organization_id"), "xhr/getOrganizations?contact=1")
        build_select2($("#deal_contact_id"), "xhr/getContacts?organization_id="+$("#deal_organization_id").val());
        $(".stages .widget-radio ").on('click',function () {
            deal_stage = $("input[name=stage_id]",$(this)).val()
            removeclassactive();
            $(this).addClass("active");
        });
        $('#deal_organization_id').on('change',function(){
            $("#deal_contact_id").val('')
            if($(this).val()){
                var select_data = $(this).select2('data');
                $('#deal_title').val(select_data.text+' Deal');
                if(select_data.count == 1)
                    $('#deal_contact_id').val(select_data.contact_id).attr('data-select-name',select_data.contact_name);
            }else{
                $('#deal_title').val('');
            }
            build_select2($("#deal_contact_id"), "xhr/getContacts?organization_id="+$("#deal_organization_id").val()); 
        });
        $('.tooltip').tooltipster();
        $('.tooltip').removeClass('tooltip tooltipster');
        $(".panel-body").on("click",'#add_deal,.add_deal_profile',function(){
            deleted_attachments = [];
            $("#deal_modal .add-label").removeClass('hidden')
            $("#modal_deal_id").val(0);
            deal_origin = $(this).attr('data-origin');
            if(deal_origin == 'profile'){
                $('#deal_organization_id').val($('#org_id').val()).attr('data-select-name',$('#current_organization_name').val()).trigger('change')
                $('#deal_organization_id').prop('disabled',true);
                if($("#contact_profile_id").val()){
                    $('#deal_contact_id').val($("#contact_profile_id").val()).attr('data-select-name',$('#CName').html()).trigger('change');
                    $('#deal_contact_id').prop('disabled',true);
                }
            }else{
                $('#deal_organization_id,#deal_contact_id').prop('disabled',false);
            }
            if(default_category_data.length > 0){
                $('#Cat_ID').select2('val', []);
                $('#Cat_ID').data().select2.updateSelection(default_category_data);
            }
            $('#currency_id').val(84).select2();
            removeclassactive();
            $($("#pipe_stage").children()[0]).addClass("active");
            if ($($("input[type=radio]").parents()[0]).hasClass("active"))
                ($("input[type=radio]").parents()[0]).prop("checked", "checked");
            deal_stage = 1;
        }); 
        $("#tableWithSearch").on("click",".edit_deal",function(){
            deleted_attachments = [];
            $("#deal_modal .edit-label").removeClass('hidden')
            var deal_id = $(this).attr("data-id")
            $("#modal_deal_id").val(deal_id);
            CommonViewById("crmAjax/getDealDetails",{rowId:deal_id},'#deal_loader',function(response){
                var main_response = response['main'][0],product_cat = response['product_category'];
                $("#deal_value").val(main_response.deal_value)
                $("#currency_id").val(main_response.currency_id).select2();
                removeclassactive();
                $($("#pipe_stage").children()[main_response.stage_id - 1]).addClass("active");
                $("input[type=radio]").each(function () {
                    if ($($(this).parents()[1]).hasClass("active"))
                        $(this).prop("checked", "checked");
                });
                deal_stage = main_response.stage_id;
                $("#deal_organization_id").val(main_response.organization_id).attr('data-select-name',main_response.organization_customer_name).trigger('change');
                $("#deal_contact_id").val(main_response.contact_id).attr('data-select-name',main_response.contact_name);
                build_select2($("#deal_contact_id"), "xhr/getContacts?organization_id="+main_response.organization_id);
                $('#Cat_ID').select2('val', []);
                $('#Cat_ID').data().select2.updateSelection(product_cat);
                $("#deal_title").val(main_response.deal_title);
                $("#deal_probability").val(main_response.deal_probability);
                $(".deal_attachments_div").html(response['attachments']);
            });
        });
        $("#submit_deal").on("click", function () {
            if (!$("#deal_form").valid())
                return;
            $("#deal_loader").removeClass('hidden');
            var Data = new FormData(document.getElementById("deal_form"));
            Data.append('current_stage_id',deal_stage);
            Data.append('organization_id',$('#deal_organization_id').val());
            Data.append('contact_id',$('#deal_contact_id').val());
            Data.append('deleted_attachments', JSON.stringify(deleted_attachments));
            $.ajax({
                url: "crmAjax/submitDeal",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            if(deal_origin == 'list' || $('#modal_deal_id').val() != '0'){
                                ChangeTable();
                            }else if(deal_origin == 'pipeline'){
                                getPipelineData()
                            }else if(deal_origin == 'profile'){
                                if($("#current_contact_id").val()){
                                    loadlog(deal_origin, $("#org_id").val(),$("#current_contact_id").val());
                                    getdeals('contact_id',$("#current_contact_id").val());
                                }else{
                                    loadlog(deal_origin, $("#org_id").val());
                                    getdeals('organization_id',$("#org_id").val());
                                }
                            }
                            hideModalAlert('deal_modal', 'deal_alert');
                        }
                        AddAlert("#deal_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#deal_loader").addClass('hidden');
                }
            });
        });
         $('.deal_attachments_div').on('click', '.delete_attachment', function () {
            deleted_attachments.push($(this).closest('.main_attachment_row').attr('data-attachment-name'));
            $(this).closest('.main_attachment_row').remove();
        });
    });
    function removeclassactive(){
        $(".stages label").each(function () {
            $(this).removeClass("active");
        });
    }
</script>
