<?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/paystack.php");
require_once("/home/fundbridge/crons.ballng.com/email.php");

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

$admins = $conn->query("select fname,lname,email from admins where role in (select rid from roles where permissions like '%approve_payouts%')")->fetch_all(MYSQLI_ASSOC);

$payouts = mysqli_query($conn, "select * from payouts where status = 0 and code = '' order by id asc");
while($payout = mysqli_fetch_assoc($payouts)){
    $id = $payout['id'];
    $uid = $payout['uid'];
    $lid = $payout['lid'];
    $amount = floatval($payout['amount']);
    $reference = $payout["reference"] ?: time().mt_rand(1,999999);
    
    if($amount >= $payoutLimit && intval($payout['is_approved']) == 0){
        // check for approval.
        if(intval($payout["is_approval_mail_sent"]) == 0){
            foreach($admins as $admin){
                send($admin["fname"]." ".$admin["lname"],$admin["email"], "payout_approval",array("name"=>$admin["fname"],"amount"=>number_format($amount,2)));
            }
            mysqli_query($conn, "update payouts set is_approval_mail_sent =  1 where id = '$id' limit 1");
        }
        continue;
    }
    
    if(intval($payout['is_approved']) == 2){
        mysqli_query($conn, "update payouts set status = 2 where id = '$id' limit 1");
        continue;
    }
    
    $code = $payout["code"];
    if($code && validateTransfer($code)){
        continue;
    }
    
    // init transfer
    $amountPaid = floatval($payout["amount_paid"]);
    $amountPaid = $amountPaid > 0 ? $amountPaid : $amount;
    $code = request_transfer($amountPaid,$payout['account'],"Loan Payout.",$reference);
    echo $uid."=".$amountPaid."=".$code."<br />";
    if($code){
        mysqli_query($conn, "update payouts set code = '$code', status = 1,reference='$reference' where id = '$id' limit 1");
        mysqli_query($conn, "INSERT INTO `payments`(`uid`, `lid`, `ref`, `amount`, `type`, `method`, `status`) VALUES ('$uid', '$lid', '$code', '$amountPaid', '0', '', 1)");
        $fee = floatval($payout["fee"]);
        if($fee > 0){
            mysqli_query($conn, "INSERT INTO `payments`(`uid`,`title`, `lid`, `ref`, `amount`, `type`, `method`, `status`) VALUES ('$uid','Platform Charge on Loan Payout', '$lid', '', '$fee', '0', '', 1)");
        }
    }
}
$conn->close();
?>