<?php
set_time_limit(0);
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);
require_once("/home/fundbridge/crons.ballng.com/db.php");
require_once("/home/fundbridge/crons.ballng.com/email.php");
 
 
$penaltyChargePercent = floatval(mysqli_fetch_assoc(mysqli_query($conn, "select meta_value from settings where meta_key = 'penalty_charge' limit 1"))['meta_value']);
$penaltyDays = floatval(mysqli_fetch_assoc(mysqli_query($conn, "select meta_value from settings where meta_key = 'penalty_days' limit 1"))['meta_value']);
 
$loans = mysqli_query($conn, "select * from loans where status = 1 order by id desc");
while($loan = mysqli_fetch_assoc($loans)){
    $id = $loan['id'];
    $lid = $loan['lid'];
    $uid = $loan['uid'];
    $amount = floatval($loan['amount']);
    $duration = floatval($loan['duration']);
    $date_ends = strtotime($loan['repayment_date']);
    
    if(time() < $date_ends){
        if(mysqli_num_rows(mysqli_query($conn, "select id from payouts where lid = '$lid'  limit 1")) == 0 ){
            // add payout request.
            $account = mysqli_num_rows(mysqli_query($conn, "select transfer_code from accounts where uid = '$uid' and is_default = 1 limit 1")) > 0 ? mysqli_fetch_assoc(mysqli_query($conn, "select transfer_code from accounts where uid = '$uid' and is_default = 1 limit 1"))['transfer_code'] ?? "" : mysqli_fetch_assoc(mysqli_query($conn, "select transfer_code from accounts where uid = '$uid' limit 1"))['transfer_code'] ?? "";
            mysqli_query($conn, "INSERT INTO `payouts`(`uid`, `lid`, `code`, `amount`, `account`, `fee`, `status`, `is_approval_mail_sent`, `is_approved`, `admin`,`note`) VALUES ('$uid','$lid', '', '$amount', '$account',0,0,0,0,'','')");
        }
        if(mysqli_num_rows(mysqli_query($conn, "select id from payouts where lid = '$lid' and status = 1  limit 1")) == 0 ){
            echo "pending payment";
            //pending payment
            continue;
        }
        
        // check for loan repayment amount
        $startDate = date("Y-m-d",strtotime($loan["date_approved"] ?: $loan["date_added"]));
        $endDate = date("Y-m-d", $date_ends);
        
        $now = $lid == "APP-85072137" ? "2024-04-26" : date("Y-m-d");
        $nowDateTime=new DateTime($now);
        $startDateTime=new DateTime($startDate);
        $months = $nowDateTime->diff($startDateTime);
        $months = (($months->y) * 12) + ($months->m);
    
        $amount = floatval($loan["amount"]);
        $interest = round($loan["interest"],2);
        $frequency = intval($loan["frequency"]);
        
        $prinicipalAmount = 0;
        if($frequency == 0 && $now == $endDate){
            // end payment
            $prinicipalAmount = $amount;
        }else if($frequency == 1){
            // monthly
            $prinicipalAmount = round($amount / $duration,2);
        }else if($frequency == 2 && ($months % 3 == 0)){
            // quarterly
            $prinicipalAmount = round($amount / ( $duration / 3 ),2);
        }else if($frequency == 3 && ($months % 6 == 0)){
            // semi annually
            $prinicipalAmount = round($amount / ( $duration / 6 ),2);
        }else if($frequency == 4 && ($months % 12 == 0)){
            // yearly
            $prinicipalAmount = round($amount / ( $duration / 12 ),2);
        }
        $repayment_month = round($prinicipalAmount + $interest, 2) + floatval($loan['penalty_charge']);
        $sql = "update loans set repayment_monthly = '$repayment_month' where lid = '$lid' limit 1";
        mysqli_query($conn, $sql);
        
        // check if loan has been repaid.
        $nextRepaymentDate = date("Y-m-").(date("d", strtotime($startDate)));
        $lastRepayedDate = mysqli_fetch_assoc(mysqli_query($conn, "select date_added from payments where type = 1 and lid = '$lid' order by id desc limit 1"))['date_added'] ?? "";
        
        $isRepaymentNotified = intval($loan['is_repayment_notified']);
        $isRepaid = $lastRepayedDate && strtotime($lastRepayedDate) >= strtotime($nextRepaymentDate);
        if(!$isRepaid && strtotime($nextRepaymentDate) > strtotime($startDate) ){
            $penaltyDay = date("Y-m-d", strtotime("+$penaltyDays days", strtotime($nextRepaymentDate)));
            $penaltyCharge = round(($penaltyChargePercent / 100) * $repayment_month,2);
            $user = mysqli_fetch_assoc(mysqli_query($conn, "select fname,lname,email from users where uid = '$uid' limit 1"));
            $dedicatedAccount = mysqli_fetch_assoc(mysqli_query($conn, "select bank, number from dedicated_accounts where uid = '$uid' limit 1")) ?? array();
            if(strtotime($nextRepaymentDate) == strtotime($now)){
                if($isRepaymentNotified == 0){
                    // repayment day, notify of pending repayment.
                    echo "repayment day, notify of pending repayment. - ";
                    send($user["fname"]." ".$user["lname"],$user["email"], "repayment_alert",array("name"=>$user["fname"],"lid"=>$loan["lid"],"penaltyDate"=>date("F j, Y", strtotime($penaltyDay)),"penaltyCharge"=>number_format($penaltyCharge,2),"repaymentAmount"=>number_format($repayment_month,2),"bankName"=>$dedicatedAccount['bank'] ?? "","accountNumber"=>$dedicatedAccount['number'] ?? ""));
                    mysqli_query($conn, "update loans set is_repayment_notified = 1,is_penalty_charged=0 where lid = '$lid' limit 1");
                }
            }else if(strtotime($now) == strtotime($penaltyDay)){
                // add charge and notify, reset is repayment notified back to 0.
                $isPenaltyCharged = intval($loan["is_penalty_charged"]);
                if($isPenaltyCharged == 0){
                    echo "add charge and notify - ";
                    $penaltyCharge += floatval($loan["penalty_charge"]);
                    $newRepaymentAmount = $penaltyCharge + $repayment_month;
                    mysqli_query($conn, "update loans set is_repayment_notified = 0, is_penalty_charged = 1, penalty_charge = '$penaltyCharge', repayment_monthly = '$newRepaymentAmount' where lid = '$lid' limit 1");
                    send($user["fname"]." ".$user["lname"],$user["email"], "penalty_charged",array("name"=>$user["fname"],"lid"=>$loan["lid"],"penaltyCharge"=>number_format($penaltyCharge,2),"repaymentAmount"=>number_format($newRepaymentAmount,2),"bankName"=>$dedicatedAccount['bank'] ?? "","accountNumber"=>$dedicatedAccount['number'] ?? ""));
                }
            }
            echo $lid." - Repayment Date: ".$nextRepaymentDate." - Last Repaid Date: ".$lastRepayedDate." - Penalty Date: $penaltyDay"."<br />";
        }else if(intval($loan["is_penalty_charged"]) == 1 || intval($loan["is_repayment_notified"]) == 1){
            echo "recalc done.";
            $amountPaid = floatval(mysqli_fetch_assoc(mysqli_query($conn, "select amount from payments where type = 1 and lid = '$lid' order by id desc limit 1"))['amount'] ?? "0");
            $penaltyCharge = floatval($loan['penalty_charge']);
            $repaymentAmount = floatval($repayment_month) -  $penaltyCharge;
            $amountLeft = ($amountPaid - $repaymentAmount);
            if($amountLeft == $penaltyCharge){
                $repayment_month = $repaymentAmount;
                $penaltyCharge = 0;
            }else{
                $repayment_month = $repaymentAmount;
                $penaltyCharge = $penaltyCharge - $amountLeft;
            }
            mysqli_query($conn, "update loans set is_repayment_notified = 0,is_penalty_charged=0,repayment_monthly='$repayment_month',penalty_charge='0' where lid = '$lid' limit 1");
        }
    }else{
        // end loans
        $user = mysqli_fetch_assoc(mysqli_query($conn, "select fname,lname,email from users where uid = '$uid' limit 1"));
        send($user["fname"]." ".$user["lname"],$user["email"], "loan_matured",array("name"=>$user["fname"],"title"=>$loan["lid"],"amount"=>number_format($amount,2),"repayment_amount"=>number_format($amount,2)));
        mysqli_query($conn, "update loans set status = 3 where id = '$id' limit 1");
    }
}
$conn->close();
?>