<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

require('/home/fundbridge/crons.fundbridgeinvestment.com/pdf-gen/fpdf_transparency.php');
require('/home/fundbridge/crons.fundbridgeinvestment.com/number-words/autoload.php');
require_once("/home/fundbridge/crons.ballng.com/db.php");
use NumberToWords\NumberToWords;

$extMap = array("/"=>"jpg","i"=>"png","R"=>"gif","U"=>"webp");

function getImage($dataURI){
    global $extMap;
    $pic = 'data://text/plain;base64,'.$dataURI;
    
    $type = "png";
    if ($type=="png"||$type=="jpeg"||$type=="gif") return array($pic, $type);
    return false;
}

function getOfferLetterData($data){
    $res = array();
    $res[] = array("type"=>"break","data"=>30);
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/image-top-right.png","attr"=>array("align"=>"L","y"=>0,"x"=>150,"width"=>60,"height"=>46));
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/image-top-left.png","attr"=>array("align"=>"L","y"=>10,"x"=>10,"width"=>65,"height"=>22));
    $res[] = array("type"=>"text","data"=> date("F j, Y", strtotime($data["dateAdded"])),"attr"=>array("align"=>"L","font"=>10));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=> "Name: ". $data["userName"],"attr"=>array("align"=>"L","border"=>0,"font"=>10));
    $res[] = array("type"=>"text","data"=> "Address: ". $data["userAddress"],"attr"=>array("align"=>"L","border"=>0,"font"=>10));
    $res[] = array("type"=>"break");
    $res[] = array("type"=>"text","data"=> "Attention: .......","attr"=>array("align"=>"L","border"=>0,"font"=>10));
    $res[] = array("type"=>"break");
    $res[] = array("type"=>"header","data"=> "OFFER/ACCEPTANCE OF LOAN FACILITY","attr"=>array("align"=>"C","border"=>0,"underline"=>false));
    $res[] = array("type"=>"break","data"=>10);
    $res[] = array("type"=>"text","data"=>"We refer to your application for loan facility and our various discussions on the above subject and are pleased to inform that the Management of Bridge Advances & Loans Limited has approved a loan facility to be availed to you under the following terms and conditions.", "attr"=>array("align"=>"L","font"=>10));
    $res[] = array("type"=>"break");
    $res[] = array("type"=>"row","data"=>array('Lender:', "Bridge Advances & Loans Limited (\"BALL\" or \"The Lender\")"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Obligor:', $data["userName"]." (\"The Borrower\")"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Facility Type:', "Term Loan Facility "), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Facility Amount:', "NGN".number_format($data["amount"],2)." (".$data["amountWords"].")"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Tenor:', "Up to ".(intval($data["duration"]) * 30 )." days"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array("Pricing:","Interest rate: ".$data['rate']."% per month."), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Repayment Pattern:', "Repayment of principal and interest on monthly basis"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Repayment Source:', "From the borrower salary"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"row","data"=>array('Prepayment Clause:', "No penalty shall be imposed on the Borrower\nfor payment made before the due date"), "attr"=>array("border"=>"","margin"=>24));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"header","data"=> "Security:","attr"=>array("align"=>"L","border"=>0,"underline"=>false));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"1.	To be inserted ","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"header","data"=> "Default Charge:","attr"=>array("align"=>"L","border"=>0,"underline"=>false));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"Failure to meet repayment as at when due will attract payment agreed of the interest rate plus a monthly ".$data["penaltyCharge"]."% flat late payment Charge on the unpaid amount due. The late payment charge shall be applied after a ".$data["penaltyDuration"]."-day grace period and shall continue until all past-due Obligations are fully paid.","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/watermark.png","attr"=>array("align"=>"L","y"=>240,"x"=>0));
    $res[] = array("type"=>"break","data"=>100);
    $res[] = array("type"=>"header","data"=> "Conditions Precedent to Drawdown:","attr"=>array("align"=>"L","border"=>0,"underline"=>false));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"Receipt of: \n1.	Duly executed offer letter signed by the obligor\n2.	Payment of Facility Fee\n3.	..............","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"header","data"=> "Other Conditions:","attr"=>array("align"=>"L","border"=>0,"underline"=>false));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"4.	Failure of the Borrower to honour obligations on the facility payment dates will trigger the immediate liquidation of the Placement Facility to repay the due obligation. \n5.	All out-of-pocket expenses incurred in the arrangement, administration and recovery of this facility including but not limited to solicitors' charges, travelling expenses, etc. shall be for the account of the borrower.","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"We are pleased to have been able to arrange this facility for you and hold the same available for your acceptance and compliance (to the stated conditions precedent to drawdown), for fourteen days (from the date on this Offer) after which it lapses (at the option of the Lender).","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"text","data"=>"Kindly indicate your acceptance of the offer by appending your signature(s) and affixing your company seal to this Letter.","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>10);
    $res[] = array("type"=>"text","data"=>"Yours faithfully,","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>2);
    $res[] = array("type"=>"text","data"=>"For: Bridge Advances & Loans Limited","attr"=>array("align"=>"L"));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/signature-left.png","attr"=>array("align"=>"L","y"=>118,"x"=>10,"width"=>40,"height"=>14));
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/signature-right.png","attr"=>array("align"=>"L","y"=>115,"x"=>100,"width"=>50,"height"=>16));
    $res[] = array("type"=>"row","data"=>array("....................................","             ","             ","             ","...................................."), "attr"=>array("border"=>""));
    $res[] = array("type"=>"row","data"=>array("Authorized Signatory","             ","             ","             ","Authorized Signatory"), "attr"=>array("border"=>""));
    $res[] = array("type"=>"break","data"=>10);
    $res[] = array("type"=>"text","data"=>"Accepted: ....................................","attr"=>array("align"=>"L","margin"=>90));
    $res[] = array("type"=>"break","data"=>10);
    $res[] = array("type"=>"text","data"=>"....................................","attr"=>array("align"=>"L"));
    if($data["signature"]){
        $res[] = array("type"=>"image","data"=>$data["signature"],"attr"=>array("align"=>"L","y"=>153,"x"=>10,"height"=>15));
    }
    
    $res[] = array("type"=>"text","data"=>"Borrower","attr"=>array("align"=>"L","bold"=>true));
    $res[] = array("type"=>"break","data"=>5);
    $res[] = array("type"=>"text","data"=>"Name: ".$data["userName"],"attr"=>array("align"=>"L","bold"=>true));
    $res[] = array("type"=>"break","data"=>2);
    $res[] = array("type"=>"text","data"=>"Date: ".date("F j, Y", strtotime($data["dateAdded"])),"attr"=>array("align"=>"L","bold"=>true));
    $res[] = array("type"=>"image","data"=>"/home/fundbridge/assets.ballng.com/pdf/watermark.png","attr"=>array("align"=>"L","y"=>240,"x"=>0));
    return $res;
}

