<?php
/**
 * @ASCOOS-NAME         : Ascoos OS
 * @ASCOOS-VERSION      : 1.0.0
 * @ASCOOS-SUPPORT      : support@ascoos.com
 * @ASCOOS-BUGS         : https://issues.ascoos.com
 * 
 * @CLASS-METHOD-STUDY  : TZipHandler::extractWithProgress()
 * @file                : extractWithProgress.php
 * @test                : callback that sends JSON progress to the browser
 * 
 * @desc <English> It demonstrates the use of the extractWithProgress method, which sends JSON progress to the browser via a callback
 * @desc <Greek> Παροσιάζει την χρήση της μεθόδου extractWithProgress που μέσω callback στέλνει JSON progress στον browser
 * 
 * @since PHP 8.3.0
 */
declare(strict_types=1);
use ASCOOS\OS\Kernel\Archives\TZipHandler;

session_start();

// <EN> We save the progress in the session so that Ajax can read it
// <EL> Αποθηκεύουμε την πρόοδο σε session για να την διαβάζει το Ajax
function ajaxProgressCallback(int $current, int $total, string $entryName = ''): void {
    $_SESSION['zip_progress'] = [
        'current' => $current,
        'total'   => $total,
        'percent' => $total > 0 ? round(($current / $total) * 100, 2) : 0,
        'entry'   => $entryName,
    ];
//    session_write_close(); // επιτρέπει στο AJAX να διαβάζει τη session
}


// <EN> Starting decompression (once)
// <EL> Εκκίνηση αποσυμπίεσης (μία φορά)
if (!isset($_SESSION['zip_started'])) {
    $_SESSION['zip_started'] = true;
    $zipHandler =& TZipHandler::getInstance();
    $zipHandler->extractWithProgress('/path/to/archive.zip', '/path/to/target', 'ajaxProgressCallback');
}

// <EN> Endpoint to return the current progress
// <EL> Endpoint για να επιστρέφει την τρέχουσα πρόοδο
header('Content-Type: application/json');
echo json_encode($_SESSION['zip_progress'] ?? ['current'=>0,'total'=>0,'percent'=>0,'entry'=>'']);
?>