<?php
    // only a post with paystack signature header gets our attention
    $headers = getallheaders();
    // only a post with paystack signature header gets our attention
    $paystackSignature = array_key_exists('x-paystack-signature', $headers) ? $headers["x-paystack-signature"] : $headers["X-Paystack-Signature"];
    if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !$paystackSignature){
        exit();
    }
    
    // Retrieve the request's body
    $input = @file_get_contents("php://input");
    
    define('PAYSTACK_SECRET_KEY','sk_live_f7669e5d6cf5d8355bd64fb883928237149bc026');
    
    // validate event do all at once to avoid timing attack
    if($paystackSignature !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY)){
        exit();
    }
    
    // parse event (which is json string) as object
    // Do something - that will not take long - with $event
    $event = json_decode(stripslashes($input), true);
    if(is_array($event) && !empty($event) && isset($event["event"])){
        require_once("/home/fundbridge/crons.ballng.com/db.php");
        if($event["event"] == "customeridentification.success"){
            $data = $event["data"];
            $customer = $data["customer_code"];
            $confirm_customer = mysqli_query($conn, "select uid from dedicated_accounts where cus_code = '$customer' limit 1");
            if(mysqli_num_rows($confirm_customer) > 0){
                require_once("/home/fundbridge/crons.ballng.com/paystack.php");
                $uid = mysqli_fetch_assoc($confirm_customer)["uid"];
                $user = mysqli_fetch_assoc(mysqli_query($conn, "select fname,lname,phone from users where uid = '$uid' limit 1"));
                $account = createAccount($customer,$user["fname"],$user["lname"],$user["phone"]);
                if($account && $account["number"]){
                    $number = $account["number"];
                    $bank = $account['bank'];
                    mysqli_query($conn, "update dedicated_accounts set number = '$number',bank='$bank',status = 1 where uid = '$uid' limit 1");
                }
            }
        }
        if($event["event"] == "dedicatedaccount.assign.success"){
            $data = $event["data"];
            $customer = $data["customer"]["customer_code"];
            $confirm_customer = mysqli_query($conn, "select uid from dedicated_accounts where cus_code = '$customer' limit 1");
            if(mysqli_num_rows($confirm_customer) > 0){
                require_once("/home/fundbridge/crons.ballng.com/paystack.php");
                $uid = mysqli_fetch_assoc($confirm_customer)["uid"];
                $user = mysqli_fetch_assoc(mysqli_query($conn, "select fname,lname,phone,email from users where uid = '$uid' limit 1"));
                if(array_key_exists("account_number", $data)){
                    $number = $data["account_number"];
                    $bank = $data['bank']["name"];
                    mysqli_query($conn, "update dedicated_accounts set number = '$number',bank='$bank',status = 1 where uid = '$uid' limit 1");
                    
                    // send notification email
                    require_once("/home/fundbridge/crons.ballng.com/email.php");
                    send($user['fname']. " " . $user['lname'],$user['email'], "account_generated", array("name"=> $user['fname'], "bank"=>$bank,"number"=>$number));
                }
            }
        }
        if($event["event"] == "charge.success"){
            $data = $event["data"];
            $uid = "";
            
            if($data["channel"] == "dedicated_nuban"){
                $account = $data["authorization"]["receiver_bank_account_number"];
                $confirm_customer = mysqli_query($conn, "select uid from dedicated_accounts where number = '$account' limit 1");
                if(mysqli_num_rows($confirm_customer) > 0){
                    $uid = mysqli_fetch_assoc($confirm_customer)["uid"];
                    $amount = floatval($data["amount"]) / 100;
                    
                    // check if amount has been added before
                    $reference = $data['reference'];
                    $checkPayment = mysqli_query($conn, "select id from payments where uid = '$uid' and ref = '$reference' limit 1");
                    if(mysqli_num_rows($checkPayment) > 0){
                        mysqli_close($conn);
                        http_response_code(200);
                        return;
                    }
                    
                    $pendingLoan = mysqli_query($conn, "select lid,repayment_amount from loans where uid = '$uid' and (status = 1 or status = 3)");
                    if(mysqli_num_rows($pendingLoan) > 0 ){
                        $pendingLoan = mysqli_fetch_assoc($pendingLoan);
                        $loanId = $pendingLoan['lid'];
                        $repaymentAmount = floatval($pendingLoan["repayment_amount"]);
                        $amountPaid = floatval(mysqli_fetch_array(mysqli_query($conn, "select sum(amount) from payments where uid = '$uid' and lid = '$loanId' and type = 1"))[0]);
                        $amountLeft = $repaymentAmount - $amountPaid;
                        mysqli_query($conn, "INSERT INTO `payments`(`uid`, `lid`, `ref`, `amount`, `type`, `method`, `status`) VALUES ('$uid', '$loanId', '$reference', '$amount', '1', 'bank', 1)");
                        if(true){
                            $amountLeft -= $amount;
                            // send money receieved email
                            require_once("/home/fundbridge/crons.ballng.com/email.php");
                            $userInfo = mysqli_fetch_assoc(mysqli_query($conn, "select fname,lname,email from users where uid = '$uid' limit 1"));
                            if($amountLeft <= 0){
                                // amount paid in full
                                mysqli_query($conn, "update loans set status = 4 where lid = '$loanId' limit 1");
                                send($userInfo['fname']. " " . $userInfo['lname'],$userInfo['lname'], "loan_repaid", array("name"=> $userInfo['fname'],"amount"=>"&#8358;".number_format($amount,2),"loan_amount"=>"&#8358;".number_format($repaymentAmount,2)));
                            }else{
                                send($userInfo['fname']. " " . $userInfo['lname'],$userInfo['lname'], "loan_repaid_pending", array("name"=> $userInfo['fname'],"amount"=>"&#8358;".number_format($amount,2),"loan_amount"=>"&#8358;".number_format($repaymentAmount,2),"amount_left"=>"&#8358;".number_format($amountLeft,2)));
                            }
                        }
                    }
                }
            }
        }
        
        if($event["event"] == "transfer.success"){
            $data = $event["data"];
            $code = $data["transfer_code"];
            if($code){
                mysqli_query($conn, "update payouts set status = 1 where code = '$code' limit 1");
                mysqli_query($conn, "update payments set status = 1 where type = 0 and ref = '$code' limit 1");
            }
        }
        
        if($event["event"] == "transfer.failed" || $event["event"] == "transfer.reversed"){
            $data = $event["data"];
            $code = $data["transfer_code"];
            if($code){
                mysqli_query($conn, "update payouts set status = 0 where code = '$code' limit 1");
                mysqli_query($conn, "update payments set status = 1 where type = 0 and ref = '$code' limit 1");
            }
        }
    }
    mysqli_close($conn);
    http_response_code(200);
?>