<?php
ini_set('display_errors', 'On');
error_reporting(E_ERROR);



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

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

//get json array
$jsonArr = json_decode($json, true);
error_log("\n report_raw_data script called",3,"my-errors.log");
                
// check for required fields
 
 if(isset($jsonArr['email']))
 {
    $filename=$jsonArr['csv_type'];
    $filedata=$jsonArr['data'];
    $email=$jsonArr['email'];
    $flag=$jsonArr['completed'];
    if(!empty($email) && $flag =="no")
    {
        error_log("\nenterde first", 3, "my-errors.log");
        $subdir="../FBTempReport/".$email;
        mkdir($subdir);
        $dir="../FBTempReport/".$email."/".$email;
        mkdir($dir);
        $csvFileName =$dir.'/'.$filename.'.csv';
        $fp = fopen($csvFileName, 'w');
        foreach ($filedata as $value) {
            fputcsv($fp, $value);
            
        }
        fclose($fp);
        $response["success"] = 1;
        $response["message"] = "csv file created succesfully";
        echo json_encode($response);
    			
    
    }
    if (!empty($email) && $flag =="yes")
    {
        
        zipcreator($email);
        error_log("\nenterde second", 3, "my-errors.log");
        $response["success"] = 1;
        $response["message"] = "Zip created succesfully";
        error_log("\nresponse: ".print_r($response, true), 3, "my-errors.log");
        echo json_encode($response);
        
     }

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


function zipcreator($email)
{

    // Get real path for our folder
$rootPath = realpath("../FBTempReport/".$email."/".$email);

// Initialize archive object
$zip = new ZipArchive();
$zip->open($rootPath.'.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

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);
        
        
        // Add current file to archive
        $res=$zip->addFile($filePath,$relativePath);
        
        
        if($res !== true)
        {
            
            error_log("\nfailed:".$zip->getStatusString()."\n", 3, "my-errors.log");
        }
        
    }
}

// Zip archive will be created only after closing object
$zip->close();


}

?>