<?php
//while (ob_get_level())
//ob_end_clean();
//header("Content-Encoding: None", true);
  
ini_set("session.auto_start", 0);
ini_set('display_errors', 'On');
//ini_set('allow_url_fopen','On');
error_reporting(E_ERROR);

include 'fpdf/fpdf.php';
// array for JSON response (default to failure)
$response = array();
$response["success"] = 0;
$response["message"] = "Failed";

class PDF extends FPDF
{
// Load data
function LoadData($file)
{
    // Read file lines
    $lines = file($file);
    $data = array();
    foreach($lines as $line)
        $data[] = explode(';',trim($line));
    return $data;
}


// Colored table
function FancyTable($header, $data)
{
    // Colors, line width and bold font
    $this->SetFillColor(255,0,0);
    $this->SetTextColor(255);
    $this->SetDrawColor(128,0,0);
    $this->SetLineWidth(.3);
    $this->SetFont('','B');
    // Header
    $w = array(40, 35, 40, 45);
    for($i=0;$i<count($header);$i++)
        $this->Cell($w[$i],7,$header[$i],1,0,'C',true);
    $this->Ln();
    // Color and font restoration
    $this->SetFillColor(224,235,255);
    $this->SetTextColor(0);
    $this->SetFont('');
    // Data
    $fill = false;
    foreach($data as $row)
    {
        $this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
        $this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
        $this->Cell($w[2],6,number_format($row[2]),'LR',0,'R',$fill);
        $this->Cell($w[3],6,number_format($row[3]),'LR',0,'R',$fill);
        $this->Ln();
        $fill = !$fill;
    }
    // Closing line
    $this->Cell(array_sum($w),0,'','T');
}
}

//get json string
$json = file_get_contents('php://input');

//get json array
$jsonArr = json_decode($json, true);
$email = $jsonArr['email'];

