<?php

require 'vendor/autoload.php';

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

// SFTP credentials for the destination server
//$destination_server = 'files.us.priority-connect.online';     // Replace with your destination SFTP server
//$destination_username = 'CTD5B'; // Replace with your SFTP username
//$pem_file_path = 'test-priority-server.ppk';          // Replace with the path to your .pem file

$destination_server = 'files.us.priority-connect.online';     // Replace with your destination SFTP server
$destination_username = 'PE61D'; // Replace with your SFTP username
$pem_file_path = 'live-priority-server.pem';          // Replace with the path to your .pem file

// Folder containing the files you want to send
$local_folder = getcwd().'/taika/PriorityOrders/'; // Make sure this ends with a trailing slash

// Path on the destination server where files will be uploaded
$destination_folder = '/';

// Step 1: Load the private key from the .pem file
$key = PublicKeyLoader::load(file_get_contents($pem_file_path));

// Step 2: Connect to the destination SFTP server
$sftp = new SFTP($destination_server);

if (!$sftp->login($destination_username, $key)) {
    die('Login failed for destination SFTP server');
}

// Step 3: Read all files from the local folder
$files = scandir($local_folder);

// Step 4: Loop through each file and send it to the destination server
foreach ($files as $file) {
    // Ignore '.' and '..'
    if ($file != '.' && $file != '..') {

        $local_file_path = $local_folder . $file;
        $destination_file_path = $file;

        // Check if it's a file before uploading
        if (is_file($local_file_path) && pathinfo($file, PATHINFO_EXTENSION) === 'txt') {
            echo "Uploading file: $local_file_path to $destination_file_path\n";

            if ($sftp->put($destination_file_path, $local_file_path, SFTP::SOURCE_LOCAL_FILE)) {
                echo "File uploaded successfully: $file\n";
                rename($local_file_path, $local_folder.'completed/'. basename($file));
            } else {
                echo "Error uploading file: $file\n";
            }
        }
    }
}

echo "All files uploaded successfully.\n";

?>