function getData($type, $id, $isDownload){
    global $conn;
    $res = array();
    if($type == "offerLetter"){
        $numberToWords = new NumberToWords();
        $currencyTransformer = $numberToWords->getCurrencyTransformer('en');
        $data = $conn->query("select lid,uid,coalesce((select concat(title,' ',fname,' ',lname) as name from users where uid = loans.uid limit 1),'') as userName,coalesce((select concat(address,' ',lga,' ',state) from users where uid = loans.uid limit 1),'') as userAddress,amount,category,repayment_date as repaymentDate,duration_type as durationType,duration,rate,signature,date_added as dateAdded from loans where lid = '$id' limit 1")->fetch_assoc();
        if($data){
            $data["penaltyCharge"] = mysqli_fetch_assoc(mysqli_query($conn,"select meta_value from settings where meta_key = 'penalty_charge' limit 1"))['meta_value'];
            $data["penaltyDuration"] = mysqli_fetch_assoc(mysqli_query($conn,"select meta_value from settings where meta_key = 'penalty_days' limit 1"))['meta_value'];
            $data["signature"] = $data["signature"] ? "/home/fundbridge/assets.ballng.com/signatures/".$data["signature"] : "";
            $amountWords = ucwords($currencyTransformer->toWords(floatval($data["amount"]) * 100,"NGN"));
            $amountWords = str_replace("Nairas", "Naira", $amountWords);
            $amountWords = str_replace("Kobos", "Kobo", $amountWords);
            $data["amountWords"] = $amountWords;
            
            $res = getOfferLetterData($data);
            if($res){
                $filename = "offer_letter_".$data["lid"];
                return genPdf($res, $filename,"",$isDownload);
            }
        }
    }
    return false;
}

