<?php
function getFolderSize($dir) {
    $size = 0;

    // RecursiveDirectoryIterator flags to skip `.` and `..`
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS));

    foreach ($iterator as $file) {
        $size += $file->getSize();
    }

    return $size;
}

$directory = 'output';  // Replace with your folder path
$folderSize = getFolderSize($directory);

// Convert the size to human-readable format
function formatSizeUnits($bytes) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }

    return $bytes;
}


?>

<div class="row mb-4">
    <div class="col-12 col-md-10">
        <div class="note note-secondary"><strong>System Perfomance:</strong> Archiving old files (<2 years) reduces the records in the main database. This means that searching and sorting is more efficient. File cleanup reduces your storage
               footprint.</div>
        </div>
    </div>


    <div class="row">
        <div id="dbArchive" class="col-12 col-md-6 px-4">
            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <h2>Archive older reports</h2>
                        <p>
                            Choose a date from which you want to archive reports. All reports from all clients produced before that date will be archived. This process vastly improved the performance of the delivery system.
                        </p>
                    </div>

                    <div id="s1">
                        <div class="form-group row">

                            <div class="col-12 col-md-8">
                                <div class="input-group" data-mdb-datepicker-init data-mdb-input-init data-mdb-toggle-button="false" data-mdb-format="dd-mm-yyyy">
                                    <label for="archive_date" class="form-label me-4">Select archive date</label>
                                    <input type="text" class="form-control " id="archive_date" name="archive_date" data-mdb-toggle="datepicker" value="<?= date('d-m-Y',strtotime('now -2year'));?>" />

                                    <button id="start" class="btn btn-md btn-info" type="button" id="button-addon2">Start</button>
                                </div>

                            </div>
                        </div>
                        <div class="row mt-5">
                            <div class="col-12 text-center"><i class="fad fa-folder-open fa-10x" style="--fa-primary-color: #2a3f54; --fa-secondary-color: #bdceeb; --fa-secondary-opacity:1; filter: drop-shadow(0 0 0.75rem black);"></i>
                            </div>
                        </div>

                    </div>

                    <div id="s2" style="display: none">
                        <div id="result" class="col-12 mt-5 text-center"></div>
                        <div class="col-12 text-center mt-5">
                            <p><a class="btn btn-info" href="index.php?t=includes/master&p=repArchive.php">Restart</a></p>
                        </div>
                    </div>



                    <div id="end" style="display:none">
                        <div class="col-12 text-center">
                            <h3>The archive process has completed <span class="green-text">successfully</span></h3>
                            <p><a class="btn btn-info" href="index.php?t=includes/master&p=repArchive.php">Restart</a></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="fileRemove" class="col-12 col-md-6 px-4">
            <div class="card">
                <div class="card-body">
                    <div class="row mb-3">
                        <h2>File Cleanup - <small><?= "Current storage size: " . formatSizeUnits($folderSize)?></small></h2>
                        <p>Choose a date from which you want to delete files. All reports from all clients produced more than the given time will be removed. The system will rebuld any report removed if later needed.</p>
                    </div>
                    <div id="r1">
                        <div class="col-12 col-md-8">
                            <div class="input-group">
                                <label class="control-label me-4" for="repYear">Select number of years</label>
                                <select id="repYear" class="form-control">
                                    <option value="0">0</option>
                                    <?php foreach(range(1,10) as $y){
                    echo '<option value="'.$y.'">'.$y.'</option>';
                    }?>
                                </select>
                                <button id="run" class="btn btn-md btn-info " type="button" id="button-addon2">Start</button>
                            </div>
                        </div>
                        <div class="row mt-5">
                            <div class="col-12 text-center"><i class="fad fa-database fa-10x" style="--fa-primary-color: #2a3f54; --fa-secondary-color: #bdceeb; --fa-secondary-opacity:1; filter: drop-shadow(0 0 0.75rem black);"></i></div>
                        </div>
                    </div>
                    <div id="r2" style="display: none">
                        <div id="result2" class="col-12 mt-5 text-center"></div>
                        <div class="col-12 text-center mt-5">
                            <p><a class="btn btn-info" href="index.php?t=includes/master&p=repArchive.php">Restart</a></p>
                        </div>
                    </div>

                    <div id="end2" style="display:none">
                        <div class="col-12 text-center">
                            <h3>The removal process has completed <span class="green-text">successfully</span></p>
                                <p><a class="btn btn-info" href="index.php?t=includes/master&p=repArchive.php">Restart</a></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
    document.getElementById('start').addEventListener('click', function() {
        showLoadingIndicator("Searching", "fa-spinner fa-spin-reverse");
        var date = document.getElementById('archive_date').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', ROOT_URL + '/includes/master/repArchive_functions.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                var rep = xhr.responseText.trim();
                if (rep == 0) {
                    document.getElementById('result').innerHTML = '<p>There are <strong>' + rep + '</strong> reports detected prior to ' + date + '</p>';
                } else {
                    document.getElementById('result').innerHTML = '<p>There are <strong>' + rep + '</strong> reports detected prior to <strong>' + date +
                        '</strong><br>Do you wish to proceed?</p><p><a class="btn btn-success" href="javascript:void(0)" onclick="commit()">Commit Archive</a></p>';
                }
                document.getElementById('s1').style.display = 'none';
                document.getElementById('s2').style.display = 'block';
                removeLoadingIndicator();
            }
        };

        xhr.send('FUNCTION=getReps&start=' + encodeURIComponent(date) + '&tenant=' + encodeURIComponent(TENANT_URL));
    });

    function commit() {
        document.getElementById('s2').style.display = 'none';
        showLoadingIndicator("Archiving Reports", "fa-archive fa-spin-reverse");
        var date = document.getElementById('archive_date').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', ROOT_URL + '/includes/master/repArchive_functions.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                removeLoadingIndicator();
                document.getElementById('end').style.display = 'block';
            }
        };

        xhr.send('FUNCTION=commit&start=' + encodeURIComponent(date) + '&tenant=' + encodeURIComponent(TENANT_URL));
    }

    document.getElementById('run').addEventListener('click', function() {
        showLoadingIndicator("Searching", "fa-search fa-spin-reverse");
        var year = document.getElementById('repYear').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', ROOT_URL + '/includes/master/repArchive_functions.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                var rep = xhr.responseText.trim();
                if (rep == 0) {
                    document.getElementById('result2').innerHTML = '<p>There are <strong>' + rep + '</strong> files detected</p>';
                } else {
                    document.getElementById('result2').innerHTML = '<p>There are <strong>' + rep +
                        '</strong> reports detected<br>Do you wish to proceed?</p><p><a class="btn btn-success" href="javascript:void(0)" onclick="removeFiles()">Commit Removal</a></p>';
                }
                document.getElementById('r1').style.display = 'none';
                document.getElementById('r2').style.display = 'block';
                removeLoadingIndicator();
            }
        };

        xhr.send('FUNCTION=getDocs&years=' + encodeURIComponent(year) + '&tenant=' + encodeURIComponent(TENANT_URL));
    });

    function removeFiles() {
        document.getElementById('r2').style.display = 'none';
        showLoadingIndicator("Archiving Reports", "fa-trash fa-spin-reverse");
        var year = document.getElementById('repYear').value;

        var xhr = new XMLHttpRequest();
        xhr.open('POST', ROOT_URL + '/includes/master/repArchive_functions.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                removeLoadingIndicator();
                document.getElementById('end2').style.display = 'block';
            }
        };

        xhr.send('FUNCTION=removeFiles&years=' + encodeURIComponent(year) + '&tenant=' + encodeURIComponent(TENANT_URL));
    }

    document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Report Archive and system cleanup</li>';
    </script>