<?php

namespace App\SuperAdmin\Http\Controllers\Front;

class GeneratefolderfilesController extends FrontBaseController
{
    public function generate_folder_files(){
        
        if(!(url('/') == 'http://hrmifly-saas.test' )){
            return redirect()->route('front.index');
        }
        // Files Paths

        $modified_files = [
            '.gitignore',
            'app/SuperAdmin/Http/Controllers/Api/CompanyController.php',
        ];

        $localpath = 'C:/wamp64/www/';

        foreach ($modified_files as $key => $modified_file) {
            self::createFolders($localpath . 'kiyo_hrm_updates/' . $modified_file);
            self::copyFiles($localpath . 'hrmifly-saas/' . $modified_file, $localpath . 'kiyo_hrm_updates/' . $modified_file);
            echo $modified_file . " --  File copied successfully.<br>";
        }       
        die;
    }

    private function createFolders($filePath){
        // Get the directory path from the file path
        $directory = dirname($filePath);

        // Create the directory if it doesn't exist
        if (!file_exists($directory)) {
            // Recursive flag is set to true to create nested directories
            if (!mkdir($directory, 0777, true)) {
                // If unable to create directory, display an error message
                echo "Failed to create directory: $directory";
                return false;
            }
        }
        return true;
    }

    private function copyFiles($source, $destination){
        // Check if source is a directory
        if (is_dir($source)) {
            // Create destination directory if it doesn't exist
            if (!file_exists($destination)) {
                mkdir($destination, 0777, true);
            }

            // Open the source directory to read its contents
            $dir = opendir($source);

            // Iterate through each file/directory in the source directory
            while (false !== ($file = readdir($dir))) {
                if (($file != '.') && ($file != '..')) {
                    // If the current item is a directory, recursively copy its contents
                    if (is_dir($source . '/' . $file)) {
                        copyFiles($source . '/' . $file, $destination . '/' . $file);
                    } else {
                        // If the current item is a file, copy it to the destination
                        copy($source . '/' . $file, $destination . '/' . $file);
                    }
                }
            }

            // Close the source directory handle
            closedir($dir);
        } else {
            // If the source is a file, simply copy it to the destination
            copy($source, $destination);
        }
    }
}
