<?php 

define("TABLEID", 'tblAppendGrid');

class interestModel
{
    private $db;
    public $ask;
    public $reply;
    public $positions;
    public $result;
    public $numbers;
    public $i;
    public $sdate;
    public $edate;
    public $amount;
    public $total;
    public $ids;
    public $notes;
    public $counter;
    public $uid;
    
    function __construct(){
        $this->db=$GLOBALS['db'];
    }
    
    function getRecords(){

        $this->ask="select id,DATE_FORMAT(date_from,'%d.%m.%Y') as date_from,DATE_FORMAT(date_to,'%d.%m.%Y') as date_to,symbol,rate from ecmpaymentstate_interest where deleted=0 order by position asc";
        
        $this->reply=$this->db->query($this->ask);
        while($this->result=$this->db->fetchByAssoc($this->reply)){
            $this->positions[]=$this->result;
        }
        
        return $this->positions;
    }

    function createNumber(){
        $this->numbers=explode(",",$_REQUEST[TABLEID.'_rowOrder']);
    }
        
    function getPost(){
        $tmp=array();
        $this->positions=array();
        $this->i=0;
        foreach ($this->numbers as $val){
            $tmp['rate']=$_REQUEST[TABLEID.'_rate_'.$val];
            $tmp['date_from']=date('Y-m-d',strtotime($_REQUEST[TABLEID.'_date_from_'.$val.'_date']));
            $tmp['date_to']=date('Y-m-d',strtotime($_REQUEST[TABLEID.'_date_to_'.$val.'_date']));
            $tmp['symbol']=$_REQUEST[TABLEID.'_symbol_'.$val];
            $tmp['position']=$this->i;
            $tmp['id']=$_REQUEST[TABLEID.'_id_'.$val]!='' ? $_REQUEST[TABLEID.'_id_'.$val] : create_guid();

            $this->saveRecord($tmp);
            unset($tmp);
            $this->i++;
        }
    }
    
    function deleteOld(){
        $this->db->query("delete from ecmpaymentstate_interest");
    }
    
    function saveRecord($tmp){
        $this->ask='INSERT INTO ecmpaymentstate_interest SET ';
        foreach ($tmp as $key=>$val){
            $this->ask.=$key.'="'.$val.'", ';
        }
        $this->ask.='deleted=0';
        $this->db->query($this->ask);
    }
    
    function saveRecords()
    {
        $this->deleteOld();
        $this->createNumber();
        $this->getPost();
    }
    
    function getInterestTable(){
        $this->positions=array();
        $this->ask="select * from ecmpaymentstate_interest where
 (date_from >= '".$this->sdate."' or date_to >= '".$this->sdate."') 
and (date_from <= '".$this->edate."' or date_to <= '".$this->edate."')";
 
        $this->reply=$this->db->query($this->ask);
        while($this->result=$this->db->fetchByAssoc($this->reply)){
            $this->positions[]=$this->result;
        }
       // var_dump($this->positions);
    }
    
