<?php

include('server.php');
include(__DIR__.'/vendor/autoload.php');
include(__DIR__.'/GoogleClient.php');
?>

<?php

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename))
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    $dt = date('d-M-Y:hh:mm:ss');
    $log_msg = $dt . ' - ' .  $log_msg;
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}


try{

$response = GoogleClient::getClient();

if($response['success'] == 1)
{
        $client = $response['client'];

        $service = new \Google_Service_Drive($client);


	/*
	//Refresh root lelvel folders
	$toplevel = $service->teamdrives->listTeamdrives(['pageSize' => 100]); //->getTeamDrives();

	$sql = "truncate table rootfolders_1";
	mysqli_query($db, $sql);

        $fileid = array();
        $filename = array();
        foreach($toplevel as $x=>$y)
        {
                $id = $toplevel[$x]->id;
                $name = $toplevel[$x]->name;
		$sql = "insert into rootfolders(foldername, folderid) values('$name','$id')";
		mysqli_query($db, $sql);
        }
	*/


	$sql = "select * from rules where originid is null and destinationid is null";
	$sql = "select * from rules";
	$rulesresults = mysqli_query($db, $sql);
	while($row = $rulesresults->fetch_assoc())
	{
		//Findout origin id
		$folder = substr($row['origin'], 1);
		$rule = $row['rules'];
		$folder = explode("\\", $folder);
		$id = $row['id'];
		$sql = "select * from rootfolders where foldername='$folder[0]'";
		$rootfolderresults = mysqli_query($db, $sql);
		$rootfolderrow = $rootfolderresults->fetch_assoc();
		$folderId = $rootfolderrow['folderid'];
		$updatesql = "update rules set originid='$folderId' where id='$id'";
		mysqli_query($db, $updatesql);

		wh_log("Record id - $id => Rule - $rule");

		for($i=1;$i<count($folder);$i++)
		{

		$sql = "select * from rules where id='$id'";
		$ruleresult =  mysqli_query($db, $sql);
		$rulerow = $ruleresult->fetch_assoc();	
		$folderId = $rulerow['originid'];
		
		$optParams = array(
			'supportsTeamDrives' => true,
		);
        	$results = $service->files->get($folderId, $optParams);
	        $teamDriveId = $results["teamDriveId"];

        	// now we can get the sub-folders (if there are any)
	        $params = [
	            'q'                     => "'{$folderId}' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder'",
	            //'pageSize'              => $pageSize,
	            'corpora'               => 'teamDrive',
	            'includeTeamDriveItems' => true,
	            'supportsTeamDrives'    => true,
	            'teamDriveId'           => $teamDriveId,    // this must be the parent Id
	            'orderBy'               => 'name',
        	];

    		$results = $service->files->listFiles($params);
        	foreach($results  as $x=>$y)
	        {
        	        $fid = $results[$x]->id;
                	$name = $results[$x]->name;
			$originfid = $fid;

			if ($name == $folder[$i]) {
				$updatesql = "update rules set originid='$fid' where id='$id'";
				mysqli_query($db, $updatesql);
				break;
			}
			else
                        {
                                $updatesql = "update rules set originid='Not Exist' where id='$id'";
                                mysqli_query($db, $updatesql);
                        }
	        }
		}

	    //Findout destination id
		$folder = substr($row['destination'], 1);
                $folder = explode("\\", $folder);
                //$id = $row['id'];
                $sql = "select * from rootfolders where foldername='$folder[0]'";
                $rootfolderresults = mysqli_query($db, $sql);
                $rootfolderrow = $rootfolderresults->fetch_assoc();
                $folderId = $rootfolderrow['folderid'];
                $updatesql = "update rules set destinationid='$folderId' where id='$id'";
                mysqli_query($db, $updatesql);

                for($i=1;$i<count($folder);$i++)
                {

                $sql = "select * from rules where id='$id'";
                $ruleresult =  mysqli_query($db, $sql);
                $rulerow = $ruleresult->fetch_assoc();
                $folderId = $rulerow['destinationid'];

		$fval = $folder[$i];

                $optParams = array(
                        'supportsTeamDrives' => true,
                );
                $results = $service->files->get($folderId, $optParams);
                $teamDriveId = $results["teamDriveId"];

                // now we can get the sub-folders (if there are any)
                $params = [
                    'q'                     => "'{$folderId}' in parents and trashed = false and mimeType = 'application/vnd.google-apps.folder'",
                    'pageSize'              => 1000,
                    'corpora'               => 'teamDrive',
                    'includeTeamDriveItems' => true,
                    'supportsTeamDrives'    => true,
                    'teamDriveId'           => $teamDriveId,    // this must be the parent Id
                    'orderBy'               => 'name',
                ];

                $results = $service->files->listFiles($params);
		$glist = array();
                foreach($results  as $x=>$y)
                {
                        $fid = $results[$x]->id;
                        $name = $results[$x]->name;
			$glist += array($name=>$fid);
		}

		if (array_key_exists($folder[$i],$glist))
		{
			$val = $glist[$folder[$i]];
			$destinationfid = $val;
			 $updatesql = "update rules set destinationid='$val' where id='$id'";
                         mysqli_query($db, $updatesql);
			//echo $folder[$i] . " - exist\n";
		}
		else
		{
			wh_log("Destination folder $fval not exist, creating folder");
			$file = new Google_Service_Drive_DriveFile(array(
		        	'name' => $folder[$i],
			        'mimeType' => 'application/vnd.google-apps.folder',
				'parents' => array($folderId)
			));

			$optParams =[ 
				'supportsTeamDrives'    => true
			];

		try {
		    $createdFile = $service->files->create($file, $optParams);
		    $val = $createdFile->id;
			$destinationfid = $val;
			 wh_log("Destination folder $fval created - id: $destinationfid");
			$updatesql = "update rules set destinationid='$val' where id='$id'";
			mysqli_query($db, $updatesql);
		} catch (Exception $e) {
		    echo 'Exception reçue : ',  $e->getMessage(), "\n";
		}
		}
                }

		//File moving part
		//==========================

	 $params = [
            'q'                     => "'{$originfid}' in parents and not trashed",
            'corpora'               => 'teamDrive',
            'includeTeamDriveItems' => true,
            'supportsTeamDrives'    => true,
            'teamDriveId'           => $teamDriveId,    // this must be the parent Id
            'orderBy'               => 'name',
        ];

        $results = $service->files->listFiles($params);
        foreach($results  as $x=>$y)
        {
                $id = $results[$x]->id;
                $name = $results[$x]->name;

		$ext = pathinfo($name, PATHINFO_EXTENSION);
                if (($ext == 'pdf') || ($ext == 'PDF') || ($ext == 'Pdf')) 
		{


		if (fnmatch($rule, $name))
		{
			$mfile = new \Google_Service_Drive_DriveFile();
		        //$mfile->setName($name);
		        //$service->files->update($id, $mfile, $optParams);

		        $optParams=array(
                		 'supportsTeamDrives' => true,
		                 'removeParents' => $originfid,
		                 'addParents' => $destinationfid,
	                );

	        	$response = $service->files->update($id, $mfile, $optParams);
			wh_log("$name file matched with $rule and moved to $fval - $destinationfid folder");

		}
		}

	}


		

	}

} else {
                                echo $response['html'];
                                die;
                        }

                } catch(\Exception $e){
			wh_log($e->getMessage());
                        echo '<p>Exception occured:'.$e->getMessage().'</p>';
                        echo '<p>If issue is in Google api, remove data in token.json and refresh this page and try again.-</p>';
                        die;
                }
?>