// check for required fields
if (isset($jsonArr['email']))  {	
	//echo "entered in main";
	
	
	$receipt = $jsonArr['receipt'];
	$continew=$jsonArr['continue'];
	$remainingimagename=$jsonArr['remainingimagename'];
	$remainingimage=$jsonArr['remainingimage'];
	$temppresent=$jsonArr['temp'];
	if(!empty($remainingimage) && !empty($remainingimagename) && $continew =="yes")
	{
		//echo "entered in remaining";
		//echo "actual image:-".$remainingimage; 
		//echo "imag name:-".$remainingimagename;
		//receiveimagefromphone($remainingimage,$email,$remainingimagename);
		$tempfilepath="../FBTempReport/".$email;
	    mkdir($tempfilepath, 0777, true);
		$tempfilepath="../FBTempReport/".$email."/";
		//echo $remainingimagename;
		//echo $tempfilepath.$remainingimagename;
	    file_put_contents($tempfilepath.$remainingimagename, base64_decode($remainingimage));
		if($continew =="yes"){
			$response["success"] = 1;
			$response["message"] = "Success";
			echo json_encode($response);
			exit;
		}
	
	}
	if(!empty($receipt) && $continew == "no"){
	    //echo "enterd in receipts";
	    if(!empty($remainingimage) && !empty($remainingimagename))
	    {
	       // echo "enterd in dir";
	        $dir="../FBTempReport/".$email."/";
	        if (!is_dir($dir)) {
                mkdir($dir);         
                }
	    $tempfilepath="../FBTempReport/".$email."/";
        file_put_contents($tempfilepath.$remainingimagename, base64_decode($remainingimage));
	    }
		//echo "\nentered in receipt";
		$pic=$receipt;
		if (strpos($pic,":::")){
		//	echo "\nentered in receipt pics";
			$receiptarray=(explode(":::",$pic));
       		$receipt= array_filter($receiptarray);
        	$tempfilepath="../FBTempReport/".$email."/";
  			foreach ($receipt as $singlepicpath) {
		    	//	echo "\nenterd in loop".$singlepicpath;
                $tempfilepath="../FBTempReport/".$email."/";
				$file_path = "../FBReceiptsTemp/";
				$file_path = $file_path.$singlepicpath;
				$tempfilepath=$tempfilepath.$singlepicpath;
				//echo "\ntemp file path:".$tempfilepath;
				if (file_exists($file_path) == false and file_exists($tempfilepath)==false) {
				//	echo "\nenterd in file system";

	 				$imagebasename=$singlepicpath;
	 			//	echo "\nbasename".$singlepicpath;
	 				if($imagenotexist=="")
	 				{
	 					$imagenotexist=$imagebasename.":::";
	 				}
	 				else
	 				{
	 					$imagenotexist=$imagenotexist.$imagebasename.":::";
					}
		        }
			}
			if($imagenotexist !="")
			{


				//echo "\nentered in image section";
				//echo "\nnotavailable images:".$imagenotexist;
                $response["success"] = 1;
    			$response["message"] = "image not exist";
    			$response["imagenotexist"]=$imagenotexist;
    			echo json_encode($response);
    			
			}

			else if($imagenotexist == ""){
			    


                    $pdf = new PDF();
   					foreach ($receipt as $singlepicpath) {
   					    $tempfilepath="../FBTempReport/".$email."/";
			        	$file_path = "../FBReceiptsTemp/";
				        $file_path = $file_path.$singlepicpath;
			        	$tempfilepath=$tempfilepath.$singlepicpath;
			        	//$type=getimagesize($tempfilepath);
			        	//echo $type[2]."type";
						
   						if($temppresent=="yes" && file_exists($tempfilepath) == true)
   						{
   						    
                            $pdf->AddPage();
							$pdf->Image('http://www.fuelbuddy-app.com/FBTempReport/'.$email.'/'.$singlepicpath);
						}
						else
						{   //$size = getimagesize('http://www.fuelbuddy-app.com/FBReceiptsTemp/'.$singlepicpath);
   						    //echo "type".$size[2];
   						    $type   = exif_imagetype('http://www.fuelbuddy-app.com/FBReceiptsTemp/'.$singlepicpath);
   						   if($type==3)
   						   {
   						       //$name=basename($path,".jpg");
   						       //$name=$name.".png";
   						       
   						      //$fullimage=imagepng(imagecreatefromstring(file_get_contents($singlepicpath)), "output.png");
   						      //echo $fullimage;
   						        $path ='http://www.fuelbuddy-app.com/FBReceiptsTemp/'.$singlepicpath; 
                                $type = pathinfo($path, PATHINFO_EXTENSION);
                                $data = file_get_contents($path);
                                //$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
                              
                                $base64 ='data://text/plain;base64,'. base64_encode($data);
                                $info = getimagesize($base64);
                                //echo $base64;
                                //echo $info[0];
                                //echo $info[1];
   						        $pdf->AddPage();
   						       error_log("imgdata".$base64,3,"my-errors.log");
   						      
						       $pdf->Image($base64,10,30,$info[0] ,$info[1], 'png');
						       
						        //$pdf->Image($base64,'png');
   						   }
   						   else {
						    $pdf->AddPage();
						    $pdf->Image('http://www.fuelbuddy-app.com/FBReceiptsTemp/'.$singlepicpath);
   						   }
						}
					}
					$filename='../FBTempReport/'.$email.'/'.$email.'.pdf';
					$pdf->Output($filename,"F");
					if(file_exists($filename) == true)
					{
				        $response["success"] = 1;
				        $response["message"] = "all images exist and PDF created succesfully";
    			       
    		            echo json_encode($response);
					}
					else
					{
					  $response["success"] = 1;
    			      $response["message"] = "all images exist and PDF not created ";
    			      
    		          echo json_encode($response);
    			
					}
					
			}
	}
}

}	
else{
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
}



function receiveimagefromphone($remainingimage,$email,$remainingimagename)
{
	//echo "in function";
	//echo $remainingimage;
	//echo $remainingimagename;
	$tempfilepath="../FBTempReport/".$email;
	mkdir($tempfilepath, 0777, true);
	$tempfilepath="../FBTempReport/".$email/"/";
	file_put_contents($tempfilepath.$remainingimagename, base64_decode($remainingimage));

}

?>