<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT."init.php");

    
$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
include_once (PATH_TO_ROOT."CRM/_CRM_config.php");
include_once(PATH_TO_ROOT."CRM/class/class.Language-Pack.php");

$LangPack = new LanguagePack($db, $aLanguage);
$ajax = "CRM/_forms/nastavitve/_ajax/ajax.loanCredit.php";

$windowId = "loanCreditSettingsWindow";
$gridName = "loanCreditSettingsGrid";
?>
Ext.ns('Ext.ux.grid');
Ext.ux.grid.CheckColumn = Ext.extend(Ext.grid.Column, {
    processEvent : function(name, e, grid, rowIndex, colIndex){
        if (name == 'mousedown') {
            var record = grid.store.getAt(rowIndex);
            record.set(this.dataIndex, !record.data[this.dataIndex]);
            Ext.Ajax.request({
                url:'<?php echo $ajax;?>',
                params: { 
                    action: 'update',
                    id      : record.id,
                    field   : 'active',
                    oldValue: !record.data.active == true ? 0 : 1,
                    value   : record.data.active == true ? 1 : 0,
                    table   :'<?php echo WARPIT_CRM."._loanCreditsIntervals";?>'                 
                }                           
            })
            record.commit();
            return false; // Cancel row selection.
        } else {
            return Ext.grid.ActionColumn.superclass.processEvent.apply(this, arguments);
        }
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td'; 
        return String.format('<div class="x-grid3-check-col{0}">&#160;</div>', v ? '-on' : '');
    },

    init: Ext.emptyFn
});
Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn);
Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn;
Ext.grid.Column.types.checkcolumn = Ext.ux.grid.CheckColumn;

var <?php echo $gridName;?> = new Ext.grid.EditorGridPanel({
    id: '<?php echo $gridName;?>',
    store: new Ext.data.Store({
        url: '<?php echo $ajax;?>',
        baseParams:{
            action: 'getSettings'
        },
        reader: new Ext.data.JsonReader({       
                root:'rows',
                totalProperty : "results"
            },
            new Ext.data.Record.create([
                {name:'id', type:'id'},
                {name:'id_product', type: 'string'},
                {name:'dateFrom', type:'string'},
                {name:'dateTo', type:'string'},
                {name:'comment', type:'string'},
                {name:'active', type:'bool'}
            ])
        )
    }),
    colModel: new Ext.grid.ColumnModel({
       defaults:{
           width: 100,
           sortable: true
       },
       columns:[{
            header: '#ID',
            dataIndex: 'id',
            hidden: true  
       },{
            header: '<?php echo $LangPack->GetLabel("creditLoanSettings", "product_name_column_title","Produkt"); ?>',
            dataIndex: 'id_product',
            editor: 
            new Ext.form.ComboBox({ 
                mode: 'remote',
                triggerAction: 'all',
                editable: false,
                lazyRender: true,
                listeners:{
                    beforequery: function(qe){
                        delete qe.combo.lastQuery;
                    },
                    focus: function(combo){
                        if(combo.getValue() == 0 || combo.getValue == null)
                            combo.setValue('<?php echo $LangPack->GetLabel("CRM_all", "select_option_title","Izberite...");?>');
                    }
                },
                store: new Ext.data.JsonStore({
                    url : '<?php echo $ajax; ?>',
                    root : 'rows',
                    baseParams: {
                        action: 'getProducts'
                    },
                    fields:[
                         { name:"id", type: 'int' },
                         { name:"id_product", type: 'string' }
                    ]
                }),
                valueField: 'id',
                displayField: 'id_product'
            })
       },{
            header: '<?php echo $LangPack->GetLabel("creditLoanSettings", "date_from_column_title","Datum od"); ?>',
            dataIndex: 'dateFrom',
            editor: new Ext.form.DateField({ format: 'd.m.Y'})
       },{
            header: '<?php echo $LangPack->GetLabel("creditLoanSettings", "date_to_column_title","Datum do"); ?>',
            dataIndex: 'dateTo',
            editor: new Ext.form.DateField({ format: 'd.m.Y'})
       },{
            header: '<?php echo $LangPack->GetLabel("creditLoanSettings", "commnet_column_title","Komentar"); ?>',
            width: 200,
            dataIndex: 'comment',
            editor: new Ext.form.TextArea()
       },{
            header: '<?php echo $LangPack->GetLabel("creditLoanSettings", "active_column_title","Aktivni"); ?>',
            dataIndex: 'active',
            width: 50,
            xtype: 'checkcolumn'
       }]
    }),
    viewConfig:{
        forceFit: true
    },
    listeners: {
        afteredit : function(e) {
            var val = e.value;
            if(e.field == "dateFrom" || e.field == "dateTo"){
                val = e.value.format('d.m.Y');
            }
            Ext.Ajax.request({
                url:'<?php echo $ajax;?>',
                params: { 
                    action: 'update',
                    id      : e.record.id,
                    field   : e.field,
                    value   : val,
                    oldValue: e.originalValue,
                    table   :'<?php echo WARPIT_CRM."._loanCreditsIntervals";?>'                 
                },
                success : function(resp,opt){ 
                    e.grid.getStore().reload();
                }                                                       
            })
        }   
    },  
    sm: new Ext.grid.RowSelectionModel()
});