    function daybeetwen($date,$date2){
      
        $date1 = new DateTime($date);
        $date2 = new DateTime(date('Y-m-d', strtotime($date2)));
       
        return $diff = $date2->diff($date1)->format("%a");
    }
    function calculateRate($typ,$dni,$proc ){
        if($typ=='R')$typ='365';
        if($typ=='M')$typ='30';
        return (($dni/$typ)*($proc/100)*$this->amount);
    }
    function calculateInterest(){
        $this->total=0;
       for($i=0;$i<count($this->positions);$i++){
           if($i==0){
           if(strtotime($this->positions[$i]['date_from'])<strtotime($this->sdate)){
               $this->positions[$i]['date_from']=date('Y-m-d', strtotime($this->sdate.' + 1 day'));
           } 
           if(strtotime($this->positions[$i]['date_from'])==strtotime($this->sdate)){
             $this->positions[$i]['date_from']=date('Y-m-d', strtotime($this->sdate.' + 1 day'));
           }
               //$this->positions[$i]['date_from']=$this->sdate;
               
                
                
                if(strtotime($this->positions[$i]['date_to'])>strtotime($this->edate)){
                    $this->positions[$i]['date_to']=$this->edate;
         
                    $this->positions[$i]['days']=$this->daybeetwen($this->positions[$i]['date_from'],$this->edate);
          
                } else {
                    $this->positions[$i]['days']=$this->daybeetwen($this->positions[$i]['date_from'],$this->positions[$i]['date_to']);
                }
                $this->positions[$i]['amount']=$this->calculateRate($this->positions[$i]['symbol'],$this->positions[$i]['days'],$this->positions[$i]['rate']);
                $this->positions[$i]['date_from']=date('d.m.Y',strtotime($this->positions[$i]['date_from']));
                $this->positions[$i]['date_to']=date('d.m.Y',strtotime($this->positions[$i]['date_to']));
            $this->total+=$this->positions[$i]['amount'];
       }
        else {
            if(strtotime($this->positions[$i]['date_from'])<strtotime($this->sdate)){
                $this->positions[$i]['date_from']=$this->sdate;
            }
            if(strtotime($this->positions[$i]['date_from'])==strtotime($this->sdate)){
                $this->positions[$i]['date_from']=$this->sdate;
            }
            //$this->positions[$i]['date_from']=$this->sdate;
             
            
            
            if(strtotime($this->positions[$i]['date_to'])>strtotime($this->edate)){
                $this->positions[$i]['date_to']=$this->edate;
                $this->positions[$i]['days']=$this->daybeetwen($this->positions[$i]['date_from'],$this->edate);
            } else {
                $this->positions[$i]['days']=$this->daybeetwen($this->positions[$i]['date_from'],$this->positions[$i]['date_to']);
            }
            $this->positions[$i]['amount']=$this->calculateRate($this->positions[$i]['symbol'],$this->positions[$i]['days'],$this->positions[$i]['rate']);
            $this->positions[$i]['date_from']=date('d.m.Y',strtotime($this->positions[$i]['date_from']));
            $this->positions[$i]['date_to']=date('d.m.Y',strtotime($this->positions[$i]['date_to']));
            $this->total+=$this->positions[$i]['amount'];
       }
      
    }
    }
    
    
    
    function rozbijDate($tmp){
        $date=array();
        
        $date[0]=date("Y",strtotime($tmp));
        $date[1]=date("n",strtotime($tmp));
        $date[2]=date("j",strtotime($tmp));
        
        return $date;
    }
    
    function checkDate($tmp){
        $tmp=$this->rozbijDate($tmp);
      
        while($this->workingDayOfYear(time(), true, mktime(0,0,0,$tmp[1],$tmp[2],$tmp[0]))!=false){
       
            $tmp = date('Y-m-d', strtotime($this->sdate.' + 1 day'));
            
            $this->sdate=$tmp;
            $tmp=$this->rozbijDate($tmp);
        }
    
    }
    
    function loadDates($par = true){
        $this->sdate=date("Y-m-d",strtotime($_REQUEST['payment_date']));
        $this->edate=date("Y-m-d",strtotime($_REQUEST['payment_after_date'])); 
        if($par==true){
        $this->amount=$this->number_unformat($_REQUEST['amount'],false,',','.')/100;
        } else {
            $this->amount=$_REQUEST['amount'];
        }
    }
    
    function json2array(){
        $this->ids=explode(",",$_REQUEST['id_list']);
        array_pop($this->ids);
    }
    
    function json2array2($id){
        $this->ids=explode(",",$id);
        array_pop($this->ids);
    }
    
