<commit_before><?php
class Model_Account_Loan extends Model_Account{
	
	public $transaction_deposit_type = TRA_LOAN_ACCOUNT_AMOUNT_DEPOSIT;	
	public $default_transaction_deposit_narration = "Amount submited in Loan Account {{AccountNumber}}";	

	function init(){
		parent::init();


		$this->getElement('scheme_id')->getModel()->addCondition('SchemeType','Loan');
		$this->addCondition('SchemeType','Loan');

		$this->getElement('agent_id')->destroy();
		$this->getElement('collector_id')->destroy();
		$this->getElement('Amount')->caption('Loan Amount');
		$this->getElement('CurrentInterest')->caption('Panelty');
		$this->getElement('account_type')->enum(explode(",",LOAN_TYPES))->mandatory(true);
		$this->getElement('doc_image_id')->mandatory(false);

		$this->addExpression('maturity_date')->set(function($m,$q){
			return "DATE_ADD(DATE(".$q->getField('created_at')."), INTERVAL +(".$m->add('Model_Scheme')->addCondition('id',$q->getField('scheme_id'))->fieldQuery("NumberOfPremiums")->render().") MONTH)";
		});

		$this->addExpression('dealer_monthly_date')->set(function ($m,$q){
			return $m->refSQL('dealer_id')->fieldQuery('dealer_monthly_date');
		});

		$this->addHook('beforeSave',$this);
		$this->addHook('editing',$this);
		// $this->addHook('afterAccountDebited,afterAccountCredited',array($this,'closeIfPaidCompletely'));

		$this->add('Controller_Validator');
		$this->is(array(
							'AccountNumber|to_trim|unique'
						)
				);

		$this->is('account_type','if','Loan Against Deposit','[LoanAgainstAccount_id]!');

		//$this->add('dynamic_model/Controller_AutoCreator');
	}

	function editing(){
		$this->getELement('LoanInsurranceDate')->system(true);
		// $this->getELement('LoanAgainstAccount_id')->system(true);
	}

	function beforeSave(){
		if(!$this['account_type'])
			throw $this->exception('Please Specify Account Type', 'ValidityCheck')->setField('account_type');

		if($this['account_type'] == 'Loan Against Deposit' AND !$this['LoanAgainstAccount_id']){
			throw $this->exception('For Secured Loans Another Account is must','ValidityCheck')->setField('LoanAgainstAccount_id');
		}

		if($this->loaded() and $this['account_type'] == 'Loan Against Deposit' and $this->dirty['LoanAgainstAccount_id']){
			$old_locked_account = $this->newInstance()->load($this->id);
			$old_locked_account->ref('LoanAgainstAccount_id')->unlock();
			$this->ref('LoanAgainstAccount_id')->lock();
		}

	}

