<?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");

$platformCharge = floatval(mysqli_fetch_assoc(mysqli_query($conn, "select meta_value from settings where meta_key = 'platform_charge' limit 1"))['meta_value']);

$loans = mysqli_query($conn, "select * from loans where status = 1 order by id desc");
while($loan = mysqli_fetch_assoc($loans)){
    $lid = $loan['lid'];
    $uid = $loan['uid'];
    $amount = floatval($loan['amount']);
    $date_ends = strtotime($loan['repayment_date']);
    
    if(time() < $date_ends && mysqli_num_rows(mysqli_query($conn, "select id from payouts where lid = '$lid'  limit 1")) == 0 ){
        // add payout request.
        $charge = round(($platformCharge / 100) * $amount, 2);
        $actualAmount = $amount - $charge;
        $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_query($conn, "INSERT INTO `payouts`(`uid`, `lid`, `code`, `amount`,`amount_paid` ,`account`, `fee`, `status`, `is_approval_mail_sent`, `is_approved`, `admin`,`note`) VALUES ('$uid','$lid', '', '$amount','$actualAmount','$account','$charge',0,0,0,'','')");
    }
}
$conn->close();
?>