<?php
//$me_username = "jerry";
//$discon = mysqli_connect("localhost","ogosmsco_smssite","@321basket","ogosmsco_smssite");


function to2dp($num){
    return number_format((float)$num, 2, '.', ',');
}


$inv = mysqli_query($discon,"SELECT * FROM invoicegen WHERE INUsername = '$me_username' and INStatus = 'UNSENT' LIMIT 1") or die(mysqli_error($discon));
if(mysqli_num_rows($inv)>0){
    
    


    $invoice = mysqli_fetch_array($inv);
    $inid = $invoice['INId'];
    $nowd = date("Y-m-d h:i:s");
    $nowen = date("M").', '.date("Y");
    $nowdigit = date("d/m/Y");
    $saveas = "/home/ogosmsse/public_html/dynamicapi/53p79ut7/autoinvoice/invoices/INVOICE-$me_username-".str_replace(':','_',$nowd).".pdf";
    $invoice_id = $inid;
    $receiver_physical_address = $invoice['INReceiverAddr'];
    $units = $invoice['INUnits'];
    $unit_price = to2dp($invoice['INUnitPrice']);
    $total_price = to2dp($units*$unit_price);
    $total_price2 = to2dp(($units*$unit_price)+30000);
    
    
    
    
    
    
    
    
    
    //PROCESSING ITEMS/
    $items = @json_decode($invoice['INItems'],true);
    $istr = '';
    error_log(json_encode($items));
    if(gettype($items) == "array"){
        $total_price = 0;
        foreach($items as $item_){
            $units_ = $item_['unit'];
            $descr_ = $item_['descr'];
            $unitprice_ = to2dp($item_['cost']);
            $totalprice_ = to2dp($unitprice_ * $units_) ;
            $istr.= "
            <tr>
				<td>$units_ </td>
				<td>$descr_ </td>
				<td>N $unitprice_ K</td>
				<td>N $totalprice_ </td>
			</tr>
			";
			$total_price = $total_price + ($unitprice_ * $units_);
        }
        $total_price = to2dp($total_price);
    }else{
        $istr = "
        <tr>
				<td>$units</td>
				<td>SMS units (SIM Route, Corporate Route and Normal Route)</td>
				<td>N $unit_price K</td>
				<td>N $total_price K</td>
			</tr>
        ";
    }
    
    
    //END OF PROCESSING ITEMS
    

    require "pdfgen.php";

    if(file_exists($saveas)){



//recipeeint
        $to = $invoice['INReceiver'];
//sender
        $from = $invoice['INSender'];
        $fromName = 'OgoSMS Support';

//email subject
        $subject = "Sms Invoice for the Month of $nowen";

//attachment file path
        $file = $saveas;

//email body content
        $htmlContent = 'Good day, <br/> Attached is the sms invoice for the month of '.$nowen.'<br/> Regards, OgoSMS Support';

//header for sender info
        $headers = "From: $fromName"." <".$from.">";

//boundary
        $semi_rand = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//headers for attachment
        $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";

//multipart boundary
        $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
            "Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";

//preparing attachment
        if(!empty($file) > 0){
            if(is_file($file)){
                $message .= "--{$mime_boundary}\n";
                $fp =    @fopen($file,"rb");
                $data =  @fread($fp,filesize($file));

                @fclose($fp);
                $data = chunk_split(base64_encode($data));
                $message .= "Content-Type: application/octet-stream; name=\"".basename($file)."\"\n" .
                    "Content-Description: ".basename($file)."\n" .
                    "Content-Disposition: attachment;\n" . " filename=\"".basename($file)."\"; size=".filesize($file).";\n" .
                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
            }
        }
        $message .= "--{$mime_boundary}--";
        $returnpath = "-f" . $from;

//send email
        $mail = @mail($to, $subject, $message, $headers, $returnpath);

//email sending status
        error_log ($mail?"Invoice ($saveas) sent to $to":"Unable to send invoice $saveas to $to");







        mysqli_query($discon,"UPDATE invoicegen SET INDateSent = now(),INFilename = '$saveas',INStatus = 'SENT' WHERE INId = '$inid'");


    }else{
        error_log("Invoice file Not found $saveas");
    }



}