	function createNewPendingAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues=null,$form=null,$created_at=null){
		$pending_account = parent::createNewPendingAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues,$form,$created_at);
		return $pending_account;
	}

	function createNewAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues=array(),$form=null, $on_date = null ){

		// AccountNumber is already comming as getNewAccountNumber from pending Account Actions.

		if(!$on_date) $on_date = $this->api->now;

		if($otherValues['LoanAgainstAccount_id']){
			$security_account = $this->add('Model_Account')->load($otherValues['LoanAgainstAccount_id']);
			$security_account->lock();
		}

		parent::createNewAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues,$form,$on_date);
		
		$this->createProcessingFeeTransaction($from_account = $otherValues['loan_from_account'], $on_date);
		
		$extra_info = json_decode($otherValues['extra_info'],true);

		if($form)
			$this->addDocumentDetails($form);
		else
			$this->addDocumentDetailsFromPending($extra_info);

		if(isset($extra_info['guarantors'])){
			$guarantors = $extra_info['guarantors'];
			foreach ($guarantors as $g) {
				$this->addGuarantor($g['id']);
			}
		}
		
		$this->createPremiums();
	}

	function createProcessingFeeTransaction($from_account, $on_date){
		$scheme = $this->ref('scheme_id');
		$ProcessingFees = $scheme['ProcessingFees'];
		$AccountCredit = $this['Amount'] - $ProcessingFees;
		
		if($scheme['ProcessingFeesinPercent']){
			$ProcessingFees = $ProcessingFees * $this['Amount'] / 100;
			$AccountCredit = $this['Amount'] - $ProcessingFees;
		}

		$transaction = $this->add('Model_Transaction');
		$transaction->createNewTransaction(TRA_LOAN_ACCOUNT_OPEN,$this->ref('branch_id'),$on_date, "Loan Account Openned ". $this['AccountNumber'], null, array('reference_id'=>$this->id));
		
		$loan_from_other_account = $this->add('Model_Account')->load($from_account);

		$transaction->addDebitAccount($this, $this['Amount']);
		$transaction->addCreditAccount($this['branch_code'] . SP . PROCESSING_FEE_RECEIVED . SP. $this['scheme_name'], $ProcessingFees);
		$transaction->addCreditAccount($loan_from_other_account, $AccountCredit);
		
		$transaction->execute();
	}

	function addDocumentDetails($form){
		$documents=$this->add('Model_Document');
		foreach ($documents as $d) {
		 	if($form[$this->api->normalizeName($documents['name'])])
		 		$this->updateDocument($documents, $form[$this->api->normalizeName($documents['name'].' value')]);
		}
	}

	function addGuarantor($member_id){
		$g=$this->add('Model_AccountGuarantor');
		$g['account_id'] = $this->id;
		$g['member_id'] = $member_id;
		$g->save();
		return $g;
	}


	function addDocumentDetailsFromPending($extra_info){

		if(!isset($extra_info['documents_feeded'])) return;
		echo "<pre>";
		print_r($extra_info);
		echo "</pre>";
		$doc_info = $extra_info['documents_feeded'];
		foreach ($doc_info as $doc_name => $value) {
			$document = $this->add('Model_Document')->loadBy('name',$doc_name);
			$this->updateDocument($document, $value);
		}
	}

	function getFirstEMIDate($return_date_string=false){
		// ??? .... $this['created_at'] with dealer_monthly_date ... relation

		$date = new MyDateTime($this['created_at']);

		$toAdd = 'P1M';

		if($this['dealer_id']){
			$dd=explode(",",$this['dealer_monthly_date']);
			$applicable_date = (int)date('d',strtotime($this['created_at']));<commit_msg>Empty document by pass<commit_after><?php
class Model_Account_Loan extends Model_Account{
	
	public $transaction_deposit_type = TRA_LOAN_ACCOUNT_AMOUNT_DEPOSIT;	
	public $default_transaction_deposit_narration = "Amount submited in Loan Account {{AccountNumber}}";	

	function init(){
		parent::init();


		$this->getElement('scheme_id')->getModel()->addCondition('SchemeType','Loan');
		$this->addCondition('SchemeType','Loan');

		$this->getElement('agent_id')->destroy();
		$this->getElement('collector_id')->destroy();
		$this->getElement('Amount')->caption('Loan Amount');
		$this->getElement('CurrentInterest')->caption('Panelty');
		$this->getElement('account_type')->enum(explode(",",LOAN_TYPES))->mandatory(true);
		$this->getElement('doc_image_id')->mandatory(false);

		$this->addExpression('maturity_date')->set(function($m,$q){
			return "DATE_ADD(DATE(".$q->getField('created_at')."), INTERVAL +(".$m->add('Model_Scheme')->addCondition('id',$q->getField('scheme_id'))->fieldQuery("NumberOfPremiums")->render().") MONTH)";
		});

		$this->addExpression('dealer_monthly_date')->set(function ($m,$q){
			return $m->refSQL('dealer_id')->fieldQuery('dealer_monthly_date');
		});

		$this->addHook('beforeSave',$this);
		$this->addHook('editing',$this);
		// $this->addHook('afterAccountDebited,afterAccountCredited',array($this,'closeIfPaidCompletely'));

		$this->add('Controller_Validator');
		$this->is(array(
							'AccountNumber|to_trim|unique'
						)
				);

		$this->is('account_type','if','Loan Against Deposit','[LoanAgainstAccount_id]!');

		//$this->add('dynamic_model/Controller_AutoCreator');
	}

	function editing(){
		$this->getELement('LoanInsurranceDate')->system(true);
		// $this->getELement('LoanAgainstAccount_id')->system(true);
	}

	function beforeSave(){
		if(!$this['account_type'])
			throw $this->exception('Please Specify Account Type', 'ValidityCheck')->setField('account_type');

		if($this['account_type'] == 'Loan Against Deposit' AND !$this['LoanAgainstAccount_id']){
			throw $this->exception('For Secured Loans Another Account is must','ValidityCheck')->setField('LoanAgainstAccount_id');
		}

		if($this->loaded() and $this['account_type'] == 'Loan Against Deposit' and $this->dirty['LoanAgainstAccount_id']){
			$old_locked_account = $this->newInstance()->load($this->id);
			$old_locked_account->ref('LoanAgainstAccount_id')->unlock();
			$this->ref('LoanAgainstAccount_id')->lock();
		}

	}

	function createNewPendingAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues=null,$form=null,$created_at=null){
		$pending_account = parent::createNewPendingAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues,$form,$created_at);
		return $pending_account;
	}

	function createNewAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues=array(),$form=null, $on_date = null ){

		// AccountNumber is already comming as getNewAccountNumber from pending Account Actions.

		if(!$on_date) $on_date = $this->api->now;

		if($otherValues['LoanAgainstAccount_id']){
			$security_account = $this->add('Model_Account')->load($otherValues['LoanAgainstAccount_id']);
			$security_account->lock();
		}

		parent::createNewAccount($member_id,$scheme_id,$branch, $AccountNumber,$otherValues,$form,$on_date);
		
		$this->createProcessingFeeTransaction($from_account = $otherValues['loan_from_account'], $on_date);
		
		$extra_info = json_decode($otherValues['extra_info'],true);

		if($form)
			$this->addDocumentDetails($form);
		else
			$this->addDocumentDetailsFromPending($extra_info);

		if(isset($extra_info['guarantors'])){
			$guarantors = $extra_info['guarantors'];
			foreach ($guarantors as $g) {
				$this->addGuarantor($g['id']);
			}
		}
		
		$this->createPremiums();
	}

	function createProcessingFeeTransaction($from_account, $on_date){
		$scheme = $this->ref('scheme_id');
		$ProcessingFees = $scheme['ProcessingFees'];
		$AccountCredit = $this['Amount'] - $ProcessingFees;
		
		if($scheme['ProcessingFeesinPercent']){
			$ProcessingFees = $ProcessingFees * $this['Amount'] / 100;
			$AccountCredit = $this['Amount'] - $ProcessingFees;
		}

		$transaction = $this->add('Model_Transaction');
		$transaction->createNewTransaction(TRA_LOAN_ACCOUNT_OPEN,$this->ref('branch_id'),$on_date, "Loan Account Openned ". $this['AccountNumber'], null, array('reference_id'=>$this->id));
		
		$loan_from_other_account = $this->add('Model_Account')->load($from_account);

		$transaction->addDebitAccount($this, $this['Amount']);
		$transaction->addCreditAccount($this['branch_code'] . SP . PROCESSING_FEE_RECEIVED . SP. $this['scheme_name'], $ProcessingFees);
		$transaction->addCreditAccount($loan_from_other_account, $AccountCredit);
		
		$transaction->execute();
	}

	function addDocumentDetails($form){
		$documents=$this->add('Model_Document');
		foreach ($documents as $d) {
		 	if($form[$this->api->normalizeName($documents['name'])])
		 		$this->updateDocument($documents, $form[$this->api->normalizeName($documents['name'].' value')]);
		}
	}

	function addGuarantor($member_id){
		$g=$this->add('Model_AccountGuarantor');
		$g['account_id'] = $this->id;
		$g['member_id'] = $member_id;
		$g->save();
		return $g;
	}


	function addDocumentDetailsFromPending($extra_info){

		if(!isset($extra_info['documents_feeded'])) return;
		// echo "<pre>";
		// print_r($extra_info);
		// echo "</pre>";
		$doc_info = $extra_info['documents_feeded'];
		foreach ($doc_info as $doc_name => $value) {
			if ($doc_name =="") continue;
			$document = $this->add('Model_Document')->loadBy('name',$doc_name);
			$this->updateDocument($document, $value);
		}
	}

	function getFirstEMIDate($return_date_string=false){
		// ??? .... $this['created_at'] with dealer_monthly_date ... relation

		$date = new MyDateTime($this['created_at']);

		$toAdd = 'P1M';

		if($this['dealer_id']){
			$dd=explode(",",$this['dealer_monthly_date']);
			$applicable_date = (int)date('d',strtotime($this['created_at']));
{'fraction_non_alphanumeric': 0.1949616648411829, 'fraction_numerical': 0.0006740247704103125, 'mean_word_length': 7.02027027027027, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 183, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6243732', 'n_tokens_mistral': 4341, 'n_tokens_neox': 3870, 'n_words': 471}