<?php
session_start();
$licenseValid = false;
$expirationWarning = false;

// Define the path to the license folder
$licenseDir = __DIR__ . '/../license/';

// Check if there are any CSV files in the license directory
$files = glob($licenseDir . '*.csv');

if (!empty($files)) {
    $csvFile = $files[0]; // Take the first CSV file (assuming there's only one)
    
    if (($handle = fopen($csvFile, 'r')) !== false) {
        if (($header = fgetcsv($handle, 1000, ',')) !== false) {
            $licenseKeyIndex = array_search('License Key', $header);
            $createdDateIndex = array_search('Created Date', $header);
            $expirationDateIndex = array_search('Expiration Date', $header);

            if ($licenseKeyIndex !== false && $createdDateIndex !== false && $expirationDateIndex !== false) {
                if (($data = fgetcsv($handle, 1000, ',')) !== false) {
                    $expirationDate = $data[$expirationDateIndex];
                    $currentDate = new DateTime();
                    $expirationDateTime = new DateTime($expirationDate);

                    $dateDifference = $expirationDateTime->diff($currentDate)->days; // Calculate days difference

                    // Check if the expiration date is today or has passed
                    if ($expirationDateTime <= $currentDate) {
                        $licenseValid = true; // Set license as valid since it is expired
                    }

                    // Check if the expiration date is within the next 10 days and not expired
                    if ($dateDifference > 0 && $dateDifference <= 10) {
                        $expirationWarning = true;
                    }

                    fclose($handle);
                }
            }
        }
    }
}
$_SESSION['difference'] = $dateDifference;
?>

<script>
    window.onload = function() {
        var licenseValid = <?php echo json_encode($licenseValid); ?>;
        var expirationWarning = <?php echo json_encode($expirationWarning); ?>;

        if (licenseValid) {
            document.getElementById('popup_token').classList.add('show');
            document.querySelector('.blur-background').style.display = 'block';
        } else if (expirationWarning) {
            alert("Warning: Your license key will expire within the next 10 days.");
        }
    }
</script>
