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

$admins = $conn->query("select fname,lname,email from admins where role in (select rid from roles where permissions like '%receive_loan_request_notifications%')")->fetch_all(MYSQLI_ASSOC);
$staffAdmins = $conn->query("select fname,lname,email from admins where role in (select rid from roles where permissions like '%receive_staff_loan_request_notification%')")->fetch_all(MYSQLI_ASSOC);
 
$loans = mysqli_query($conn, "select * from loans where is_notified = 0 and status != 5 order by id desc");
while($loan = mysqli_fetch_assoc($loans)){
    $id = $loan['id'];
    $lid = $loan['lid'];
    $uid = $loan['uid'];
    $isNotified = intval($loan["is_notified"]);
    $amount = floatval($loan["amount"]);
    
    if($isNotified == 0){
        // check if notified
        $user = mysqli_fetch_assoc(mysqli_query($conn, "select concat(fname,' ',lname) as name from users where uid = '$uid' limit 1"))['name'];
        if(intval($loan["category"]) == 458634){
            foreach($staffAdmins as $admin){
                send($admin["fname"]." ".$admin["lname"],$admin["email"], "notify_loan",array("name"=>$admin["fname"],"amount"=>number_format($amount,2),"user"=>$user));
            }
        }else{
            foreach($admins as $admin){
                send($admin["fname"]." ".$admin["lname"],$admin["email"], "notify_loan",array("name"=>$admin["fname"],"amount"=>number_format($amount,2),"user"=>$user));
            }
        }
        
        mysqli_query($conn, "update loans set is_notified =  1 where id = '$id' limit 1");
    }
}
$conn->close();
?>