<?php
// src/Controller/ArticlesController.php

namespace App\Controller;
use Cake\I18n\Number;
use App\Controller\AppController;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
class DemandController extends AppController
{
    public $helpers = array('Html', 'Form');
    public $components = array('RequestHandler', 'Paginator', 'Flash');
  

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
         //$this->Security->config('unlockedActions', ['sectionAjax', 'section_ajax']);
         //$this->Security->config('allowedActions', ['sectionAjax', 'section_ajax']);

        if(isset($this->Security) && ($this->request->is('ajax') || $this->request['action'] == 'index')) {
			$this->Security->config('unlockedActions', [$this->request['action']]);
		}
         
    }    
    public function generate()
    {
$this->loadModel('Division');
$divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ,'order' => 'Division.division ASC'));
$this->set('divisions',$divisions);
$this->loadModel('Section');
$sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
$this->set('sections',$sections);

if ($this->request->is('post')) {
    $division = $this->request->getData('division');
    $this->set('division',$division);
    $section = $this->request->getData('section');
    $this->set('section',$section);
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    if(!isset($_POST['postvalue']))
    {
    if($month=="" || $year=="") 
{
    $this->Flash->success(__('Select Month and Year'));
    return $this->redirect(['action' => 'generate']);
}
    }
    $div = $this->request->getData('division');
    $this->loadModel('Division');
    $div = $this->Division->find('all', ['conditions' => ['Division.division' => $div ]  ]);
    $row = $div->first();
    $division_mem_no = $row['id'];
    $address=$row['address'];
    $this->set('address',$address);
 
        $this->loadModel('MapDivisionSection');
        $sec = $this->MapDivisionSection->find('all', ['conditions' => ['MapDivisionSection.division_id' => $division_mem_no], 'contain' => ['Section'] ] );
        // Iterate it
        $s=0;
        $result = array();
foreach($sec as $key=>$postObject) {
//echo $postObject->section_id;
    $this->loadModel('Section');
    $sections = $this->Section->find('all', ['conditions' => ['Section.id' => $postObject->section_id ]  ]);
    foreach($sections as $key=>$new) {
        $postObject->section = $new->section;
        }
        $result[$key] = $postObject;  
}
$this->set(compact('sec')); 
     $this->loadModel('Member');
    if($division!="" && $section=="")
    {
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
    $this->set(compact('members'));
    }
    elseif($division!="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
     elseif($division=="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
    else{
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
    $this->set(compact('members'));
    }
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Demand');
        $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
        $demand  = $query->first(); 
        $re =$demand ? $demand->mem_no :0;
        if($re!=0) 
    {
        $this->Flash->success(__('Selected Month and Year  Demand Already Generated'));
        return $this->redirect(['action' => 'generate']);
    }
    }
    $result = array();
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Loan');
        $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$mem_no]] );
        $loan  = $query->first(); 
        //Loan Principle
        $member->loan_principle_amt =$loan ? $loan->loan_principle_amt :0;
        $member->loan_int_rate =$loan ? $loan->loan_int_rate :0;
        $member->loan_os_amt =$loan ? $loan->loan_os_amt :0;
          $member->no_of_days =$loan ? $loan->no_of_days :0;
           $member->fst_int =$loan ? $loan->fst_int :0;
        //Loan INterest : calcucaltion
        if($member->fst_int==1){
          $member->loan_int_amt = ( $member->loan_int_rate * $member->loan_os_amt *$member->no_of_days)/36500;
      }
        else{
        $member->loan_int_amt = ( $member->loan_int_rate * $member->loan_os_amt )/1200;
       
       }

        $member->old_pri_int = ( $member->old_due_pri * 3 )/1200;
         //Loan Amount
         $member->loan_int_amt = round($member->loan_int_amt); 
         $member->f_int_amt = round($member->f_int_amt); 
         $member->old_pri_int = round($member->old_pri_int); 
         $member->loan_no =$loan ? $loan->loan_no :0;
         $member->loan_amount =$loan ? $loan->loan_amount :0;
         $member->loan_instalment =$loan ? $loan->loan_instalment :0;
         $member->curr_instalment =$loan ? $loan->curr_instalment :0;
         $this->loadModel('Thrift');
        $query = $this->Thrift->find('all', ['conditions' => ['Thrift.is_deleted' => 0,'Thrift.mem_no'=>$mem_no]] );
        $thrift  = $query->first(); 
        $member->thrift_amt = $thrift ? $thrift->thrift_amt : 0;
                $this->loadModel('Insurance');
        $query = $this->Insurance->find('all', ['conditions' => ['Insurance.mem_no'=>$mem_no]] );
        $insurance  = $query->first(); 
        $member->insurance = $insurance ? $insurance->insurance : 0;
        /*  $this->loadModel('Member');
        $query = $this->Member->find('all', ['conditions' => ['Member.mem_no'=>$mem_no]] );
        $mem  = $query->first(); 
        $member->old_ins = $mem ? $mem->old_ins : 0; */
        $member->total = $member->loan_int_amt + $member->loan_principle_amt + $member->old_due_pri + $member->old_due_int + $member->old_thrift + $member->thrift_amt + $member->insurance + $member->old_pri_int+  $member->old_ins;
        $member->total = round($member->total);   
        $result[$key] = $member;
       /* print "<pre>";
        print_r($mem); */
      
    }
 //   die();
    $this->set(compact('members'));
    
    if(isset($_POST['postvalue'])){

        $postvalue = $this->request->getData('postvalue');
        foreach($postvalue as $key=>$value){
       
            $this->loadModel('Demand');
            $demand = $this->Demand->newEntity();
            $this->Demand->patchEntity($demand,$value);
           /*  print_r($demand);
        die(); */
            $this->Demand->save($demand);
            
            $pay_ = TableRegistry::get("Loan");
                        $query = $pay_->query();
                                    $result = $query->update()
                                            ->set(['fst_int' => '0'])
                                            ->where(['mem_no' => $demand['mem_no']])
                                            ->execute(); 
        }
       
        $this->Flash->success(__('Demand Saved Successfully'));
        $this->set('demand', $demand);
     //   print "<pre>";
      //  print_r($postvalue); 
        //die();
    }
   
}
}
public function reverse()
    {
$this->loadModel('Member');
$mem_no = $this->Member->find('list', array( 'keyField' => 'mem_no', 'valueField' => 'mem_no' ));
$this->set('mem_no',$mem_no);
if ($this->request->is('post')) {
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    
        $member_no = $this->request->getData('mem_no');
        $this->set('member_no',$member_no);
        $this->loadModel('Payment');
        $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted' => '0','Payment.mem_no'=>$member_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        $payment  = $query->first(); 
        $calc['thrift_amt'] =$payment ? $payment->thrift_amt :0;
        $calc['mem_no'] =$payment ? $payment->mem_no :0;
        $calc['last_pri'] =$payment ? $payment->last_principal :0;
        $calc['pri_amt'] =$payment ? $payment->loan_pri_amt :0;
        $calc['tot_pri'] = $calc['pri_amt'] + $calc['last_pri'];
        $calc['last_int'] =$payment ? $payment->last_int :0;
        $calc['tot_pay'] =$payment ? $payment->tot_pay :0;
        if($calc['mem_no']==0) 
    {
        $this->Flash->success(__('Selected Month and Year Payment Not Recovered'));
        return $this->redirect(['action' => 'reverse']);
    }
    $this->loadModel('Loan');
           $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=> $calc['mem_no'] ]] );
           $loano  = $query->first(); 
           $calc['cur_os'] = $loano->loan_os_amt;
           $calc['loan_os'] = $calc['cur_os'] + $calc['tot_pri']; 
            $this->loadModel('Thrift');
            $query = $this->Thrift->find('all', ['conditions' => ['Thrift.is_deleted' => 0,'Thrift.mem_no'=>$calc['mem_no']]] );
            $thrift  = $query->first(); 
            $calc['total_t'] =  $thrift->tot_thrift;
    $calc['tot_thrift'] = $calc['total_t'] - $calc['thrift_amt'] ;
            $th_u = TableRegistry::get("Thrift");
    $query = $th_u->query();
                $result = $query->update()
                        ->set(['tot_thrift' => $calc['tot_thrift']])
                        ->where(['mem_no' => $calc['mem_no']])
                        ->execute();
    
                        $pay_ = TableRegistry::get("Payment");
                        $query = $pay_->query();
                                    $result = $query->update()
                                            ->set(['is_deleted' => '1'])
                                            ->where(['mem_no' => $calc['mem_no']])
                                            ->execute();
    $this->loadModel('Demand');
    $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$member_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
    $demand  = $query->first(); 
    $calc['old_pri'] =$demand ? $demand->d_last_principal :0;
    $calc['old_int'] =$demand ? $demand->d_last_int :0;
    $calc['tot_amt'] =$demand ? $demand->d_total :0;
    $member = TableRegistry::get("Member");
    $query = $member->query();
                $result = $query->update()
                        ->set(['old_due_int' => $calc['old_int'],'old_due_pri'=>$calc['old_pri']])
                        ->where(['mem_no' => $calc['mem_no']])
                        ->execute(); 
    $calc['tot_amt'] = $calc['tot_amt'] - $calc['tot_pay']; 
    
    if($calc['tot_amt']<=0)
    {
        $calc['loan_os'] = $calc['loan_os'] - $calc['tot_amt'];
    }                
        $loan = TableRegistry::get("Loan");
        $query = $loan->query();
                    $result = $query->update()
                            ->set(['loan_os_amt' => $calc['loan_os']])
                            ->where(['mem_no' => $calc['mem_no']])
                            ->execute();
                        $this->Flash->success(__('Selected Month and Year Payment Reversed'));
                        return $this->redirect(['action' => 'reverse']);
    }
}
    public function sectionajax()
    {
        $this->autoRender = false;
        if ($this->request->is('ajax')) {
            $division = $this->request->query('division');
            $this->loadModel('Division');
            $division = $this->Division->find('all', ['conditions' => ['Division.division' => $division ]  ]);
            $row = $division->first();
            $division_mem_no = $row['id'];

            if($division){
                $this->loadModel('MapDivisionSection');
                $sections = $this->MapDivisionSection->find('all', ['conditions' => ['MapDivisionSection.division_id' => $division_mem_no], 'contain' => ['Section'] ,'order' => array('MapDivisionSection.section_id ASC')] );
                // Iterate it
foreach($sections as $postObject) {
    //echo $postObject->section_id;
    $division = $this->request->query('section');
            $this->loadModel('Section');
            $section1[] = $this->Section->find('all',array(
                'conditions' => array('Section.id' =>$postObject->section_id),
                'order' => array('Section.section ASC'),
            ));
            
}
                $resultJ = json_encode(array('result' => true, 'data' => $section1));

                $this->response->type('json');
                $this->response->body($resultJ);
                return $this->response;
            }else{
                $resultJ = json_encode(array('result' => false));
                $this->response->type('json');
                $this->response->body($resultJ);
                return $this->response;
            }
        }
    }

    public function receipt()
    {
    $this->loadModel('Division');
$divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ,'order' => 'Division.division ASC'));
$this->set('divisions',$divisions);
        $this->loadModel('Section');
        $sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
        $this->set('sections',$sections);
        
        if ($this->request->is('post')) {
            $division = $this->request->getData('division');
            $this->set('division',$division);
            $section = $this->request->getData('section');
            $this->set('section',$section);
            $added_on = $this->request->getData('added_on');
            $this->set('added_on',$added_on);
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    if($month==""&&$year!="" || $year==""&&$month!="") 
    {
        $this->Flash->success(__('Select Month and Year'));
        return $this->redirect(['action' => 'receipt']);
    }
    $this->loadModel('Member');
    if($division!="" && $section=="")
    {
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
    $this->set(compact('members'));
    }
    elseif($division!="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
     elseif($division=="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
    else{
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
    $this->set(compact('members'));
    }
    $result = array();
    foreach($members as $key=>$member){
        $mem_no=$member->mem_no;
        $this->loadModel('Payment');
        if($added_on!==""){
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.paid_on'=>$added_on]] );
        }
        else{
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        }
        
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
        $member->thrift_amt =$payment ? $payment->thrift_amt :0;
        $member->rec_no =$payment ? $payment->rec_no :0;
        $member->share_amt =$payment ? $payment->share_amt :0;
          $member->ent_fees =$payment ? $payment->ent_fees :0;
        $member->loan_pri_amt =$payment ? $payment->loan_pri_amt :0;
        $member->loan_int_amt =$payment ? $payment->loan_int_amt :0;
        $member->last_int =$payment ? $payment->last_int :0;
        $member->last_principal =$payment ? $payment->last_principal :0;
        $member->p_int =$payment ? $payment->p_int :0;
         $member->f_pri =$payment ? $payment->f_pri :0;
        $member->f_int =$payment ? $payment->f_int :0;
        $member->f_old_pri =$payment ? $payment->f_old_pri :0;
        $member->f_old_int =$payment ? $payment->f_old_int :0;
        $member->f_p_int =$payment ? $payment->f_p_int :0;
        $member->others =$payment ? $payment->others :0;
        $member->insurance =$payment ? $payment->insurance :0;
         $member->old_ins =$payment ? $payment->old_ins :0;
          $member->old_thrift =$payment ? $payment->old_thrift :0;
        $member->due_by =$payment ? $payment->due_by :0;
        $member->ex_os =$payment ? $payment->ex_os :0;
        $member->f_ex_os =$payment ? $payment->f_ex_os :0;
        $member->os_pay =$payment ? $payment->os_pay :0;
        $member->tot_pay =$payment ? $payment->tot_pay :0;
        $member->paid_on =$payment ? $payment->paid_on :0;
        $this->loadModel('Loan');
        $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$mem_no]] );
        $loan  = $query->first(); 
        $member->loan_no =$loan ? $loan->loan_no :0;
        $result[$key] = $member;
}
    $this->set(compact('member'));  
}
    }

    public function view()
    {
    $mem_no         = isset($this->request->query['mem_no'])         ? $this->request->query['mem_no']         : null;
    $year       = isset($this->request->query['year'])       ? $this->request->query['year']       : null;
    $month = isset($this->request->query['month']) ? $this->request->query['month'] : null;
    $added_on = isset($this->request->query['added_on']) ? $this->request->query['added_on'] : null;
    $this->set('mem_no',$mem_no); 
    $this->set('month',$month);
    $this->set('year',$year);
    $this->loadModel('Member');
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.mem_no'=>$mem_no]] );
    $this->set(compact('members'));
    $member  = $members->first(); 
        $this->loadModel('Payment');
        if($added_on!==""){
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.paid_on'=>$added_on]] );
        }
        else{
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        }
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
        $member->thrift_amt =$payment ? $payment->thrift_amt :0;
        $member->rec_no =$payment ? $payment->rec_no :0;
        $member->share_amt =$payment ? $payment->share_amt :0;
          $member->ent_fees =$payment ? $payment->ent_fees :0;
        $member->loan_pri_amt =$payment ? $payment->loan_pri_amt :0;
        $member->loan_int_amt =$payment ? $payment->loan_int_amt :0;
        $member->last_int =$payment ? $payment->last_int :0;
        $member->last_principal =$payment ? $payment->last_principal :0;
        $member->p_int =$payment ? $payment->p_int :0;
         $member->f_pri =$payment ? $payment->f_pri :0;
        $member->f_int =$payment ? $payment->f_int :0;
        $member->f_old_pri =$payment ? $payment->f_old_pri :0;
        $member->f_old_int =$payment ? $payment->f_old_int :0;
        $member->f_p_int =$payment ? $payment->f_p_int :0;
        $member->others =$payment ? $payment->others :0;
        $member->insurance =$payment ? $payment->insurance :0;
         $member->old_ins =$payment ? $payment->old_ins :0;
        $member->due_by =$payment ? $payment->due_by :0;
        $member->ex_os =$payment ? $payment->ex_os :0;
        $member->f_ex_os =$payment ? $payment->f_ex_os :0;
        $member->os_pay =$payment ? $payment->os_pay :0;
        $member->f_os_pay =$payment ? $payment->f_os_pay :0;
        $member->tot_pay =$payment ? $payment->tot_pay :0;
        $member->paid_on =$payment ? $payment->paid_on :0;
        $this->loadModel('Loan');
        $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$mem_no]] );
        $loan  = $query->first(); 
        $member->loan_no =$loan ? $loan->loan_no :0;
  
    $this->set(compact('member'));  

    }

    public function ssms()
    {
    $mem_no         = isset($this->request->query['mem_no'])         ? $this->request->query['mem_no']         : null;
    $year       = isset($this->request->query['year'])       ? $this->request->query['year']       : null;
    $month = isset($this->request->query['month']) ? $this->request->query['month'] : null;
    $added_on = isset($this->request->query['added_on']) ? $this->request->query['added_on'] : null;
    $this->set('mem_no',$mem_no); 
    $this->set('month',$month);
    $this->set('year',$year);
    $this->loadModel('Member');
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.mem_no'=>$mem_no]] );
    $this->set(compact('members'));
    $member  = $members->first(); 
        $this->loadModel('Payment');
        if($added_on!==""){
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.paid_on'=>$added_on]] );
        }
        else{
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        }
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
        $member->thrift_amt =$payment ? $payment->thrift_amt :0;
        $member->rec_no =$payment ? $payment->rec_no :0;
        $member->share_amt =$payment ? $payment->share_amt :0;
          $member->ent_fees =$payment ? $payment->ent_fees :0;
        $member->loan_pri_amt =$payment ? $payment->loan_pri_amt :0;
        $member->loan_int_amt =$payment ? $payment->loan_int_amt :0;
        $member->last_int =$payment ? $payment->last_int :0;
        $member->last_principal =$payment ? $payment->last_principal :0;
        $member->p_int =$payment ? $payment->p_int :0;
         $member->f_pri =$payment ? $payment->f_pri :0;
        $member->f_int =$payment ? $payment->f_int :0;
        $member->f_old_pri =$payment ? $payment->f_old_pri :0;
        $member->f_old_int =$payment ? $payment->f_old_int :0;
        $member->f_p_int =$payment ? $payment->f_p_int :0;
        $member->others =$payment ? $payment->others :0;
        $member->insurance =$payment ? $payment->insurance :0;
         $member->old_ins =$payment ? $payment->old_ins :0;
        $member->due_by =$payment ? $payment->due_by :0;
        $member->ex_os =$payment ? $payment->ex_os :0;
        $member->f_ex_os =$payment ? $payment->f_ex_os :0;
        $member->os_pay =$payment ? $payment->os_pay :0;
        $member->f_os_pay =$payment ? $payment->f_os_pay :0;
        $member->tot_pay =$payment ? $payment->tot_pay :0;
        $member->paid_on =$payment ? $payment->paid_on :0;
         $member->payment_month =$payment ? $payment->payment_month :0;
        $member->payment_year =$payment ? $payment->payment_year :0;
        $this->loadModel('Loan');
        $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$mem_no]] );
        $loan  = $query->first(); 
        $member->loan_no =$loan ? $loan->loan_no :0;
         $months_t=array('January'=>'ஜனவரி','February'=>'பிப்ரவரி ','March'=>'மார்ச்','April'=>'ஏப்ரல்','May'=>'மே','June'=>'ஜுன்','July'=>'ஜுலை','August'=>'ஆகஸ்ட்','September'=>'செப்டம்பர்','October'=>'அக்டோபர்','November'=>'நவம்பர்','December'=>'டிசம்பர்' );
   $s_yr=date('Y',strtotime($member->paid_on));
   $s_month=date("m", strtotime($member->paid_on));
  $month_tam=$months_t[$member->payment_month];
  //print_r($month_tam);die();
   $pri=$member->loan_pri_amt+$member->last_principal;
    $int=$member->loan_int_amt+$member->last_int;
    $f_pri=$member->f_pri+$member->f_old_pri;
    $f_int=$member->f_int+$member->f_old_int;
    $msg=$member->mem_name."(".$member->mem_no."), ".$month_tam." ".$s_yr." மாத சம்பளத்தில் ரூ.".$member->tot_pay." செலுத்தியுள்ளீர்கள், சி. சே:".$member->thrift_amt.", அசல்:".$pri.", வட்டி:".$int.", ப. கடன்:".$f_pri.", வட்டி:".$f_int.", ரசீது எண்:".$member->rec_no.", - திருச்சிராப்பள்ளி வேளாண்மை கூட்டுறவு சங்கம்: 0431 - 2420 540, மேலும் விவரங்களுக்கு இங்கே கிளிக் செய்யவும் http://r693.tnecs.com/demand/view?mem_no=".$member->mem_no."&month=".$payment->payment_month."&year=".$payment->payment_year."&added_on=";
    $umsg=urlencode($msg);
   $url="http://brightsms.brighttechnologies.co.in/httpapi/httpapi?token=4fc1372211bcae6ea775183d27f176e8&sender=AGRISO&number=$member->phone&route=2&type=3&sms=$umsg";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curl_scraped_page = curl_exec($ch);
    curl_close($ch);
                $this->Flash->success(__('SMS send successfully'));
                return $this->redirect(['action' => 'receipt']);
  
    $this->set(compact('member'));  

    }
    
    public function asms()
    {

            $division=isset($this->request->query['division'])?$thi->request->query['division']:null;
            $this->set('division',$division);
             $section=isset($this->request->query['section'])?$thi->request->query['division']:null;
            $this->set('section',$section);
            $added_on=isset($this->request->query['added_on'])?$thi->request->query['added_on']:null;
            $this->set('added_on',$added_on);
    $month=isset($this->request->query['month'])?$thi->request->query['month']:null;
    $this->set('month',$month);
     $year=isset($this->request->query['year'])?$thi->request->query['year']:null;
    $this->set('year',$year);
    if($month==""&&$year!="" || $year==""&&$month!="") 
    {
        $this->Flash->success(__('Select Month and Year'));
        return $this->redirect(['action' => 'receipt']);
    }
    $this->loadModel('Member');
    if($division!="" && $section=="")
    {
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
    $this->set(compact('members'));
    }
    elseif($division!="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
     elseif($division=="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
    else{
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
    $this->set(compact('members'));
    }
    $result = array();
    foreach($members as $key=>$member){
        $mem_no=$member->mem_no;
        $this->loadModel('Payment');
        if($added_on!==""){
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.paid_on'=>$added_on]] );
        }
        else{
            $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>'0','Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        }
        
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
        $member->thrift_amt =$payment ? $payment->thrift_amt :0;
        $member->rec_no =$payment ? $payment->rec_no :0;
        $member->share_amt =$payment ? $payment->share_amt :0;
          $member->ent_fees =$payment ? $payment->ent_fees :0;
        $member->loan_pri_amt =$payment ? $payment->loan_pri_amt :0;
        $member->loan_int_amt =$payment ? $payment->loan_int_amt :0;
        $member->last_int =$payment ? $payment->last_int :0;
        $member->last_principal =$payment ? $payment->last_principal :0;
        $member->p_int =$payment ? $payment->p_int :0;
         $member->f_pri =$payment ? $payment->f_pri :0;
        $member->f_int =$payment ? $payment->f_int :0;
        $member->f_old_pri =$payment ? $payment->f_old_pri :0;
        $member->f_old_int =$payment ? $payment->f_old_int :0;
        $member->f_p_int =$payment ? $payment->f_p_int :0;
        $member->others =$payment ? $payment->others :0;
        $member->insurance =$payment ? $payment->insurance :0;
         $member->old_ins =$payment ? $payment->old_ins :0;
          $member->old_thrift =$payment ? $payment->old_thrift :0;
        $member->due_by =$payment ? $payment->due_by :0;
        $member->ex_os =$payment ? $payment->ex_os :0;
        $member->f_ex_os =$payment ? $payment->f_ex_os :0;
        $member->os_pay =$payment ? $payment->os_pay :0;
        $member->tot_pay =$payment ? $payment->tot_pay :0;
        $member->paid_on =$payment ? $payment->paid_on :0;
        $this->loadModel('Loan');
        $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$mem_no]] );
        $loan  = $query->first(); 
        $member->loan_no =$loan ? $loan->loan_no :0;
        $result[$key] = $member;
            $months_t=array('1'=>'ஜனவரி','2'=>'பிப்ரவரி ','3'=>'மார்ச்','4'=>'ஏப்ரல்','5'=>'மே','6'=>'ஜுன்','7'=>'ஜுலை','8'=>'ஆகஸ்ட்','9'=>'செப்டம்பர்','10'=>'அக்டோபர்','11'=>'நவம்பர்','12'=>'டிசம்பர்' );
  

   $s_yr=date('Y',strtotime($member->paid_on));
   $s_month=date("m", strtotime($member->paid_on));
  $month_tam=$months_t[$s_month];
   $pri=$member->loan_pri_amt+$member->last_principal;
    $int=$member->loan_int_amt+$member->last_int;
    $f_pri=$member->f_pri+$member->f_old_pri;
    $f_int=$member->f_int+$member->f_old_int;
    $msg=$member->mem_name."(".$member->mem_no."), ".$month_tam." ".$s_yr." மாத சம்பளத்தில் ரூ.".$member->tot_pay." செலுத்தியுள்ளீர்கள், சி. சே:".$member->thrift_amt.", அசல்:".$pri.", வட்டி:".$int.", ப. கடன்:".$f_pri.", வட்டி:".$f_int.", ரசீது எண்:".$member->rec_no.", - திருச்சிராப்பள்ளி வேளாண்மை கூட்டுறவு சங்கம்: 0431-2422230, மேலும் விவரங்களுக்கு இங்கே கிளிக் செய்யவும் http://r693.tnecs.com/demand/view?mem_no=".$member->mem_no."&month=".$payment->payment_month."&year=".$payment->payment_year."&added_on=";
    $umsg=urlencode($msg);
   $url="http://brightsms.brighttechnologies.co.in/httpapi/httpapi?token=4fc1372211bcae6ea775183d27f176e8&sender=AGRISO&number=$member->phone&route=2&type=3&sms=$umsg";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $curl_scraped_page = curl_exec($ch);
    curl_close($ch);
              
}
  $this->Flash->success(__('SMS send successfully'));
                return $this->redirect(['action' => 'receipt']);
    $this->set(compact('member'));  

    }

    public function divrec()
    {
        $this->loadModel('Division');
        $divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ));
        $this->set('divisions',$divisions);
        $this->loadModel('Section');
        $sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
        $this->set('sections',$sections);
        
        if ($this->request->is('post')) {
           /* $division = $this->request->getData('division');
            $this->set('division',$division);
            $section = $this->request->getData('section');
            $this->set('section',$section);
            $added_on = $this->request->getData('added_on');
            $this->set('added_on',$added_on); */
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    if($month==""&&$year!="" || $year==""&&$month!="") 
    {
        $this->Flash->success(__('Select Month and Year'));
        return $this->redirect(['action' => 'divrec']);
    }
   $sql='SELECT sum(tot_pay) as total,sum(ex_os) as ex_os,sum(f_ex_os) as f_ex_os,sum(thrift_amt) as thrift_amt,sum(loan_pri_amt) as pri,sum(last_principal) as l_pri ,sum(os_pay) as os_pay,sum(loan_int_amt) as interest,sum(last_int) as l_int,sum(p_int) as p_int,sum(f_pri) as f_pri,sum(p.f_old_pri) as f_old_pri , sum(p.f_os_pay) as f_os_pay,sum(f_int) as f_int,sum(p.f_old_int) as f_old_int,sum(f_p_int) as f_p_int ,sum(others) as others,max(paid_on) as paid_on ,m.division as division,m.section as section FROM payment p join member m on m.mem_no=p.mem_no where ';
   $sql.='p.payment_month="'.$month.'" and p.payment_year="'.$year.'"  and p.is_deleted="0" group by m.division , m.section ';

        $this->loadModel('Payment');
        $conn = ConnectionManager::get('default');
        $payment = $conn->execute($sql);
    $this->set(compact('payment'));  
}

    }

    public function divreciept()
    {
        $division         = isset($this->request->query['division'])         ? $this->request->query['division']         : null;
        $section         = isset($this->request->query['section'])         ? $this->request->query['section']         : null;
        $year       = isset($this->request->query['year'])       ? $this->request->query['year']       : null;
        $month = isset($this->request->query['month']) ? $this->request->query['month'] : null;
        $added_on = isset($this->request->query['added_on']) ? $this->request->query['added_on'] : null;
        $this->set('division',$division); 
        $this->set('section',$section); 
        $this->set('month',$month);
        $this->set('year',$year);
    if($month==""&&$year!="" || $year==""&&$month!="") 
    {
        $this->Flash->success(__('Select Month and Year'));
        return $this->redirect(['action' => 'divrec']);
    }
    $sql='SELECT sum(tot_pay) as total,sum(ex_os) as ex_os,sum(f_ex_os) as f_ex_os,sum(thrift_amt) as thrift_amt,sum(loan_pri_amt) as pri,sum(last_principal) as l_pri ,sum(os_pay) as os_pay,sum(loan_int_amt) as interest,sum(last_int) as l_int,sum(p_int) as p_int,sum(f_pri) as f_pri,sum(p.f_old_pri) as f_old_pri , sum(p.f_os_pay) as f_os_pay,sum(f_int) as f_int,sum(p.f_old_int) as f_old_int,sum(f_p_int) as f_p_int ,sum(others) as others,max(paid_on) as paid_on ,m.division as division,m.section as section FROM payment p join member m on m.mem_no=p.mem_no where ';
    $sql.='p.payment_month="'.$month.'" and p.payment_year="'.$year.'" and m.division="'.$division.'" and m.section="'.$section.'"  and p.is_deleted="0" group by m.division , m.section ';

        $this->loadModel('Payment');
        $conn = ConnectionManager::get('default');
        $payment = $conn->execute($sql);

        foreach($payment as $pay)  { 
            if( $pay['total'] <=0)
            {  
                $this->Flash->success(__('Division Reciept Not Available'));
                return $this->redirect(['action' => 'divrec']);
            }
        }
    $this->set(compact('payment'));  


    }

    public function recover()
    {
$this->loadModel('Division');
$divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ,'order' => 'Division.division ASC'));
$this->set('divisions',$divisions);
$this->loadModel('Section');
$sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
$this->set('sections',$sections);

