<?php $stt_days_limit=dbCol('dflt_ist_days_limit','settings','id=1');
$tree=$this->aqsam_model->GetCats(0);
$cat_tree=$this->aqsam_model->cat_tree($tree);
$cats = array_values($cat_tree);
$cats = array_values($cat_tree);

?>

<script>
Vue.prototype.$http = axios

</script>
<script>


var app = new Vue({
  data: {
	  table_setts: [],
      return_book: {
		  user_name:'<?=login("full_name_or_name")?>',
		  user_id:'<?=login("id")?>',
		  id:'',
		  book_id:'',
		  return_date: '<?=date("Y-m-d")?>',	 
	  },
	  

      users: <?=json_encode(dbRows('id,full_name as name','users'))?>,
      book: {
		  id:'',title:'',taba_no:'',sana_taba:'',muallif_name:'',muhaqqiq_name:'',qism_name:'',nashir_name:'',mujalladat:'',ser_bai:'',lang:'',ser_shira:'',tadad:'',
		 
	  },
		book_istiarat: [],
	  member: {
		  id:'',name:'',contact_no:'',email:'',adrs:'',
		 
	  },
		member_istiarat: [],
		member_reports: [],
		search_members: [],

    fltrs: {
		search: {
			q:"",
			in:"all",
			name:"<?=lang('all')?>",
		},
		aqsam: {
			rows:<?=json_encode($cats)?>,
			ids:[],
		},sorts: [
			{"col":"id","type":"z2a"},
			]
		,page: 1
	},
	
	ist_fltrs: {
		search: {
			q:"",
			in:"title",
			name:"<?=lang('book_name')?>",
		}
		,return_options: {
			rows:[
			{"opt":"<?=lang('books_not_retrnd')?>","val":0},
			{"opt":"<?=lang('books_retrnd')?>","val":1},
			],
			codes:[0],
		},sorts: [
			{"col":"id","type":"z2a"},
			]
		,days_left: {
			from:0,
			to:30
		,
		}
		,page: 1
	},members_fltrs: {
		search: {
			q:"",
			
		},
		page: 1
	},cart: {
		date: '<?=date("Y-m-d")?>',
		inserted_fatoora_id: '',
		total_qntty:0,
      items: [],
      member: [],
      allTotal: [],
      all_ribh: [],
      payd:false,
    },fatoora: {
      id: '',date: '',total:0,ribh:0,khasara:0,total_items:0,total_qntty:0,
      items: [],
      user: {id:'<?=login('id')?>',name:'<?=login('full_name_or_name')?>'},
      member: [],
      allTotal: [],
      all_ribh: [],
      payd:false,
    },

    cart_date_qry: Date.now().to_date_js,
    mabeeat_date_qry: '',
    mabeeat_fatoora_id_qry: '',
    cart_member_qry: '',
	cart_members_list: [],
	new_member_name: '',
	new_member_contact_no: '',
	new_member_email: '',
	new_member_adrs: '',
    search_books: '',

    khasm_ser:'',
    changeDaysNum:'',
    book_name_qry: '',
    table_fltr: '',
    table_fltr_type: '',
    table_text: '',
    table_limit: '',
    table_sort: '',
    table_page: '',
    table_sort_type: '',
    dbNumRet: '',
    cart_drafts: '',


	
    search_ist_books: '',
    search_ist_books_qry: '',
   	
 

	col:{
		isbn:0,
		book_number:0,
		des:0,
		note:1,
		muallif_name:1,
		muhaqqiq_name:1,
		qism_name:0,
		nashir_name:1,
		lang:1,
		taba_no:1,
		sana_taba:0,
		mujallad:1,
		shelf_no:0,
		raff_no:0,	
		book_stts:0,
		heading : "<?=lang('books_list')?>",
		top_text : " ",
		bottom_text : "",
		fltrs: [],
		sett: {
			"table_name": "books",
			"title": "<?=lang('table_sett_title')?>",
		}
	},

	},components: {
    Pagination
  },
  mounted: function () {
	this.get_table_setts();
	  
    this.search_book();
    this.search_ist_book();
    this.get_members();
	
	

	

  

  },
  
  computed: {
    
    cart_member_name_qry: function () {

	  this.$http.get('<?=site_url()?>/ajax/cart/add_member/?name=' + app.new_member_name + '&contact_no=' + app.new_member_contact_no, {})
        .then(function (response) {
			app.cart.member = response.data;
          console.log(response.data);


        })
        .catch(function (error) {
          console.log(error);
        });
	
    }
  },
  methods: {
sortBooks: function (col) {
	var type;
	if(type==null){type='a2z'}
	is_col=_.filter(this.fltrs.sorts,{'col':col});
	is_a2z=_.filter(this.fltrs.sorts,{'col':col,'type':'a2z'});
	this.fltrs.sorts=_.pullAllBy(this.fltrs.sorts, [{ 'col': col }], 'col');
	
	if(is_col.length>0){
		if (is_a2z.length>0){
			type='z2a';
		}else{
		type='a2z';
	}
		
	}
	


	this.fltrs.sorts.unshift({"col":col,"type":type});
	this.search_book();
	
},
save_table_sett: function () {
	var json = {
			col:this.col,
			fltrs:this.fltrs,
		}
	
		$.ajax({
        url: '<?=site_url()?>/ajax/books/save_table_sett/',
        type: 'post',
        data: {
          json: JSON.stringify(json)

        }
      }).done(function(val) {         
		app.get_table_setts();
		   UIkit.notification({message: '<?=lang('data_saved')?>', status: 'success', pos: 'top-center', timeout: 1000});
      })
		console.log(this.col);
		
    },
    get_table_setts: function () {
      this.$http.get("<?=site_url()?>/ajax/db/rows?select=*&from=table_sett&where=table_name='books'&orderby=id DESC ", {})
        .then(function (response) {
          app.table_setts = response.data;
		  
		   _.forEach(app.table_setts,function (o){
				if(o.dflt==1){
					app.to_crrnt_table_sett(o.json);
				}
			});
			
			app.search_book();
		  
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    set_dflt_table_sett: function (id,json) {
    app.to_crrnt_table_sett(json);

      this.$http.get('<?=site_url()?>/ajax/table_sett/set_dflt/?id=' + id, {})
        .then(function (response) {
		app.get_table_setts();
        })
        .catch(function (error) {
          console.log(error);
        });
    },del_table_sett: function (id, index) {
      this.table_setts.splice(index, 1)

      this.$http.get('<?=site_url()?>/ajax/db/del?from=table_sett&where=id=' + id, {})
        .then(function (response) {
		app.get_table_setts();
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    to_crrnt_table_sett: function (json) {
      json = $.parseJSON(json);
	   this.col =json.col;
	   this.fltrs =json.fltrs;
	   this.search_book();
    },
    bookInfo: function (b) {
		      this.book=b;
			  this.bookIstiarat(b.id)
    },
    bookIstiarat: function (id) {
		
		this.$http.get("<?=site_url()?>/ajax/reports/book_istiarat?id="+id, {})
        .then(function (response) {
          app.book_istiarat =  response.data;
          console.log(app.book_istiarat);
        })
        .catch(function (error) {
          console.log(error);
        });
      
    },
    memberModelUpd: function (id) {
		this.memberInfo(id)
		this.memberIstiarat(id)
		this.memberReports(id)
	},
    memberInfo: function (id) {
		    this.$http.get("<?=site_url()?>/ajax/members/get_member/"+id, {})
        .then(function (response) {
          app.member =  response.data;
          console.log(app.member);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    memberIstiarat: function (id) {
		
		this.$http.get("<?=site_url()?>/ajax/reports/member_istiarat?id="+id, {})
        .then(function (response) {
          app.member_istiarat =  response.data;
          console.log(app.member_istiarat);
        })
        .catch(function (error) {
          console.log(error);
        });
      
    },
    memberReports: function (id) {
		
		this.$http.get("<?=site_url()?>/ajax/reports/member_reports?id="+id, {})
        .then(function (response) {
          app.member_reports =  response.data;
          console.log(app.member_reports);
        })
        .catch(function (error) {
          console.log(error);
        });
      
    },returnBookDropDown: function (ist) {

	  this.return_book.id=ist.id;
	  this.return_book.book_id=ist.book_id;
	  console.log(this.return_book);
    },
    
     returnBook: function (book) {
		 	 book.return_date=this.return_book.return_date;
return_url='<?=site_url()?>/ajax/istiara/return_book/?user_id='+this.return_book.user_id+'&json=' + JSON.stringify(book);
console.log(return_url);
      this.$http.get(return_url, {})
        .then(function (response) {
			book.returnd=1;
			book.return_user_name=app.return_book.user_name;
              UIkit.notification({message: '<?=lang('data_saved')?>', status: 'success', pos: 'top-center', timeout: 1000});
			app.search_book();
      })
        .catch(function (error) {
          console.log(error);
        });
    },    
	DeleteIst: function (book) {
		
		
var r = confirm("<?=lang('is_del')?>");
if (r == true) {
		del_ist_url = '<?=site_url()?>/ajax/istiara/delete_ist/?id=' + book.id;
      this.$http.get(del_ist_url, {})
        .then(function (response) {

              UIkit.notification({message: '<?=lang('data_deleted')?>', status: 'success', pos: 'top-center', timeout: 1000});
			app.search_book();
			app.search_ist_book();
          console.log("del:"+del_ist_url);
      })
        .catch(function (error) {
          console.log(error);
        });

    
}    },
    ReturndBook: function (ist) {
		
		this.$http.get("<?=site_url()?>/ajax/reports/book_mabeat?id="+ist.id+
		'&json='+JSON.stringify(ist), {})
        .then(function (response) {

        })
        .catch(function (error) {
          console.log(error);
        });


    },addToCart: function (i) {

      app.cart.items.push({
        id: i.id,
        title: i.title,
        nashir_name: i.nashir_name,
        muallif_name: i.muallif_name,
        mujallad: i.mujallad,
        days_limit: <?=$stt_days_limit?>,
      });

    },
    print: function (elem) {

window.print();
	},
    
	attr: function (el,attr,val) {
		$(el).attr( attr, val );
	},
	  getTotal: function (rows,coll_to_total) {
      var tot = 0;
      for (var idx in rows) {
        var currentItem = rows[idx];
        tot += parseFloat(currentItem[coll_to_total]);
      }
      return tot;
    },today: function () {
     return   moment().format('DD/MM/YYYY')
     
    },this_mnth: function () {
     return   '<?=date("01/m/Y")?>';
     
    },selectCartDate: function () {
		
     this.cart.date=moment(this.cart_date_qry,'YYYY-MM-DD').unix()  * 1000;
	 console.log(this.cart.date)
    
     
    }
	
	,
	
	changeAddMasareefDate: function () {
		
     this.add_masareef_date=moment(this.add_masareef_date_qry,'YYYY-MM-DD').unix()  * 1000;
	 console.log(this.add_masareef_date)
    
     
    },mabeeatDayDate: function () {
		
     this.mabeeat.start_date=moment(this.mabeeat_date_qry,'YYYY-MM-DD').format('DD/MM/YYYY')
     end_date_unix=moment(this.mabeeat.start_date,'DD/MM/YYYY').add(1, 'day');
	 this.mabeeat.end_date=moment(end_date_unix).format('DD/MM/YYYY')
	 this.mabeeat.page_title='تقرير مخصص';
	 this.mabeeat.fatoora_id=''
	 
	 this.item_mabeeat.start_date=this.mabeeat.start_date
     end_date_unix=moment(this.mabeeat.start_date,'DD/MM/YYYY').add(1, 'day');
	 this.item_mabeeat.end_date=this.mabeeat.end_date
	 this.item_mabeeat.page_title='تقرير مخصص للمواد';
	 this.item_mabeeat.fatoora_id=''
     
    },mabeeatFatooraNo: function () {
		
     this.mabeeat.fatoora_id=this.mabeeat_fatoora_id_qry
	 this.mabeeat.page_title="بحث برقم الفاتورة";
	 
     
    },
   
    percent: function (num_amount,num_total) {

var count1 = num_amount / num_total;
var count2 = count1 * 100;
  return count2.toFixed(2);
          },khasm_percent: function (num_amount,num_total) {

var count1 = num_amount / num_total;
var count2 = (count1 * 100)-100;
var result =  count2.toFixed(2);
result = Math.abs(result);
return result;
          },
    
    isAdedToCart: function (id) {
      var matches = 0;
      for (var idx in this.cart.items) {
        var currentItem = this.cart.items[idx];
        if (currentItem.id == id) {
          matches++
        }
      }
      if (matches == 0) {
        return true;
      } else {
        return false;
      }
    },isAdedToiCart: function (id) {
      var matches = 0;
      for (var idx in this.icart.items) {
        var currentItem = this.icart.items[idx];
        if (currentItem.id == id) {
          matches++
        }
      }
      if (matches == 0) {
        return true;
      } else {
        return false;
      }
    },

    delFromCart: function (id, index) {
      this.cart.items.splice(index, 1)

    },

    changeDays: function (i) {

      if (this.changeDaysNum < 5+1) {
        i.qntty=this.changeDaysNum;
      } else {
              UIkit.notification({message: "الحد الأقصى للكمية لهذا الكتاب: " + 5 , 
      status: 'danger', pos: 'top-center', 
      timeout: 3000});
      }
    },

    addOneDay: function (i) {
		
		i.days_limit++
		
    },
    removeOneDay: function (i) {

      if (i.days_limit >= 2) {
        i.days_limit--;
      }
    },
khasm: function (i) {

      if (this.khasm_ser >= i.ser_shira) {
        i.ser_akheer=this.khasm_ser;
        i.ribh=i.ser_akheer - i.ser_shira
      }else{
         UIkit.notification({message: "لا يمكن تخفيض السعر أقل من:  " + i.ser_shira , 
      status: 'danger', pos: 'top-center', 
      timeout: 3000});
      }
    },

    getVal: function (id) {
      var value = $('#' + id).val();
      console.log(value);
      return value;
    },


    booksPaging: function (pageNum) {
		this.fltrs.page=pageNum;
      this.search_book(this.table_fltr, this.table_text, 'id', 'z2a', pageNum)
    },
	istBooksPaging: function (pageNum) {
		this.ist_fltrs.page=pageNum;
      this.search_ist_book(this.table_fltr, this.table_text, 'id', 'z2a', pageNum)
    },
	membersPaging: function (pageNum) {
		this.members_fltrs.page=pageNum;
      this.get_members();
    },
    add_cart_member: function () {
      if(this.new_member_name==""){
		  alert("Pleas Enter Member name")
	  }else{
		  this.$http.get('<?=site_url()?>/ajax/cart/add_member/?name=' + app.new_member_name + '&contact_no=' + app.new_member_contact_no+ '&email=' + app.new_member_email+ '&adrs=' + app.new_member_adrs, {})
        .then(function (response) {
			if(response.data.ok){
			app.cart.member = response.data.member;
			console.log(response.data);

		   UIkit.dropdown("#cart_select_member").hide();
		}else{
			 UIkit.notification({message: 'حدث خطأ:<br>'+response.data.msg, 
			  status: 'danger', pos: 'top-center', 
			  timeout: 3000});
		}
        })
        .catch(function (error) {
          console.log(error);
        });
	  }
	  
    },

    search_book: function () {
     
		$('.loading_search_aya').css('display', 'block');

      this.$http.get('<?=site_url()?>/ajax/books?q=' + this.fltrs.search.q + '&in=' + this.fltrs.search.in +
	  '&aqsam=' + JSON.stringify(this.fltrs.aqsam.ids) +  '&sorts=' + JSON.stringify(this.fltrs.sorts) + '&page=' + this.fltrs.page, {})
        .then(function (response) {
          
		$('.loading_search_aya').css('display', 'none');

                   app.search_books = response.data;

          console.log('<?=site_url()?>/ajax/books?q=' + app.fltrs.search.q + '&in=' + app.fltrs.search.in +  '&aqsam=' + JSON.stringify(app.fltrs.aqsam.ids) +'&sorts=' + JSON.stringify(app.fltrs.sorts) + '&page=' + app.fltrs.page);
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    search_ist_book: function () {
		console.log(3333);
     
$('.loading_search_aya').css('display', 'block');

url='<?=site_url()?>/ajax/istiara?q=' + this.ist_fltrs.search.q + 
'&in=' + this.ist_fltrs.search.in + 
'&return_options=' + JSON.stringify(this.ist_fltrs.return_options.codes) + 
'&days_left_from=' + this.ist_fltrs.days_left.from + '&days_left_to=' + this.ist_fltrs.days_left.to+'&sorts=' + JSON.stringify(this.ist_fltrs.sorts) + 
'&page=' + this.ist_fltrs.page;
console.log(url);
      this.$http.get(url, {})
        .then(function (response) {
          
	$('.loading_search_aya').css('display', 'none');

     app.search_ist_books = response.data;

          console.log(url);
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    get_members: function () {
     
$('.loading_search_aya').css('display', 'block');

url='<?=site_url()?>/ajax/members?q=' + this.members_fltrs.search.q  + 
'&page=' + this.members_fltrs.page;
      this.$http.get(url, {})
        .then(function (response) {
          
		$('.loading_search_aya').css('display', 'none');

     app.search_members = response.data;

          console.log(url);
        })
        .catch(function (error) {
          console.log(error);
        });
    }, cart_members_listing: function  () {
     

      this.$http.get('<?=site_url()?>/ajax/members/list_members/?q='+ this.cart_member_qry, {})
        .then(function (response) {
         
          app.cart_members_list = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    search_ist_books: function (fltr = '', text = '', sort = '', sort_type = '', page = 1) {
      if (this.search_ist_books_qry != '') {
        text = this.search_ist_books_qry
      }
      if (fltr == null) {
        fltr = this.table_fltr;
      }
      if (sort == null) {
        sort = app.table_sort;
      }
      if (sort_type == null) {
        sort_type = app.table_sort_type;
      }
      if (page == null) {
        page = app.table_page;
      }

      this.$http.get('<?=site_url()?>/ajax/items?fltr=' + fltr + '&sort=' + sort + '&sort_type=' + sort_type + '&text=' + text + '&page=' + page, {})
        .then(function (response) {
          app.table_fltr = fltr;
          app.table_text = text;
          app.table_sort = sort;
          console.log(response.data);
			
          app.search_ist_books = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    
    
    search_member: function () {
      this.$http.get('<?=site_url()?>/ajax/cart/search_member/?cart_member_name=' + this.cart_member_name_qry, {})
        .then(function (response) {
          app.cart.member = response.data;
          console.log(response.data)

        })
        .catch(function (error) {
          console.log(error);
        });
    },search_member_contact: function () {
      this.$http.get('<?=site_url()?>/ajax/cart/search_member/?cart_member_contact_no=' + this.cart_member_contact_no_qry, {})
        .then(function (response) {
          app.cart.member = response.data;
          console.log(response.data)

        })
        .catch(function (error) {
          console.log(error);
        });
    },select_member: function (m) {
   app.cart.member = m;
   UIkit.dropdown("#cart_select_member").hide();

  },select_user: function (m) {
   app.fatoora.user = m;
   UIkit.dropdown("#cart_select_user").hide();

  },
    cartFinel: function (cart) {
		cart_list= this.cart
		cart_list= _.omit(cart_list, ['items', 'inserted_fatoora_id','member']);

		cart_items = this.cart.items;
	//	cart_items = _.map(cart_items, function(item){ return _.pick(item,['id', 'days_limit'])});
		
		cart_user= this.fatoora.user
		cart_user= _.pick(cart_user, 'id');
		cart_member= this.cart.member
		cart_member= _.pick(cart_member, 'id');
		
		
	
		cart_finel=cart_list;
		cart_finel['items']= cart_items
		cart_finel['member'] =cart_member;
		cart_finel['user'] =cart_user;
		
		console.log(cart_finel);
				$.ajax({
        url: '<?=site_url()?>/ajax/cart/save_finel/',
        type: 'post',
        data: {
          json:JSON.stringify(cart_finel)

        }
      }).done(function(val) {
		   app.cart.inserted_fatoora_id=val.inserted_fatoora_id
          app.cart.payd=true;
		  app.search_book();
           app.search_ist_book();
              UIkit.notification({message: '<?=lang('data_saved')?>', status: 'success', pos: 'top-center', timeout: 2000});
      }).error(function(error) {
		  console.log(error);
      })
		
		

		
		
    },

    cartClear: function () {
     
      this.cart= {
		date: '<?=date("Y-m-d")?>',
		inserted_fatoora_id: '',
		total_qntty:0,
      items: [],
      member: [],
     
      payd:false,
    }
	    this.search_book(this.table_fltr, '','id','z2a');

    }

  }


}).$mount('#app');
//


</script>
    <script>
       $('document').ready(function() {
       var allroutes = function() {
        var route = window.location.hash.slice(2);
        var sections = $('section');
        var section;

        section = sections.filter('[data-route=' + route + ']');

        if (section.length) {
          sections.hide();
          section.show();
        }
      };  
	  
      var Home = function () { };
      var showIstiara = function () { console.log("showIstiara"); };
      var showMembers = function () { console.log("showMembers"); };
      var showBookCart = function () { console.log("showBookCart"); };
      var showShopCart = function () { console.log("showShopCart"); };
      var showMabeeat = function () {
      app.list_fawateer();
      app.list_item_fawateer();
	  
      };
	  
	  var showFatoora = function (fid) {
		var route = window.location.hash.slice(2);
		app.fatoora.id=fid;
console.log("rout: "+route+"showFatoora: "+fid);	  
      };
      var showBook = function (id) { console.log("showBook"+id); };



     
      var routes = {
        '/': Home,
        '/members': showMembers,
        '/mabeeat': showMabeeat,
        '/book_cart': showBookCart,
        '/istiara': showIstiara,
        '/shop_cart': showShopCart,
        '/fatoora:fid': showFatoora
      };

     
      var router = Router(routes);

      //
      // a global configuration setting.
      //
      router.configure({
        on: allroutes
      });

      router.init(['/']);
    });
	

//UIkit.modal("#cartModal").show();
UIkit.sticky(".paging");

function remove(array, elements) {
	for (var i in elements){
    const index = array.indexOf(elements[i]);
    array.splice(index, 1);		
	
	}
return array;
}

 
 
 
  $('button[uk-close]>svg').remove();
 $('*[uk-search-icon]>svg:nth-child(2)').remove();
 $('*[uk-icon]>svg:nth-child(2)').remove();
 $('*[uk-close]>svg:nth-child(2)').remove();

    </script>
	
	<?php // ECHO  VAR_DUMP($_COOKIE["json"]);
?>