function genPdf($data,$filename,$watermark = "",$isDownload = false){
    $pdf = new AlphaPDF();
    $pdf->SetFont('Arial','',10);
    $pdf->AddPage();
    if($watermark){
        $pdf->Image('/home/fundbridge/assets.fundbridgeinvestment.com/pdf/'.$watermark, 0, 0, $pdf->GetPageWidth(), $pdf->GetPageHeight());
    }
    foreach($data as $line){
        $attr = isset($line["attr"]) ? $line["attr"] : array();
        // Color and font restoration
        $pdf->SetFillColor(255,255,255);
        $pdf->SetTextColor(0);
        $pdf->SetFont('Arial', '', isset($attr["font"]) ? $attr["font"] : 10);

        if(($attr["margin"] ?? 0) > 0){
            $pdf->SetLeftMargin($attr["margin"]);
        }else{
            $pdf->SetLeftMargin(10);
        }
        
        if($line["type"] == "text"){
            $pdf->SetFont('Arial','',10);
            if(($attr["bold"] ?? false)){
                $pdf->SetFont('','B');
            }
            $pdf->MultiCell(0,5,$line["data"],0,isset($attr["align"]) ? $attr["align"] : 'C');
        }
        if($line["type"] == "break"){
            $pdf->Ln($line["data"] ?? 5);
        }
        if($line["type"] == "image"){
            $y = $attr["y"] ?? 40;
            $x = $attr["x"] ?? 10;
            $width = $attr["width"] ?? null;
            $height = $attr["height"] ?? null;
            $pdf->Image($line["data"],$x,$y,$width,$height);
        }
        if($line["type"] == "barcode"){
            $generator = new Picqer\Barcode\BarcodeGeneratorPNG();
            $pic = getImage(base64_encode($generator->getBarcode($line["data"], $generator::TYPE_CODE_128)));
            $pdf->Image($pic[0], 140,6,0,0, $pic[1]);
        }
        if($line["type"] == "header"){
            $align = $attr["align"] ?: "L";
            if(($attr["underline"] ?? false)){
                $pdf->SetFont('','UB');
            }else{
                $pdf->SetFont('','B');
            }
            if(is_array($line["data"])){
                foreach($line["data"] as $column){
                    $pdf->Cell(0,7,$column,0,0,$align,true);
                }
                $pdf->Ln();
            }else{
                $pdf->Cell(0,5,$line["data"],isset($attr["border"]) ?  $attr["border"] : 0,0,$align,true);
            }
        }
        if($line["type"] == "row"){
            $pdf->SetFont('Arial','',10);
            if(($attr["size"] ?? 0) > 0){
                $pdf->SetFont('Arial','',$attr["size"]);
            }
            if(($attr["bold"] ?? false)){
                $pdf->SetFont('','B');
            }
            $aligns = isset($attr["aligns"]) ? $attr["aligns"] : array();
            $width = (empty($aligns) ? 120 : 150) / sizeof($line["data"]);
            $fill = true;
            $align = isset($attr["align"]) ? $attr["align"] : "L";
            $border = isset($attr["border"]) ? $attr["border"] : 0;
            $break = isset($attr["break"]) ? $attr["break"] : false;
            $pdf->SetDrawColor(0,0,0);
            foreach($line["data"] as $index => $column){
                if(is_array($column)){
                    $pdf->SetFillColor(239,251,255);
                    $pdf->SetTextColor(33,37,41);
                }
                if(is_array($column)){
                    foreach($column as $dat){
                        $pdf->Cell($width,7,$dat,1,0,$align,$fill);
                    }
                    $fill = !$fill;
                    $pdf->Ln();
                }else if(strlen($column) > 60){
                    $pdf->MultiCell(0,5,$column,0,empty($aligns) ? $align : $aligns[$index]);
                }else{
                    $pdf->Cell($width,7,$column,$border,0,empty($aligns) ? $align : $aligns[$index]);
                }
            }
            if($break){
                $pdf->Ln($break);
            }else{
                $pdf->Ln();
            }
            
        }
    }
    $filename .= ".pdf";
    if($isDownload){
        $pdf->Output("D", $filename);
    }else{
        $pdf->Output("F", "/home/fundbridge/assets.ballng.com/offer-letters/$filename");
    }
    return $filename;
}
if(isset($_GET['type'])){
    getData($_GET['type'], $_GET['id'],$_GET['is_download'] == "true");
}
?>