if ($this->request->is('post')) {
    
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    $added_on = $this->request->getData('added_on');
    $this->set('added_on',$added_on);
        $division = $this->request->getData('division');
        $this->set('division',$division);
        $section = $this->request->getData('section');
        $this->set('section',$section);
        if(!isset($_POST['postvalue']))
        {
        if($month=="" || $year=="") 
    {
        $this->Flash->success(__('Select Month and Year'));
        return $this->redirect(['action' => 'recover']);
    }
        }
    $this->loadModel('Member');
    if($division!="" && $section=="")
    {
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
    $this->set(compact('members'));
    }
    elseif($division!="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
     elseif($division=="" && $section!=""){
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
    $this->set(compact('members'));
    }
    else{
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
    $this->set(compact('members'));
    }
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Payment');
        $query = $this->Payment->find('all', ['conditions' => ['Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
        if($re!=0) 
        {
            $this->Flash->success(__('Selected Month and Year  Payment Already Recovered'));
            return $this->redirect(['action' => 'recover']);
        }
    }
   
    $this->loadModel('Payment');
    $rec_no = $this->Payment->find()
->select(['rec_no' => 'MAX(Payment.rec_no)']);
$rec_no = $rec_no->first();
$re = $rec_no->rec_no;

    $result = array();
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Demand');
        $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
        $demand  = $query->first(); 
        $member->d_thrift =$demand ? $demand->d_thrift :0;
        $member->d_loan_os =$demand ? $demand->d_loan_os :0;
        $member->d_principal = $demand ? $demand->d_principal :0;
        $member->d_last_principal =$demand ? $demand->d_last_principal :0;
        $member->d_int =$demand ? $demand->d_int :0;
        $member->d_int_rate =$demand ? $demand->d_int_rate :0;
        $member->d_last_int =$demand ? $demand->d_last_int :0;
        $member->d_others = $demand ? $demand->d_others :0;
        $member->f_os = $demand ? $demand->f_os :0;
          $member->p_int = $demand ? $demand->p_int :0;
        $member->f_pri =$demand ? $demand->f_pri :0;
        $member->f_int =$demand ? $demand->f_int :0;
         $member->f_p_int =$demand ? $demand->f_p_int :0;
        $member->f_old_pri =$demand ? $demand->f_old_pri :0;
        $member->f_old_int = $demand ? $demand->f_old_int :0;
        $member->old_thrift =$demand ? $demand->old_thrift :0;
        $member->d_insurance = $demand ? $demand->d_insurance :0;
        $member->old_ins =$demand ? $demand->old_ins :0;
        $member->d_total =$demand ? $demand->d_total :0;
        $result[$key] = $member;
    }
    
    $this->set(compact('members')); 

    if(isset($_POST['postvalue'])){
        $postvalue = $this->request->getData('postvalue');
        foreach($postvalue as $key=>$value){
           $payment['tot_pay'] = $value['amt_recover'];
           $calc['total_amt'] = $value['d_total'];
          
           $temp = $payment['tot_pay'];
           $this->loadModel('Loan');
           $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$value['mem_no']]] );
           $loano  = $query->first(); 
           $calc['cur_os'] = $loano['loan_os_amt'];
           $calc['cur_f_os'] = $loano['f_os'];
           $calc['curr_instalment'] = $loano['curr_instalment'];
           
           if($payment['tot_pay']=="" || $payment['tot_pay']==0)
           {
            $payment['rec_no']=0; 
           }
           else{
            $re=$re+1;
            $payment['rec_no']=$re;
           }
           
   if($temp>0)
          {
           $temp=$temp-$value['d_others'];
           if($temp>=0)
           {
            $payment['others'] = $value['d_others'];  
           }
           else{
            $payment['others'] = $value['d_others'] + $temp;
           }
          }
          else{
            $payment['others'] = 0;
          }
          
          if($temp>0)
          {
           $temp=$temp-$value['old_ins'];
           if($temp>=0)
           {
            $payment['old_ins'] = $value['old_ins']; 
             $calc['_old_ins'] = 0;
           }
           else{
           
            $payment['old_ins'] = $value['old_ins'] + $temp;
            $calc['_old_ins'] = $value['old_ins'] - $payment['old_ins'];
           }
          }
          else{
            $payment['old_ins'] = 0;
             $calc['_old_ins'] = $value['old_ins'];
          }


          if($temp>0)
          {
           $temp=$temp-$value['d_insurance'];
           if($temp>=0)
           {
            $payment['insurance'] = $value['d_insurance']; 
             $calc['_insurance'] = 0;
           }
           else{
           
            $payment['insurance'] = $value['d_insurance'] + $temp;
            $calc['_insurance'] = $value['d_insurance'] - $payment['insurance'];
           }
          }
          else{
            $payment['insurance'] = 0;
             $calc['_insurance'] = $value['d_insurance'];
          }

 if($temp>0)
          {
           $temp=$temp-$value['p_int'];
           if($temp>=0)
           {
            $payment['p_int'] = $value['p_int'];  
            $calc['_p_int'] = 0;
           }
           else{
            $payment['p_int'] = $value['p_int'] + $temp;
            $calc['_p_int'] = $value['p_int'] - $payment['p_int'];
           }
          }
          else{
            $payment['p_int'] = 0;
            $calc['_p_int'] = $value['p_int'];
          }


          if($temp>0)
          {
           $temp=$temp-$value['d_last_int'];
           if($temp>=0)
           {
            $payment['last_int'] = $value['d_last_int'];  
            $calc['_last_int'] = 0;
           }
           else{
            $payment['last_int'] = $value['d_last_int'] + $temp;
            $calc['_last_int'] = $value['d_last_int'] - $payment['last_int'];
           }
          }
          else{
            $payment['last_int'] = 0;
            $calc['_last_int'] = $value['d_last_int'];
          }


          if($temp>0)
          {
           $temp=$temp-$value['d_int'];
           if($temp>=0)
           {
            $payment['loan_int_amt'] = $value['d_int'];  
            $calc['_loan_int_amt'] = 0;
           }
           else{
            $payment['loan_int_amt'] = $value['d_int'] + $temp;
            $calc['_loan_int_amt'] = $value['d_int'] - $payment['loan_int_amt'];
           }
          }
          else{
            $payment['loan_int_amt'] = 0;
            $calc['_loan_int_amt'] = $value['d_int'];
          }




          if($temp>0)
          {
           $temp=$temp-$value['d_last_principal'];
           if($temp>=0)
           {
            $payment['last_principal'] = $value['d_last_principal'];  
            $calc['_last_principal'] = 0;
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal']; 
           }
           else{
            $payment['last_principal'] = $value['d_last_principal'] + $temp;
            $calc['_last_principal'] = $value['d_last_principal'] - $payment['last_principal'];
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal'];
           }
          }
          else{
            $payment['last_principal'] = 0;
            $calc['_last_principal'] = $value['d_last_principal'];
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal'];
          }

          if($temp>0)
          {
           $temp=$temp-$value['d_principal'];
           if($temp>=0)
           {
            $payment['loan_pri_amt'] = $value['d_principal'];  
            $calc['_loan_pri_amt'] = 0;
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
           }
           else{
            $payment['loan_pri_amt'] = $value['d_principal'] + $temp;
            $calc['_loan_pri_amt'] = $value['d_principal'] - $payment['loan_pri_amt'];
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
           }
          }
          else{
            $payment['loan_pri_amt'] = 0;
            $calc['_loan_pri_amt'] = $value['d_principal'];
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
          }
          
          $calc['ex'] = $calc['loan_os'];
          
          if($temp>0)
          {
           $temp=$temp-$value['old_thrift'];
           if($temp>=0)
           {
            $payment['old_thrift'] = $value['old_thrift']; 
             $calc['_old_thrift'] = 0;
           }
           else{
           
            $payment['old_thrift'] = $value['old_thrift'] + $temp;
            $calc['_old_thrift'] = $value['old_thrift'] - $payment['old_thrift'];
           }
          }
          else{
            $payment['old_thrift'] = 0;
             $calc['_old_thrift'] = $value['old_thrift'];
          }


          if($temp>0)
          {
           $temp=$temp-$value['d_thrift'];
           if($temp>=0)
           {
            $payment['thrift_amt'] = $value['d_thrift']; 
             $calc['_thrift_amt'] = 0;
           }
           else{
           
            $payment['thrift_amt'] = $value['d_thrift'] + $temp;
            $calc['_thrift_amt'] = $value['d_thrift'] - $payment['thrift_amt'];
           }
          }
          else{
            $payment['thrift_amt'] = 0;
             $calc['_thrift_amt'] = $value['d_thrift'];
          }

        
          if($temp>0)
          {
           $temp=$temp-$calc['loan_os'];
           if($temp>=0)
           {
            $payment['os_pay'] = $calc['ex'];  
            $calc['loan_os'] = 0;
           }
           else{
            $payment['os_pay'] = $calc['ex']+$temp;  
            $calc['loan_os'] = $calc['ex']-$payment['os_pay'];
           }
          }
          else{
            $payment['os_pay'] = 0;  
            $calc['loan_os'] = $calc['ex'];
          }

  if($temp>0)
          {
            $this->loadModel('Member');
            $query = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.mem_no'=>$value['mem_no']]] );
            $d  = $query->first(); 
            $calc['due_os']= $d['due_os']+$payment['os_pay'];
            $calc['due_f_os']= $d['due_f_os']+$payment['f_os_pay'];
            $calc['due_by'] =  $d['due_by'];
  $payment['thrift_amt'] = $payment['thrift_amt'] + $temp;
  $payment['due_by']=0;
          }
          else{
            $this->loadModel('Member');
            $query = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.mem_no'=>$value['mem_no']]] );
            $d  = $query->first(); 
            $calc['due_os']= $d['due_os']+$payment['os_pay'];
            $calc['due_by'] =  $d['due_by'];
            $payment['due_by']=0;
          }
          $due['old_due_int'] = $calc['_loan_int_amt'] + $calc['_last_int']+$calc['_p_int'];
          $due['old_due_pri'] = $calc['_loan_pri_amt'] + $calc['_last_principal'];
           $due['old_thrift'] = $calc['_old_thrift'] + $calc['_thrift_amt'];
            $due['old_ins'] = $calc['_old_ins'] + $calc['_insurance'];
          $payment['thrift_amt']=$payment['thrift_amt']+$payment['old_thrift'];
           $payment['insurance']=$payment['insurance']+$payment['old_ins'];
          $payment['mem_no'] = $value['mem_no'];
          $payment['share_amt'] = 0;
          $payment['payment_month'] = $value['month'];
          $payment['payment_year'] = $value['year'];
          $payment['paid_on'] = $added_on;
          $payment['paid_by'] = "Admin";
         // print "<pre>";
          //print_r($payment);
          //print_r($calc);
          //die();
          
          $this->loadModel('Thrift');
          $query = $this->Thrift->find('all', ['conditions' => ['Thrift.is_deleted' => 0,'Thrift.mem_no'=>$payment['mem_no']]] );
          $thrift  = $query->first(); 
          $calc['total_t'] =  $thrift['tot_thrift'];
$calc['tot_thrift'] = $calc['total_t'] + $payment['thrift_amt'] ;

          $th_u = TableRegistry::get("Thrift");
$query = $th_u->query();
            $result = $query->update()
                    ->set(['tot_thrift' => $calc['tot_thrift']])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();

          $this->loadModel('Payment');
            $new = $this->Payment->newEntity();
            $this->Payment->patchEntity($new,$payment);
            $this->Payment->save($new);

            $member = TableRegistry::get("Member");
$query = $member->query();
            $result = $query->update()
                    ->set(['old_due_int' => $due['old_due_int'],'old_due_pri'=>$due['old_due_pri'],'old_thrift'=>$due['old_thrift'],'old_ins'=>$due['old_ins'],'due_os'=>$calc['due_os'],'due_by'=>$calc['due_by']])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();
                    if($calc['loan_os']<=0){
                        $calc['loan_principle_amt']=0;
                        $calc['loan_os']=0;
                        
                      }
                      else{
                        $calc['loan_principle_amt']=$value['d_principal'];
                        
                      }
             
                    $loan = TableRegistry::get("Loan");
$query = $loan->query();
            $result = $query->update()
                    ->set(['loan_os_amt' => $calc['loan_os'],'loan_principle_amt' => $calc['loan_principle_amt'],'curr_instalment'=> $calc['curr_instalment']+1])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();
    
        }
        $this->set('new', $new);
        $this->Flash->success(__('Recovered Amount Saved Successfully'));
        return $this->redirect(['action' => 'recover']);
     //   print "<pre>";
      //  print_r($postvalue); 
        //die();
    }
}

}
public function revrecover()
    {
        $this->loadModel('Member');
$mem_no = $this->Member->find('list', array( 'keyField' => 'mem_no', 'valueField' => 'mem_no' ));
$this->set('mem_no',$mem_no);
if ($this->request->is('post')) {
    $month = $this->request->getData('month');
    $this->set('month',$month);
    $year = $this->request->getData('year');
    $this->set('year',$year);
    
        $member_nm = $this->request->getData('mem_no');
        $this->set('member_nm',$member_nm);
    $this->loadModel('Member');
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.mem_no'=>$member_nm]] );
    $this->set(compact('members'));
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Payment');
        $query = $this->Payment->find('all', ['conditions' => ['Payment.is_deleted'=>0,'Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
        $payment  = $query->first(); 
        $re =$payment ? $payment->mem_no :0;
    }
    if($re!=0) 
    {
        $this->Flash->success(__('Selected Month and Year  Payment Already Recovered'));
        return $this->redirect(['action' => 'revrecover']);
    }
    $this->loadModel('Payment');
    $rec_no = $this->Payment->find()
->select(['rec_no' => 'MAX(Payment.rec_no)']);
$rec_no = $rec_no->first();
$re = $rec_no->rec_no;

    $result = array();
    foreach($members as $key=>$member){
        $mem_no= $member->mem_no;
        $this->loadModel('Demand');
        $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
        $demand  = $query->first(); 
        $member->d_thrift =$demand ? $demand->d_thrift :0;
        $member->d_loan_os =$demand ? $demand->d_loan_os :0;
        $member->d_principal = $demand ? $demand->d_principal :0;
        $member->d_last_principal =$demand ? $demand->d_last_principal :0;
        $member->d_int =$demand ? $demand->d_int :0;
        $member->d_last_int =$demand ? $demand->d_last_int :0;
        $member->d_others = $demand ? $demand->d_others :0;
        $member->d_insurance =$demand ? $demand->d_insurance :0;
        $member->d_total =$demand ? $demand->d_total :0;
        $result[$key] = $member;
    }
    
    $this->set(compact('members')); 
    if(isset($_POST['postvalue'])){
        $postvalue = $this->request->getData('postvalue');
        foreach($postvalue as $key=>$value){
           $payment['tot_pay'] = $value['amt_recover'];
           $calc['total_amt'] = $value['total_amt'];
          
           $temp = $payment['tot_pay'];
           $this->loadModel('Loan');
           $query = $this->Loan->find('all', ['conditions' => ['Loan.is_deleted' => 0,'Loan.mem_no'=>$value['mem_no']]] );
           $loano  = $query->first(); 
           $calc['cur_os'] = $loano->loan_os_amt;
           if($payment['tot_pay']=="" || $payment['tot_pay']==0)
           {
            $payment['rec_no']=0; 
           }
           else{
            $re=$re+1;
            $payment['rec_no']=$re;
           }
           
   if($temp>0)
          {
           $temp=$temp-$value['others'];
           if($temp>=0)
           {
            $payment['others'] = $value['others'];  
           }
           else{
            $payment['others'] = $value['others'] + $temp;
           }
          }
          else{
            $payment['others'] = 0;
          }


          if($temp>0)
          {
           $temp=$temp-$value['insurance'];
           if($temp>=0)
           {
            $payment['insurance'] = $value['insurance'];  
           }
           else{
            $payment['insurance'] = $value['insurance'] + $temp;
           }
          }
          else{
            $payment['insurance'] = 0;
          }


          if($temp>0)
          {
           $temp=$temp-$value['last_int'];
           if($temp>=0)
           {
            $payment['last_int'] = $value['last_int'];  
            $calc['_last_int'] = 0;
           }
           else{
            $payment['last_int'] = $value['last_int'] + $temp;
            $calc['_last_int'] = $value['last_int'] - $payment['last_int'];
           }
          }
          else{
            $payment['last_int'] = 0;
            $calc['_last_int'] = $value['last_int'];
          }


          if($temp>0)
          {
           $temp=$temp-$value['loan_int_amt'];
           if($temp>=0)
           {
            $payment['loan_int_amt'] = $value['loan_int_amt'];  
            $calc['_loan_int_amt'] = 0;
           }
           else{
            $payment['loan_int_amt'] = $value['loan_int_amt'] + $temp;
            $calc['_loan_int_amt'] = $value['loan_int_amt'] - $payment['loan_int_amt'];
           }
          }
          else{
            $payment['loan_int_amt'] = 0;
            $calc['_loan_int_amt'] = $value['loan_int_amt'];
          }


          if($temp>=$value['thrift_amt'])
          {
           $temp=$temp-$value['thrift_amt'];
           if($temp>=0)
           {
            $payment['thrift_amt'] = $value['thrift_amt'];  
           }
           else{
            $payment['thrift_amt'] = $value['thrift_amt'] + $temp;
           }
          }
          else{
            $payment['thrift_amt'] = 0;
          }


          if($temp>0)
          {
           $temp=$temp-$value['last_principal'];
           if($temp>=0)
           {
            $payment['last_principal'] = $value['last_principal'];  
            $calc['_last_principal'] = 0;
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal']; 
           }
           else{
            $payment['last_principal'] = $value['last_principal'] + $temp;
            $calc['_last_principal'] = $value['last_principal'] - $payment['last_principal'];
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal'];
           }
          }
          else{
            $payment['last_principal'] = 0;
            $calc['_last_principal'] = $value['last_principal'];
            $calc['cur_os'] = $calc['cur_os'] - $payment['last_principal'];
          }

          if($temp>0)
          {
           $temp=$temp-$value['loan_pri_amt'];
           if($temp>=0)
           {
            $payment['loan_pri_amt'] = $value['loan_pri_amt'];  
            $calc['_loan_pri_amt'] = 0;
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
           }
           else{
            $payment['loan_pri_amt'] = $value['loan_pri_amt'] + $temp;
            $calc['_loan_pri_amt'] = $value['loan_pri_amt'] - $payment['loan_pri_amt'];
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
           }
          }
          else{
            $payment['loan_pri_amt'] = 0;
            $calc['_loan_pri_amt'] = $value['loan_pri_amt'];
            $calc['loan_os'] = $calc['cur_os'] - $payment['loan_pri_amt']; 
          }


          if($temp>0)
          {
            $calc['loan_os'] = $calc['loan_os'] - $temp;
          }        

          $due['old_due_int'] = $calc['_loan_int_amt'] + $calc['_last_int'];
          $due['old_due_pri'] = $calc['_loan_pri_amt'] + $calc['_last_principal'];
          $payment['mem_no'] = $value['mem_no'];
          $payment['share_amt'] = 0;
          $payment['payment_month'] = $value['month'];
          $payment['payment_year'] = $value['year'];
          $payment['paid_on'] = $value['added_on'];
          $payment['paid_by'] = "Admin";

          $this->loadModel('Thrift');
          $query = $this->Thrift->find('all', ['conditions' => ['Thrift.is_deleted' => 0,'Thrift.mem_no'=>$payment['mem_no']]] );
          $thrift  = $query->first(); 
          $calc['total_t'] =  $thrift->tot_thrift;
$calc['tot_thrift'] = $calc['total_t'] + $payment['thrift_amt'] ;

          $th_u = TableRegistry::get("Thrift");
$query = $th_u->query();
            $result = $query->update()
                    ->set(['tot_thrift' => $calc['tot_thrift']])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();

          $this->loadModel('Payment');
            $new = $this->Payment->newEntity();
            $this->Payment->patchEntity($new,$payment);
            $this->Payment->save($new);

            $member = TableRegistry::get("Member");
$query = $member->query();
            $result = $query->update()
                    ->set(['old_due_int' => $due['old_due_int'],'old_due_pri'=>$due['old_due_pri']])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();

                    $loan = TableRegistry::get("Loan");
$query = $loan->query();
            $result = $query->update()
                    ->set(['loan_os_amt' => $calc['loan_os']])
                    ->where(['mem_no' => $payment['mem_no']])
                    ->execute();
    
        }
        
        $this->set('new', $new);
        $this->Flash->success(__('Recovered Amount Saved Successfully'));
        return $this->redirect(['action' => 'revrecover']);
     //   print "<pre>";
      //  print_r($postvalue); 
        //die();
    }
}

}




public function gen()
{
$this->loadModel('Division');
$divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ));
$this->set('divisions',$divisions);
$this->loadModel('Section');
$sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
$this->set('sections',$sections);

if ($this->request->is('post')) {
$division = $this->request->getData('division');
$this->set('division',$division);
$section = $this->request->getData('section');
$this->set('section',$section);
$month = $this->request->getData('month');
$this->set('month',$month);
$year = $this->request->getData('year');
$this->set('year',$year);

$div = $this->request->getData('division');
$this->loadModel('Division');
$div = $this->Division->find('all', ['conditions' => ['Division.division' => $div ]  ]);
$row = $div->first();
$division_mem_no = $row['id'];


    $this->loadModel('MapDivisionSection');
    $sec = $this->MapDivisionSection->find('all', ['conditions' => ['MapDivisionSection.division_id' => $division_mem_no], 'contain' => ['Section'] ] );
    // Iterate it
    $s=0;
    $result = array();
foreach($sec as $key=>$postObject) {
//echo $postObject->section_id;
$this->loadModel('Section');
$sections = $this->Section->find('all', ['conditions' => ['Section.id' => $postObject->section_id ]  ]);
foreach($sections as $key=>$new) {
    $postObject->section = $new->section;
    }
    $result[$key] = $postObject;  
}
$this->set(compact('sec')); 
$this->loadModel('Member');
if($section=="")
{
$members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
$this->set(compact('members'));
}
else{
    $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
$this->set(compact('members'));
}
foreach($members as $key=>$member){
    $mem_no= $member->mem_no;
    $this->loadModel('Payment');
    $query = $this->Payment->find('all', ['conditions' => ['Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
    $payment  = $query->first(); 
    $re =$payment ? $payment->mem_no :0;
}
if($re!=0) 
{
    $this->Flash->success(__('Selected Month and Year  Payment Already Recovered , It Cannot be generated.'));
    return $this->redirect(['action' => 'generate']);
}
$result = array();
foreach($members as $key=>$member){
    $mem_no= $member->mem_no;
    $this->loadModel('Deman');
    $query = $this->Deman->find('all', ['conditions' => ['Deman.mem_no'=>$mem_no]] );
    $demand  = $query->first(); 
    //Loan Principle
    $member->loan_os =$demand ? $demand->loan_os :0;
    $member->pri =$demand ? $demand->pri :0;
    $member->per =$demand ? $demand->per :0;
    $member->inter =$demand ? $demand->inter :0;
    $member->f_os =$demand ? $demand->f_os :0;
    $member->f_pri =$demand ? $demand->f_pri :0;
    $member->f_int =$demand ? $demand->f_int :0;
    $member->td =$demand ? $demand->td :0;
    $member->tot =$demand ? $demand->tot :0;
    $result[$key] = $member;
}
$this->set(compact('members'));

}

}

public function old()
{
    $this->loadModel('Division');
    $divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ,'order' => 'Division.division ASC'));
    $this->set('divisions',$divisions);
    $this->loadModel('Section');
    $sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
    $this->set('sections',$sections);
    
    if ($this->request->is('post')) {
        
        $month = $this->request->getData('month');
        $this->set('month',$month);
        $year = $this->request->getData('year');
        $this->set('year',$year);
        $added_on = $this->request->getData('added_on');
        $this->set('added_on',$added_on);
            $division = $this->request->getData('division');
            $this->set('division',$division);
            $section = $this->request->getData('section');
            $this->set('section',$section);
            if(!isset($_POST['postvalue']))
            {
            if($month=="" || $year=="") 
        {
            $this->Flash->success(__('Select Month and Year'));
            return $this->redirect(['action' => 'old']);
        }
            }
            $div = $this->request->getData('division');
            $this->loadModel('Division');
            $div = $this->Division->find('all', ['conditions' => ['Division.division' => $div ]  ]);
            $row = $div->first();
            $division_mem_no = $row['id'];
            $address=$row['address'];
            $this->set('address',$address);
         
                $this->loadModel('MapDivisionSection');
                $sec = $this->MapDivisionSection->find('all', ['conditions' => ['MapDivisionSection.division_id' => $division_mem_no], 'contain' => ['Section'] ] );
                // Iterate it
                $s=0;
                $result = array();
        foreach($sec as $key=>$postObject) {
        //echo $postObject->section_id;
            $this->loadModel('Section');
            $sections = $this->Section->find('all', ['conditions' => ['Section.id' => $postObject->section_id ]  ]);
            foreach($sections as $key=>$new) {
                $postObject->section = $new->section;
                }
                $result[$key] = $postObject;  
        }
        $this->set(compact('sec')); 
        $this->loadModel('Member');
        if($division!="" && $section=="")
        {
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
        $this->set(compact('members'));
        }
        elseif($division!="" && $section!=""){
            $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
        $this->set(compact('members'));
        }
         elseif($division=="" && $section!=""){
            $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
        $this->set(compact('members'));
        }
        else{
        $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
        $this->set(compact('members'));
        }
      /*   foreach($members as $key=>$member){
            $mem_no= $member->mem_no;
        $this->loadModel('Demand');
        $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
        $demand  = $query->first(); 
        $re =$demand ? $demand->mem_no :0;
        if($re==0) 
    {
        $this->Flash->success(__('Selected Month and Year  Demand Not Generated'));
        return $this->redirect(['action' => 'old']);
    }
        }
       */
    
        $result = array();
        foreach($members as $key=>$member){
            $mem_no= $member->mem_no;
            $this->loadModel('Demand');
            $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
            $demand  = $query->first(); 
            $member->d_thrift =$demand ? $demand->d_thrift :0;
            $member->d_loan_no =$demand ? $demand->d_loan_no :0;
             $member->d_loan_amount =$demand ? $demand->d_loan_amount :0;
            $member->d_loan_os =$demand ? $demand->d_loan_os :0;
            $member->d_principal = $demand ? $demand->d_principal :0;
            $member->d_last_principal =$demand ? $demand->d_last_principal :0;
            $member->d_int =$demand ? $demand->d_int :0;
            $member->d_int_rate =$demand ? $demand->d_int_rate :0;
            $member->d_last_int =$demand ? $demand->d_last_int :0;
            $member->d_others = $demand ? $demand->d_others :0;
            $member->f_os = $demand ? $demand->f_os :0;
              $member->p_int = $demand ? $demand->p_int :0;
            $member->f_pri =$demand ? $demand->f_pri :0;
            $member->f_int =$demand ? $demand->f_int :0;
             $member->f_p_int =$demand ? $demand->f_p_int :0;
            $member->f_old_pri =$demand ? $demand->f_old_pri :0;
            $member->f_old_int = $demand ? $demand->f_old_int :0;
            $member->loan_instalment =$demand ? $demand->d_instalment :0;
            $member->curr_instalment =$demand ? $demand->d_curr_instalment :0;
            $member->old_thrift =$demand ? $demand->old_thrift :0;
             $member->d_insurance =$demand ? $demand->d_insurance :0;
             $member->old_ins = $demand ? $demand->old_ins :0;
            $member->d_total =$demand ? $demand->d_total :0;
            $result[$key] = $member;
        }
     
        $this->set(compact('members')); 

}
}

public function pay()
{
    $this->loadModel('Division');
    $divisions = $this->Division->find('list', array( 'keyField' => 'division', 'valueField' => 'division' ));
    $this->set('divisions',$divisions);
    $this->loadModel('Section');
    $sections = $this->Section->find('list', array( 'keyField' => 'section', 'valueField' => 'section' ));
    $this->set('sections',$sections);
    
    if ($this->request->is('post')) {
        $month = $this->request->getData('month');
        $this->set('month',$month);
        $year = $this->request->getData('year');
        $this->set('year',$year);
        
            $division = $this->request->getData('division');
            $this->set('division',$division);
            $section = $this->request->getData('section');
            $this->set('section',$section);
            if(!isset($_POST['postvalue']))
            {
            if($month=="" || $year=="") 
        {
            $this->Flash->success(__('Select Month and Year'));
            return $this->redirect(['action' => 'old']);
        }
            }
            $this->loadModel('Member');
            if($division!="" && $section=="")
            {
            $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division]] );
            $this->set(compact('members'));
            }
            elseif($division!="" && $section!=""){
                $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.division'=>$division,'Member.section'=>$section]] );
            $this->set(compact('members'));
            }
             elseif($division=="" && $section!=""){
                $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0,'Member.section'=>$section]] );
            $this->set(compact('members'));
            }
            else{
            $members = $this->Member->find('all', ['conditions' => ['Member.is_deleted' => 0]] );
            $this->set(compact('members'));
            }

          /*   foreach($members as $key=>$member){
                $mem_no= $member->mem_no;
                $this->loadModel('Payment');
                $query = $this->Payment->find('all', ['conditions' => ['Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
                $payment  = $query->first(); 
                $re =$payment ? $payment->mem_no :0;
                if($re==0) 
            {
                $this->Flash->success(__('Selected Month and Year Payment Not Recovered'));
                return $this->redirect(['action' => 'pay']);
            }
            } */
        $result = array();
        foreach($members as $key=>$member){
            $mem_no= $member->mem_no;
            $this->loadModel('Demand');
            $query = $this->Demand->find('all', ['conditions' => ['Demand.mem_no'=>$mem_no,'Demand.d_month'=>$month,'Demand.d_year'=>$year]] );
            $demand  = $query->first(); 
            $member->d_total =$demand ? $demand->d_total :0;
            $this->loadModel('Payment');
            $query = $this->Payment->find('all', ['conditions' => ['Payment.mem_no'=>$mem_no,'Payment.payment_month'=>$month,'Payment.payment_year'=>$year]] );
            $payment  = $query->first(); 
            $member->tot_pay =$payment ? $payment->tot_pay :0;
            $member->diff =  $member->d_total - $member->tot_pay;
            if($member->diff>=0){
                $member->due_to = $member->diff;
                $member->due_by = 0;
            }
            else{
                $member->due_to = 0;
                $member->due_by = 0-$member->diff;
            }
            $result[$key] = $member;
        }
        
        $this->set(compact('members')); 

}
}

}
?>