<link href="<?php echo Yii::app()->baseUrl; ?>/css/bootstrap.css" rel="stylesheet">
<div class="main_content">
<div class="innercontent_outerbox">
  <h1>Earn Points - Product </h1>
  <h4> <?php echo CHtml::link("Earn Points by Product", Yii::app()->createUrl('site/earnpoints')); ?> </a> | 
            <?php echo CHtml::link("Earn Points by Certification", Yii::app()->createUrl('site/earncertificationpoints')); ?> </h4>
  <div class="row">
    <div class="span8">
          <?php $form=$this->beginWidget('CActiveForm', array(
			'id'=>'reward-form',
			'enableAjaxValidation'=>false,
			'htmlOptions' => array('enctype' => 'multipart/form-data'),
		)); 
          $modelproducts = array(new RewardProducts());?>
        <?php //echo $form->errorSummary($model); ?>
        <?php
    foreach(Yii::app()->user->getFlashes() as $key => $message) {
        echo '<div class="flash-' . $key . '">' . $message . "</div>\n";
    }
    ?>
        <table width="100%" border="1" cellspacing="0" cellpadding="10" id="tbl_product" class="table table-fixed table-primary">
                <tr>
                    <th>Product </th>`
                    <th>Product Serial No</th>
                    <th><button class="btn" type="button" onclick="addTableRow($('#tbl_product'));">+</button></th>
                </tr>
              <tr>
                
                <td width="30%">
                    <?php echo $form->dropDownList($modelproducts,'product_id',Product::getPromotioanlProducts(),array('prompt'=>'--Select--')); ?>
                </td>
                <td width="40%">
                    <?php echo $form->textField($modelproducts,'serial_no',array('size'=>20,'maxlength'=>255,'onclick'=>'addRow()','placeholder'=>'Product Serial No:')); ?>
                </td>
                <td class="text-center">
                  <?php echo CHtml::link('<i class="fa fa-trash"></i>', 'javascript:void(0);', array('id'=>"jobtable",'onclick' => 'removeJobTable($(\'#tab_owner_details\'),this,this.id)', 'title' => 'Remove this item','class'=>'btn-span'));?>
                </td>
              </tr>
            </table>
            <table width="100%" border="0" cellspacing="0" cellpadding="10">
              <tr>
                <td><?php echo $form->labelEx($model,'end_customer_name'); ?></td>
                <td><?php echo $form->textField($model,'end_customer_name',array('size'=>20,'maxlength'=>255,'placeholder'=>'Customer name:')); ?><?php echo $form->error($model,'end_customer_name'); ?></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td><?php echo $form->labelEx($model,'date_of_purchase',array('label'=>'Date of purchase')); ?></td>
                <td><?php
				  $this->widget('zii.widgets.jui.CJuiDatePicker', array(
	 'model'=>$model,
     'attribute'=>"date_of_purchase", // the name of the field
     'options'=>array(
            'dateFormat'=>'yy-mm-dd',
            'showAnim'=>'fold',
            'showButtonPanel'=>false,
            'yearRange'=>'1900',
     'debug'=>true,

    ),
     'htmlOptions'=>array(
     'style'=>'height:20px;'
     ),
     ));
				  ?>
                  <?php echo $form->error($model,'date_of_purchase'); ?></td>
                <td>&nbsp;</td>
              </tr>
              <tr>
                <td><?php echo $form->labelEx($model,'invoice_number'); ?></td>
                <td><?php echo $form->textField($model,'invoice_number',array('size'=>20,'maxlength'=>255,'placeholder'=>'Invoice number:')); ?>
                <?php echo $form->error($model,'invoice_number'); ?></td>
                <td></td>
              </tr>
              <tr>
                <td><?php echo $form->labelEx($model,'invoice'); ?></td>
                <td><?php echo $form->fileField($model,'invoice'); ?>
                <?php echo $form->error($model,'invoice'); ?>
                  <span style="color:#999;">Upload photo/Scanned image of invoice</span></td>
                <td></td>
              </tr>
              <tr>
                <td><?php echo $form->checkBox($model,'agreement',array('value'=>null, 'checkValue'=>'1')); ?>
                <?php echo $form->labelEx($model,'agreement'); ?>
                <?php echo $form->error($model,'agreement'); ?>
                </td>
              </tr>
              <tr>
                <td><?php echo CHtml::submitButton('Submit'); ?></td>
              </tr>
            </table>
          <?php $this->endWidget(); ?>
        </div>
  </div>
</div>
<?php
$cs = Yii::app()->getClientScript();
$cs->registerScript('addRow','function addRow() {			
    var product_id = $("#Reward_product_id").val();
    var serial_no  = $("#Reward_serial_number_of_product").val();
    if(product_id!="" && serial_no!=""){
        jQuery.ajax({
            "dataType":"json",
            "type"  : "post",
            "data"  : "serial_no=" +serial_no+"&product_id="+product_id,
            "url" : "'.Yii::app()->createUrl("site/checkSerialNo").'",
            "cache": false,
            "success":function(data){
            if(data.status=="success")
            {
                
            }else{
               $("#Reward_serial_number_of_product").val("");
               alert("Serial no already used");
            }
        }
    });
    }else{
        alert("Please select a Product and enter Serial No");
    }
}',CClientScript::POS_END);
$cs->registerScript("addTableRow", "
            function addTableRow(jQtable) {
                var newrow= jQtable.find('tr:last').clone();
                var lastId = jQtable.find('tr:last td:gt(0) input').attr('id');
                var thenum = lastId.match(/\d+/g);
                var newId = Number(thenum) + 1;
                var newrow= jQtable.find('tr:last').clone();
                newrow.find('label').html(newId+1);
               
                newrow.find('a,select,label,input,textarea,hidden,.errorMessage').each(function() {
                    this.id= this.id.replace(/\d+/,newId);
                    this.value  = '';
                    (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   'display:none;';
                });
                jQtable.append(newrow);
                //var id='BuildingOwnerDetails_'+newId+'_landlord';
                //var oldId=newId-1;
               // var field='BuildingOwnerDetails_'+oldId+'_landlord';
                var select=document.getElementById(''+id+'');
                var value = $('#'+field+'').val();
                for (i=0;i<select.length;  i++) {
                   if (select.options[i].value==value) {
                     select.remove(i);
                   }
                }
        }", CClientScript::POS_HEAD);
        $cs->registerScript("addChequeTableRow", "
            function addChequeTableRow(jQtable) {
                var newrow= jQtable.find('tr:last').clone();
                var lastId = jQtable.find('tr:last td:gt(0) input').attr('id');
                var thenum = lastId.match(/\d+/g);
                var newId = Number(thenum) + 1;
                var newrow= jQtable.find('tr:last').clone();
                newrow.find('label').html(newId+1);
                newrow.find('a,select,label,input,textarea,hidden,.errorMessage').each(function() {
                    this.id= this.id.replace(/\d+/,newId);
                    this.value  = '';
                    (this.name!==undefined) ? this.name= this.name.replace(/\d+/,newId) : this.style  =   'display:none;';
                });
                jQtable.append(newrow);
                $('#cheque_date_'+newId).datepicker({dateFormat: 'dd/mm/yyyy',language:'en'});
                var oldId           = newId-1;
                var cheque_date             = 'cheque_date_'+newId;
                var old_cheque_date_field   = 'cheque_date_'+oldId;
                var old_cheque_date         = $('#'+old_cheque_date_field+'').val();
                if(old_cheque_date ==''){
                    var today = new Date();
                    var dd = today.getDate();
                    var mm = today.getMonth()+1; //January is 0!
                    var yyyy = today.getFullYear();
                    if(dd<10){
                        dd='0'+dd
                    }
                    if(mm<10){
                        mm='0'+mm
                    }
                    old_cheque_date = dd+'/'+mm+'/'+yyyy;
                }
                arr_date                    = old_cheque_date.split('/');
                n_date                      = arr_date[1] + '/' + arr_date[0] + '/' +arr_date[2];
                var d                       = new Date( n_date );
                d.setMonth( d.getMonth( ) + 1 );
                    var dday = d.getDate();
                    var dm   = d.getMonth()+1; //January is 0!
                    if(dday < 10){
                        dday = '0'+ dday;
                    }
                    if(dm < 10){
                        dm = '0'+ dm;
                    }
                    mdate = dday+'/'+dm+'/'+d.getFullYear( );
                    //mdate    = d.getDate( ) + '/' + (d.getMonth( )+ 1 ) + '/' + d.getFullYear( );
                $('#'+cheque_date+'').val(mdate);
                var checkno_id              = 'cheque_no_'+newId;
                var old_checkno_field       = 'cheque_no_'+oldId;
                var old_checkno             = $('#'+old_checkno_field+'').val();
                var new_checkno             = Number(old_checkno)+1;
                $('#'+checkno_id+'').val(new_checkno);
                var amount          = 'amount_'+newId;
                var old_amount_field= 'amount_'+oldId;
                var old_amount      = $('#'+old_amount_field+'').val();
                $('#'+amount+'').val(old_amount);
                var bank            = 'bank_name_'+newId;
                var old_bank_field  = 'bank_name_'+oldId;
                var old_bank        = $('#'+old_bank_field+'').val();
                $('#'+bank+'').val(old_bank);
            }", CClientScript::POS_HEAD);
            $cs->registerScript("isRowEmpty", " function isRowEmpty(tr) {
                    var rowfilled=false; tr.find('td:gt(0)').each(function()
                    {
                        inpt    =   $(this).find('input').val();
                        if(typeof inpt !== 'undefined' && inpt!=='' && inpt!=='0.00') {
                            rowfilled=true; return false;
                        }
                    });
                    if(rowfilled) {
                        /*jConfirm('Do you want to remove this item?', 'Confirm', function(r) {
                        alert(r);
                            if(r==true)
                                return true;
                            else
                                return false;
                        });
                        */
                        return(confirm('Do you want to remove this item?'));
                    }
                    return true;
            } ", CClientScript::POS_HEAD);
            $cs->registerScript("removeRow", "function removeRow(jQtable,evt,field_id) {
                var arr_fields= field_id.split('_');
                var row_field=arr_fields[1];
                var num_rows    =   jQtable.find('tr:gt(0)').length;
                if(num_rows>1){
                    var tr  =   $(evt).parent().parent();
                    if(isRowEmpty(tr))
                    {
                        $(evt).parents('tr').remove();
                        var i=0;
                        jQtable.find('tr:gt(0)').each(function() {
                            $(this).find('input,textarea,.errorMessage').each(function()
                            {
                                old_id   =   $(this).attr('id');
                                new_id   =   old_id.replace(/\d+/,i);
                                $(this).attr('id',new_id);
                                old_name =   $(this).attr('name');
                                if(old_name!==undefined) {
                                    new_name =   old_name.replace(/\d+/,i);
                                    $(this).attr('name',new_name);
                                }
                            });
                            $(this).find('td:first label').html(++i);
                        });
                    }
                }else {
                        jAlert('Only one row remaining','Alert');
                }
            };", CClientScript::POS_HEAD);
            $cs->registerScript("removeTableRow", "function removeTableRow(jQtable,evt,field_id) {
                var arr_fields= field_id.split('_');
                var row_field=arr_fields[1];
                //var id=$('#JobCard_'+row_field+'_id').val();
                // formIdStarter   =   jQtable.attr('id').split(/_(.+)?/)[0];
                var num_rows    =   jQtable.find('tr:gt(0)').length;
                if(num_rows>1){
                    var tr  =   $(evt).parent().parent();
                    if(isRowEmpty(tr))
                    {
                        if(id!='')
                        {
                              /*  jQuery.ajax({
                                        'type': 'post',
                                        'dataType': 'json',
                                        'url': '" . Yii::app()->createUrl('appointment/deleteservice') . "',
                                        'data': {'id':id}  ,
                                        'cache': false,
                                        'success': function(data) {
                                            if(data.status=='success'){
                                                $(evt).parents('tr').remove();
                                                var i=0;
                                                jQtable.find('tr:gt(0)').each(function() { $(this).find('input,textarea,.errorMessage').each(function()
                                                {
                                                old_id   =   $(this).attr('id');
                                                new_id   =   old_id.replace(/\d+/,i);
                                                $(this).attr('id',new_id);
                                                old_name =   $(this).attr('name');
                                                if(old_name!==undefined) {
                                                new_name =   old_name.replace(/\d+/,i);
                                                $(this).attr('name',new_name);} });
                                                $(this).find('td:first label').html(++i); });
                                                 notification('Sevice Deleted','success');
                                                 $.pnotify_remove_all();
                                            }else{
                                              notification('Deletion Not Possible, History Exist','error');
                                              $.pnotify_remove_all();
                                            }
                                        }
                                });*/
                        }
                        else
                        {
                                $(evt).parents('tr').remove();
                                var i=0;
                                jQtable.find('tr:gt(0)').each(function() {
                                    $(this).find('input,textarea,.errorMessage').each(function()
                                    {
                                        old_id   =   $(this).attr('id');
                                        new_id   =   old_id.replace(/\d+/,i);
                                        $(this).attr('id',new_id);
                                        old_name =   $(this).attr('name');
                                        if(old_name!==undefined) {
                                            new_name =   old_name.replace(/\d+/,i);
                                            $(this).attr('name',new_name);
                                        }
                                    });
                                    $(this).find('td:first label').html(++i);
                                });
                        }
                        var total_amount=0;
                        var rowCount = $('#customer_jobcard_details tr').length;
                        rowCount = parseInt(rowCount)-parseInt(2);
                        fieldId=rowCount;
                        for(i=0;i<=fieldId;i++){
                            var amount= $('#JobCard_'+i+'_cost').val();
                                if(amount != ''){
                                    total_amount+=parseFloat(amount,10);
                                }
                        }
                        $('#total').val(Math.ceil(total_amount));
                    }else {
                        jAlert('Atleast one item needed here','Alert');
                    }
                }
            };", CClientScript::POS_HEAD);?>