<?php
set_time_limit(0);
//PDO Database Connection
$db = new PDO('mysql:host=localhost;dbname=taamu_new;charset=utf8', 'taamu_files', 'taamu1234', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

//folder size function
function GetDirectorySize($path){
    $bytestotal = 0;
    $path = realpath($path);
    if($path!==false){
        foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
            $bytestotal += $object->getSize();
        }
    }
    return $bytestotal;
}
//set variables
if(isset($_GET["folder"])) {
	$folder = $_GET["folder"];
        $foldername = $result = str_replace('/','-',$folder);
	$size = GetDirectorySize($folder);
        $folderzip = __DIR__."/$folder/".$foldername.".zip";
}
//see if the folder exists in the database, if not add it
$result = $db->query("SELECT count(*) FROM directories WHERE directory = '$folder'"); 
$existing = (int) $result->fetchColumn(); 
if($existing == 0) {
	$db->query("INSERT INTO directories (directory, size) VALUES ('$folder', '0')");
}
//get the size of the folder in the database to check
$dbsize = $db->query("SELECT * FROM directories WHERE directory = '$folder'");
foreach($dbsize as $row) {
	$databasesize = $row["size"];
}
//if the size of the directory doesn't match what's in the database create a zip
if($size != $databasesize) { 
        if(file_exists($folderzip)) {
             unlink($folderzip);
        }
	// Get real path for our folder
	$rootPath = realpath($folder);

	// Initialize archive object
	$zip = new ZipArchive();
	$zip->open($folderzip, ZipArchive::CREATE | ZipArchive::OVERWRITE);

	// Create recursive directory iterator
	/** @var SplFileInfo[] $files */
	$files = new RecursiveIteratorIterator(
    	new RecursiveDirectoryIterator($rootPath),
    	RecursiveIteratorIterator::LEAVES_ONLY
	);
	$finalFile = false;
	foreach ($files as $name => $file) {
    		// Skip directories (they would be added automatically)
    		if (!$file->isDir()) {
        		// Get real and relative path for current file
        		$filePath = $file->getRealPath();
        		$relativePath = substr($filePath, strlen($rootPath) + 1);
				if (stripos($filePath,'RAR')!==FALSE){
					$finalFile = $filePath;
					break;
				}
        		// Add current file to archive
        		$zip->addFile($filePath, $relativePath);
    		}
	}
	// Zip archive will be created only after closing object
	$zip->close();
	//update the database with the size
	$db->query("UPDATE directories SET size = '$size' WHERE directory = '$folder'");
}

if ($finalFile!==false){
	//let the user download the file
	header('Content-Disposition: attachment; filename='.basename($finalFile));
	header("Content-Type: application/zip");
	$finfo = finfo_open();
	// send it to the client
	echo $finalFile;
	readfile($finalFile);
}
else{
	//let the user download the file
	header('Content-Disposition: attachment; filename='.basename($folderzip));
	header("Content-Type: application/zip");
	$finfo = finfo_open();
	// send it to the client
	echo $holdfolder.$folderzip;
	readfile($folderzip);
}


?>