var <?php echo $windowId;?> = new Ext.Window({
    title: '<?php echo $LangPack->GetLabel("creditLoanSettings", "window_title","Nastavitve"); ?>',
    id      : '<?php echo $windowId;?>',
    width   : 500,
    height  : 600,
    plain   : true,
    layout  : 'fit',
    frame: true,
    modal: true,
    tbar:[{
       text: '<?php echo $LangPack->GetLabel("CRM_all", "CRM_add_button","Dodaj"); ?>',
       iconCls: 'icon-add-record',
       handler: function(){
           CallScript('CRM/_forms/nastavitve/tabs/window.loanCreditAddInterval.php', { gridName: '<?php echo $gridName;?>'});
       } 
    },'->',{
        text: '<?php echo $LangPack->GetLabel("CRM_all", "CRM_delete_button","Izbriši"); ?>',
        iconCls: 'icon-delete-record',
        handler: function(){
            var items = Ext.getCmp('<?php echo $gridName;?>').getSelectionModel().selections.items;
            if(items.length > 0){
                var data = items[0].data;
               Ext.Msg.confirm('<?php echo $LangPack->GetLabel("CRM_settings_panel", "CRM_delete_message_title","Brisanje"); ?>', '<?php echo $LangPack->GetLabel("CRM_settings_panel", "CRM_delete_message_msg","Ali res želite izbrisati ta predment?"); ?> ('+data.id_product+' ('+data.dateFrom+' - '+ data.dateTo+ '))', function(btn){
                   if(btn == "yes"){
                        Ext.Ajax.request({
                            url:'<?php echo $ajax;?>',
                            params: { 
                                action: 'deleteInterval',
                                id      : data.id                 
                            },
                            success : function(resp,opt){ 
                                Ext.getCmp('<?php echo $gridName;?>').getStore().reload();
                            }                                                       
                        })
                   }
               });
            }
        }
    }],
    items:[<?php echo $gridName;?>],
    listeners: {
        afterRender: function(grid){
            var X = (screen.width/2) - ((Ext.getCmp('<?php echo $windowId;?>').getSize().width)/2);
            var Y = (screen.height/2) - ((Ext.getCmp('<?php echo $windowId;?>').getSize().height)/2);
            Ext.getCmp('<?php echo $windowId;?>').setPosition(X, Y);
            Ext.getCmp('<?php echo $gridName;?>').getStore().load();
        },
        beforeClose: function(window){
            Ext.getCmp('<?php echo $_POST['name'];?>').getStore().reload();
        }
    }
}).show();