    function getDatesMonitFromId($id){
  
        $this->ask=$this->db->query("
SELECT 
    t.payment_date as '0', (t.value-IFNULL(sum(r.value),0)) as '2', t.name, (t.value-IFNULL(sum(r.value),0)) as value, t.register_date, t.payment_date
FROM
    ecmtransactions t
	left join ecmtransactions_rel r on ( r.ecmtransaction_a_id=t.id or r.ecmtransaction_b_id=t.id)
                WHERE t.type='0'
                AND t.register_date > '2011-12-31'
                and  t.id='".$id."'
                ORDER BY t.register_date desc");
    
    
        $this->result=$this->db->fetchByAssoc($this->ask);
    }
    
    function getDatesFromId($id){
        $this->ask=$this->db->query("
                SELECT t.payment_date as '0',t.value as '2',t2.payment_date as '1',t.name,t.value,t.register_date FROM ecmtransactions t 
                inner join ecmtransactions_rel r on ( r.ecmtransaction_a_id=t.id or r.ecmtransaction_b_id=t.id)
                inner join ecmtransactions t2 on
                  (case r.ecmtransaction_b_id when t.id then t2.id=r.ecmtransaction_a_id else t2.id=r.ecmtransaction_b_id end)
                WHERE t.type='0'
                AND t.register_date > '2011-12-31'
                 and t.settled=1 
                and t.payment_date < t2.payment_date and t.id='".$id."'
                ORDER BY t.register_date desc");
 

        $this->result=$this->db->fetchByAssoc($this->ask);
    }
    
    function createRecord($name,$value,$date,$date2){
    
        $tmp=array();
        $tmp['total']=0;
        $tmp['days']=0;
        for ($i = 0; $i < count($this->positions); $i++) {
            $tmp['total']+=$this->positions[$i]['amount'];
            $tmp['days']+=$this->positions[$i]['days'];
        }
        $tmp['from']=$this->positions[0]['date_from'];
        $tmp['to']=$this->positions[count($this->positions)-1]['date_to'];
        $tmp['payment_date']=$date2;
        $tmp['date_doc']=date('d.m.Y',strtotime($date));
        $tmp['name']=$name;
        $tmp['paid']=$value;
        $tmp['position']=$this->counter;
        $this->counter++;
        $this->notes[]=$tmp;
    }
    
    function createID(){
        $this->uid=create_guid();
    }
    
    function updateRecord($id){
     
        $this->db->query("update ecmtransactions set note=1, note_id='".$this->uid."' where id='".$id."'");
    }
    
    function makeNotes(){
       $this->notes=array();
        $this->json2array();
        if(count($this->ids)>0){
            $this->counter=0;
            $this->createID();
            foreach ($this->ids as $val){
               
                $this->getDatesFromId($val);
                $name=$this->result['name'];
                $value=$this->result['value'];
                $date=$this->result['register_date'];
                $this->calculateRecordsToNote($this->result['0'],$this->result['1'],$this->result['2']);
               $this->createRecord($name,$value,$date);
               $this->updateRecord($val);
            }
        }
        include 'modules/EcmPaymentStates/createPDF.php';
        createEcmPaymentStatePdf($this->ids[0],'BROSWER',$this->notes,$this->uid);
       
    }
    function makeMonit($id,$t=false){
        $this->notes=array();
        $this->json2array2($id);
        if(count($this->ids)>0){
            $this->counter=0;
           // $this->createID();
            foreach ($this->ids as $val){
                 
                $this->getDatesMonitFromId($val);
                $name=$this->result['name'];
                $value=$this->result['value'];
                $date=$this->result['register_date'];
                $date2=date('d.m.Y',strtotime($this->result['payment_date']));
                $this->calculateRecordsToNote($this->result['0'],date("Y-m-d"),$this->result['2']);
                $this->createRecord($name,$value,$date,$date2);
              
              //  $this->updateRecord($val);
            }
        }
        if($t==true){
            $b='BROSWER';
        } else {
            $b='FILE';
        }

        include 'modules/EcmPaymentStates/createPDF.php';
        return createEcmPaymentStatePdf2($this->ids[0],$b,$this->notes);
         
    }
    function checkPost($start,$end,$amount){
        $_REQUEST['payment_date']=$start!='' ? $start : $_REQUEST['payment_date'];
        $_REQUEST['payment_after_date']=$end!='' ? $end : $_REQUEST['payment_after_date'];
        $_REQUEST['amount']=$amount!='' ? $amount : $_REQUEST['amount'];
    }
    
    function calculateRecordsToNote($start,$end,$amount){
        $this->checkPost($start,$end,$amount);
        $this->loadDates(false);
     
        $this->checkDate($this->sdate);
        $this->getInterestTable();
        $this->calculateInterest();

        return $this->positions;
    }
    
    function calculateRecords(){
    
        $this->loadDates(true);
 
        
        $this->checkDate($this->sdate);
   
        $this->getInterestTable();
        $this->calculateInterest();
        
        return $this->positions;
    }
    
    function number_unformat($number, $force_number = true, $dec_point = '.', $thousands_sep = ',') {
        if ($force_number) {
            $number = preg_replace('/^[^\d]+/', '', $number);
        } else if (preg_match('/^[^\d]+/', $number)) {
            return false;
        }
        $type = (strpos($number, $dec_point) === false) ? 'int' : 'float';
        $number = str_replace(array($dec_point, $thousands_sep), array('.', ''), $number);
        settype($number, $type);
        return $number;
    }
    

    function workingDayOfYear($timeStamp = null, $freeSaturdays = true,  $extraFreeDays = array(), $extraWorkingDays = array())
    {
        $freeHolidayDays	= 0;
        $addWorkingDays	 = 0;
        $timeStamp		  = is_null($extraFreeDays) ? time() : $extraFreeDays;
        $firstDayOfYear	 = date('w', mktime(0,0,0,1,1,date('Y', $timeStamp)));
        $dayOfYear		  = date('z', $timeStamp)+1;
    
        $year			   = date('Y', $timeStamp);
        $day			   = date('j', $timeStamp);
        $mon			   = date('n', $timeStamp);
        $easterDay		  = easter_date($year);
        $extraWorkingDays   = (array)$extraWorkingDays;
        $extraFreeDays	  = (array)$extraFreeDays;
    
        /*
         od aktualnego tygonia roku odejmujemy 1
         bo aktualny tydzien nie jest jeszcze zakonczony
         */
    
        $passedWeekends = (int)date('W', $timeStamp)-1;
        $freeWeekendDays= $passedWeekends;
    
        /*
         funkcja date('W') liczy tygonie w roku rozpoczynajac od poniedzialku
         stad, jezeli 1 stycznia wypada w niedziele odejmujemy jeden tydzien
         jezeli wypada pozniej niz w poniedzialek, dodajemy jeden tydzien
         */
    
        if($firstDayOfYear == 0)
        {   $passedWeekends--;
        }
        else if ($firstDayOfYear > 1)
        {   $passedWeekends++;
        }
    
        /*
         lista dni ustawowo wolnych od pracy wg.
         Ustawa z dnia 18 stycznia 1951 r. o dniach wolnych od pracy.
         (Dz.U. 1951 nr 4 poz. 28) z pozniejszymi zmianami
         isip.sejm.gov.pl/servlet/Search?todo=file&id=WDU19510040028&type=3&name=D9510028.pdf
         */
    
        $freeDaysArray = array(
                mktime(0,0,0,1,1,$year),	//  nowy rok
                mktime(0,0,0,1,6,$year),	//  trzech króli
                $easterDay,				 //  pierwszy dzien wielkiej nocy
                $easterDay + 86400,		 //  drugi dzien wielkiej nocy
                mktime(0,0,0,5,1,$year),	//  1 maja
                mktime(0,0,0,5,3,$year),	//  3 maja
                $easterDay + (60*86400),	//  boze cialo
                $easterDay + (49*86400),	//  zielone swiatki
                mktime(0,0,0,8,15,$year),   //  15 sierpnia
                mktime(0,0,0,11,1,$year),   //  1 listopada
                mktime(0,0,0,11,11,$year),  //  11 listopada
                mktime(0,0,0,12,25,$year),  //  25 grudnia
                mktime(0,0,0,12,26,$year)   //  26 grudnia
        );
       
        $weekDay = date('w', $extraFreeDays[0]);
      
       $return2= array_search($extraFreeDays[0], $freeDaysArray);
       if($weekDay == 0 || $weekDay == 6 || $return2){
     
           return true;
       } else {
          return false;
       }
    
    }
}
?>