<?php 

include ('core/codon.config.php');
include ('core/local.config.php');

class iCrewTrackerAPI extends CodonModule {

	public function __construct() {
		
	}
	
	public function trigger_file_pirep() {
		
		$data = json_decode(file_get_contents('php://input'));
		
		$directory =  "../icrewtrackerclient/prefile/";
        $files = glob($directory . "*.pirep"); // Get all .pirep files in the directory
        $processedCount = 0; // Counter for successfully processed files
        
        
        $pireps = [];
        
        foreach ($files as $file) {
            try {
                // Decode the base64 encoded content and then JSON decode it
                $pirepdata = json_decode((file_get_contents($file)), true)[0];
                $ret = ACARSData::FilePIREP($pirepdata['pilotid'], $pirepdata);	
                if($ret) {
                	$pireps[] = [
	                	'pilotid' => $pirepdata['pilotid'],
	                	'pirepdata'	=> $pirepdata,
	                ];
	                
                	unlink($file);
                	
                	$processedCount++;	
                } else {
                	$pireps[] = [
                		'error_message'	=> ACARSData::$lasterror,
                	];
                }
                
                
            } catch (Exception $e) {
                // Handle any exceptions that might occur during processing (e.g., logging)
                // For now, we'll just continue to the next file
                die($e->getMessage());
                continue;
            }
        }

        // Return the number of files processed
        return "Processed {$processedCount} PIREPs";
	}

}


$tracker = new iCrewTrackerAPI();

if(isset($_GET['action']) && $_GET['action'] != '') {
	
	header('Content-type: application/json');
	
	switch($_GET['action']) {
		case "file":
			print_r($tracker->trigger_file_pirep());
		break;
	}	
	
	
} else {
	die('No GET request passed');
}

?>