<?php
require 'config_db.php';
$data = json_decode(file_get_contents('php://input'), true);
if ($data['uid'] == '' or $data['cus_id'] == '') {
    $returnArr = array("ResponseCode" => "401", "Result" => "false", "ResponseMsg" => "Something Went Wrong!");
} else {

    $uid = strip_tags(mysqli_real_escape_string($con, $data['uid']));
    $cus_id = strip_tags(mysqli_real_escape_string($con, $data['cus_id']));
    $receipt_date = strip_tags(mysqli_real_escape_string($con, $data['receipt_date']));
    $receipt_number = strip_tags(mysqli_real_escape_string($con, $data['receipt_number']));
    $cus_type = strip_tags(mysqli_real_escape_string($con, $data['cus_type']));

    $today_paid_amount = strip_tags(mysqli_real_escape_string($con, $data['today_paid_amount']));
    
    $current_time = strip_tags(mysqli_real_escape_string($con, $data['current_time']));
    $mode = strip_tags(mysqli_real_escape_string($con, $data['mode']));

    

    //chit transaction
    if ($cus_type == "chit") {
        $balance_amount = strip_tags(mysqli_real_escape_string($con, $data['balance_amount']));

        $multiply_number = strip_tags(mysqli_real_escape_string($con, $data['multiply_number']));
        $scheme = strip_tags(mysqli_real_escape_string($con, $data['scheme']));
        $installment_number = strip_tags(mysqli_real_escape_string($con, $data['installment_number']));
        $installment_balance_amount = strip_tags(mysqli_real_escape_string($con, $data['installment_balance_amount']));
        $prev_paid_amount = strip_tags(mysqli_real_escape_string($con, $data['prev_paid_amount']));
        $prev_balance_amount = strip_tags(mysqli_real_escape_string($con, $data['prev_balance_amount']));

        $temp_today_paid_amount = $today_paid_amount;

        if($mode==1){

            $receipt_number = getLastChitReceiptNumber($con);

            if ($installment_balance_amount > $temp_today_paid_amount) {
                $installment_balance_amount = $installment_balance_amount - $temp_today_paid_amount;
    
                $update_prev_transaction_status = "update transaction_chit set  `status`='0'
                                                        where customer_id = '$cus_id' order by id desc limit 1";
                $con->query($update_prev_transaction_status);
    
                $new_transaction = "insert into transaction_chit
                                                (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,`current_installment_number`,`current_installment_amount`,
                                                `today_paid_amount`,`balance_amount`,`prev_paid_amount`,`prev_balance_amount`,`status`,
                                                `created_time`,`updated_time`)values
                                                ('$uid','$cus_id','$receipt_date','$receipt_number','$installment_number','$temp_today_paid_amount',
                                                '$today_paid_amount','$balance_amount','$prev_paid_amount','$prev_balance_amount','1',
                                                '$current_time','$current_time')";
                $final_result = $con->query($new_transaction);
    
            }
            else if($installment_balance_amount == $temp_today_paid_amount){

                $update_prev_transaction_status = "update transaction_chit set  `status`='0'
                                                        where customer_id = '$cus_id' order by id desc limit 1";
                $con->query($update_prev_transaction_status);

                $new_transaction = "insert into transaction_chit
                                                (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,`current_installment_number`,`current_installment_amount`,
                                                `today_paid_amount`,`balance_amount`,`prev_paid_amount`,`prev_balance_amount`,`status`,
                                                `created_time`,`updated_time`)values
                                                ('$uid','$cus_id','$receipt_date','$receipt_number','$installment_number','$temp_today_paid_amount',
                                                '$today_paid_amount','$balance_amount','$prev_paid_amount','$prev_balance_amount','1',
                                                '$current_time','$current_time')";
                $result = $con->query($new_transaction);

                if($result){
                    $installment_number = $installment_number + 1;
                    $installment_qry = "SELECT installment_amount 
                                            FROM installment_entry 
                                            where scheme=$scheme and installment_number=$installment_number";
                    $installment_qry = $con->query($installment_qry);

                    $installment_qry = $installment_qry->fetch_assoc();

                    if(isset($installment_qry['installment_amount'])){
                        $installment_balance_amount = $installment_qry['installment_amount'] * $multiply_number;
                    }else{
                        $installment_number = 0;
                        $installment_balance_amount = 0.00;
                    }

                    //update chit customer table
                    $final_result = true;
                }
    
            } 
            else if($installment_balance_amount < $temp_today_paid_amount){

                $update_prev_transaction_status = "update transaction_chit set  `status`='0'
                                                        where customer_id = '$cus_id' order by id desc limit 1";
                $con->query($update_prev_transaction_status);

                $temp_today_paid_amount = $temp_today_paid_amount - $installment_balance_amount;

                $new_transaction = "insert into transaction_chit
                                                (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,`current_installment_number`,`current_installment_amount`,
                                                `today_paid_amount`,`balance_amount`,`prev_paid_amount`,`prev_balance_amount`,`status`,
                                                `created_time`,`updated_time`)values
                                                ('$uid','$cus_id','$receipt_date','$receipt_number','$installment_number','$installment_balance_amount',
                                                '$today_paid_amount','$balance_amount','$prev_paid_amount','$prev_balance_amount','0',
                                                '$current_time','$current_time')";
                $result = $con->query($new_transaction);

                $installment_qry = "SELECT installment_number,installment_amount 
                                            FROM installment_entry 
                                            where scheme=$scheme and installment_number>$installment_number";
                $installment_qry = $con->query($installment_qry);

                $current_installment_amount = 0.00;
                while($temp_today_paid_amount!=0.00 && $row=$installment_qry->fetch_assoc() ){
                    $installment_number = $row['installment_number'];
                    $current_installment_amount = $row['installment_amount'] * $multiply_number;

                    $current_payment = 0.00;

                    if($current_installment_amount >= $temp_today_paid_amount){
                        $current_installment_amount = $current_installment_amount - $temp_today_paid_amount;
                        $current_payment = $temp_today_paid_amount;
                        $temp_today_paid_amount = 0.00;
                    }
                    else{
                        $current_payment = $current_installment_amount;
                        $temp_today_paid_amount = $temp_today_paid_amount - $current_installment_amount;
                        $current_installment_amount = 0.00;
                    }

                    $status = 0;
                    if($temp_today_paid_amount==0.00){
                        $status = 1;
                    }

                    $new_transaction = "insert into transaction_chit
                                                (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,`current_installment_number`,`current_installment_amount`,
                                                `today_paid_amount`,`balance_amount`,`prev_paid_amount`,`prev_balance_amount`,`status`,
                                                `created_time`,`updated_time`)values
                                                ('$uid','$cus_id','$receipt_date','$receipt_number','$installment_number','$current_payment',
                                                '$today_paid_amount','$balance_amount','$prev_paid_amount','$prev_balance_amount','$status',
                                                '$current_time','$current_time')";
                    $result = $con->query($new_transaction);



                    //update chit customer table
                    $final_result = true;

                }

                if($current_installment_amount == 0.00){
                    $installment_number = $installment_number + 1;
                    $installment_qry = "SELECT installment_amount 
                                            FROM installment_entry 
                                            where scheme=$scheme and installment_number=$installment_number";
                    $installment_qry = $con->query($installment_qry);

                    $installment_qry = $installment_qry->fetch_assoc();

                    if(isset($installment_qry['installment_amount'])){
                        // $installment_balance_amount = floatval($installment_qry['installment_amount']) * floatval($multiply_number);
                        $installment_balance_amount = $installment_qry['installment_amount'] * $multiply_number ;

                    }
                    else{
                        $installment_number = 0;
                        $installment_balance_amount = 0.00;
                    }

                    
                }
                

                // $installment_balance_amount = $current_installment_amount;

                //update chit customer table
                $final_result = true;
                
            }
    
            //update chit customer
            if($final_result){
                if ($installment_number == 0) {
                    $payment_status = 3;
                } else {
                    $payment_status = 2;
                }
    
                $update_customer_sql = "update customers_chit set 
                                            `installment_number`='$installment_number',`installment_balance_amount`='$installment_balance_amount',
                                            `payment_status`='$payment_status',`paid_time`='$current_time',
                                            `updated_time`='$current_time'
                                        where id = '$cus_id'";
    
                $final = $con->query($update_customer_sql);
    
                if ($final) {
                    $returnArr = array("ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "New Entry Success");
                } else {
                    $returnArr = array("ResponseCode" => "201", "Result" => "false", "ResponseMsg" => "Failure");
    
                }
            }
        }
        
    }
    //finance transaction
    else if ($cus_type == "finance") {

        if ($mode == 1) {

            $receipt_number = getLastFinanceReceiptNumber($con);

            $update_prev_transaction_status = "update transaction_finance set `status`='0'
                                                        where customer_id = '$cus_id' order by id desc limit 1";
            $con->query($update_prev_transaction_status);

            $new_transaction = "insert into transaction_finance
                                            (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,
                                            `today_paid_amount`,`created_time`,`updated_time`)
                                        values
                                            ('$uid','$cus_id','$receipt_date','$receipt_number',
                                             '$today_paid_amount','$current_time','$current_time')";
            $resultt = $con->query($new_transaction);

            if ($resultt) {

                $update_customer_sql = "update customers_finance set 
                                                        `payment_status`='2',`paid_time`='$current_time',`updated_time`='$current_time'
                                                where id = '$cus_id'";

                $final = $con->query($update_customer_sql);

                if ($final) {
                    $returnArr = array("ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "New Entry Success");
                } else {
                    $returnArr = array("ResponseCode" => "201", "Result" => "false", "ResponseMsg" => "Failure");

                }

            }
        }

    }
    //Interest transaction
    else if ($cus_type == "interest") {

        if ($mode == 1) {

            $receipt_number = getLastInterestReceiptNumber($con);

            $update_prev_transaction_status = "update transaction_interest set `status`='0'
                                                        where customer_id = '$cus_id' order by id desc limit 1";
            $con->query($update_prev_transaction_status);

            $new_transaction = "insert into transaction_interest
                                            (`created_by`,`customer_id`,`receipt_date`,`receipt_number`,
                                            `today_paid_amount`,`created_time`,`updated_time`)
                                        values
                                            ('$uid','$cus_id','$receipt_date','$receipt_number',
                                             '$today_paid_amount','$current_time','$current_time')";
            $resultt = $con->query($new_transaction);

            if ($resultt) {

                $update_customer_sql = "update customers_interest set 
                                                    `payment_status`='2',`paid_time`='$current_time',`updated_time`='$current_time'
                                                where id = '$cus_id'";

                $final = $con->query($update_customer_sql);

                if ($final) {
                    $returnArr = array("ResponseCode" => "200", "Result" => "true", "ResponseMsg" => "New Entry Success");
                } else {
                    $returnArr = array("ResponseCode" => "201", "Result" => "false", "ResponseMsg" => "Failure");

                }

            }
        }

    }



}

// function setChitCustomerTransactionTable(
//     $con,
//     $uid,
//     $cus_id,
//     $receipt_date,
//     $receipt_number,
//     $temp_today_paid_amount,
//     $today_paid_amount,
//     $balance_amount,
//     $multiply_number,
//     $scheme,
//     $installment_number,
//     $installment_balance_amount,
//     $prev_paid_amount,
//     $prev_balance_amount
// )
// {

//     return true;
// }


function getLastChitReceiptNumber($con)
{
	$last_receipt_number = $con->query("SELECT receipt_number FROM transaction_chit ORDER BY id DESC LIMIT 1");
	$last_receipt_number = $last_receipt_number->fetch_assoc();
	$count = isset($last_receipt_number['receipt_number']);

	if ($count) {
		$receipt_number = $last_receipt_number['receipt_number'];
		$length = 7;
		$rec_text_number = explode("-", $receipt_number);
		$no = $rec_text_number[2] + 1;
		$no = substr(str_repeat(0, $length) . $no, -$length);
		$rec_no = "REC" . "-C-" . $no;
	} else {
		$rec_no = "REC" . "-C-" . "0000001";
	}
	return $rec_no;
}

function getLastFinanceReceiptNumber($con)
{
	$last_receipt_number = $con->query("SELECT receipt_number FROM transaction_finance ORDER BY id DESC LIMIT 1");
	$last_receipt_number = $last_receipt_number->fetch_assoc();
	$count = isset($last_receipt_number['receipt_number']);

	if ($count) {
		$receipt_number = $last_receipt_number['receipt_number'];
		$length = 7;
		$rec_text_number = explode("-", $receipt_number);
		$no = $rec_text_number[2] + 1;
		$no = substr(str_repeat(0, $length) . $no, -$length);
		$rec_no = "REC" . "-F-" . $no;
	} else {
		$rec_no = "REC" . "-F-" . "0000001";
	}
	return $rec_no;
}

function getLastInterestReceiptNumber($con)
{
	$last_receipt_number = $con->query("SELECT receipt_number FROM transaction_interest ORDER BY id DESC LIMIT 1");
	$last_receipt_number = $last_receipt_number->fetch_assoc();
	$count = isset($last_receipt_number['receipt_number']);

	if ($count) {
		$receipt_number = $last_receipt_number['receipt_number'];
		$length = 7;
		$rec_text_number = explode("-", $receipt_number);
		$no = $rec_text_number[2] + 1;
		$no = substr(str_repeat(0, $length) . $no, -$length);
		$rec_no = "REC" . "-I-" . $no;
	} else {
		$rec_no = "REC" . "-I-" . "0000001";
	}
	return $rec_no;
}

echo json_encode($returnArr);
?>