<?php

require 'vendor/autoload.php';

use phpseclib3\Net\SFTP;
use phpseclib3\Crypt\PublicKeyLoader;

try {
    // Define the SFTP server details
    $sftp_server = 'files.us.priority-connect.online';
    $username = 'PE61D';
    $path_to_pem_file = 'live-priority-server.pem';

    // Define the remote and local file paths
    $remote_file_path = '/inventory/of_inventory.xml';
    $local_file_path = getcwd() . '/taika/Inventory/OF_INVENTORY.xml';
    $csv_file = getcwd() . '/taika/Inventory/inventory_'.date('mdY').'.csv';
    // Load the private key
    $key = PublicKeyLoader::load(file_get_contents($path_to_pem_file));

    // Create an SFTP instance
    $sftp = new SFTP($sftp_server);

    // Attempt to login using the username and private key
    if (!$sftp->login($username, $key)) {
        exit('Login Failed');
    }

    echo "Connected successfully!\n";

    // Download the remote file to the local path
    if ($sftp->get($remote_file_path, $local_file_path)) {
        echo "File downloaded successfully!";
    } else {
        echo "Failed to download file.";
    }
    // Close the connection (optional, as it closes automatically at the end of the script)
    $sftp->disconnect();

    // Step 3: Load and parse the XML file
    if (file_exists($local_file_path)) {
        $xml = simplexml_load_file($local_file_path) or die("Error: Cannot create XML object");

        
        // Open CSV file for writing
        $file = fopen($csv_file, 'w');

        // Step 4: Write headers to CSV file
        fputcsv($file, ['Sku', 'Stock']);

        // Loop through each record in the XML and write to CSV
        foreach ($xml->REC as $record) {
            // Extract data from each XML record
            $sku = (string)$record->SKU;
            $stk_status = (string)$record->STK_STATUS;

            if($sku){
                // Write the data into the CSV file
                fputcsv($file, [$sku, $stk_status]);
            }
        }

        // Close the CSV file
        fclose($file);

        echo "CSV file created successfully: $csv_file.\n";

        if (unlink($local_file_path)) {
            echo "XML file deleted successfully.\n";
        } else {
            echo "Error: Unable to delete XML file.\n";
        }

    } else {
        die("Error: $local_file_path does not exist.");
    }

}catch (\Exception $exception){
    echo "Exception Error: ". $exception->getMessage();
}
?>