<?php

namespace App\Console\Commands;

use App\Models\FileExport;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

const NUM_DAYS_TO_KEEP = -1;

class CleanUpStorage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'storage:cleanUpFiles';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove generated reports and bulk uploaded files from Storage which are uploaded before 24 hours.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // Creating Log file.
        $date = Carbon::now()->format('Y-m-d');
        $file = "login-" . $date . ".log";
        $path = storage_path('logs/' . $file);

        if (!file_exists($path)) {
            Log::channel('daily')->info('Log File created');
        }

        chmod($path, 0750);

        $directories = glob(storage_path('app/public/*'), GLOB_ONLYDIR);

        $protectedDirectories = ['certificates', 'ewaste_certificate', 'variance_reports', 'eol_certificates'];

        // Removing unwanted files
        // $result = $this->removeOldFiles(storage_path('integration/connection'), 2);
        // $result = $this->removeOldFiles(storage_path('integration/cdw'), 2);
        // $result = $this->removeOldFiles(storage_path('integration/insight'), 2);

        if (!empty($directories)) {
            foreach ($directories as $directory) {
                if (!in_array(sanitizeFilename($directory), $protectedDirectories)) {
                    // $this->info(sanitizeFilename($directory));
                    $this->removeOldFiles($directory, NUM_DAYS_TO_KEEP);
                }
            }
        }

        /**
         * Clear file url path from db
         */
        FileExport::where('created_at', '<', Carbon::now()->subDays(1))->update(['report_url' => '']);
    }

    /**
     * Checking each files in given path and removing unwanted files
     */
    public function removeOldFiles($path, $limit, $index = 0)
    {
        // $path = storage_path($path);

        if (!is_dir($path)) {
            return false;
        }

        chmod($path, 0750);
        $files = scandir($path, SCANDIR_SORT_DESCENDING);

        if ($files) {
            foreach ($files as $key => $file) {
                $file = $path . "/" . $file;
                $needToBeDeleted = $this->checkIsFileNeedToBeDeleted($file, $limit, $index - $key);
                if ($needToBeDeleted) {

                    unlink($file);
                }
            }
        }

        return true;
    }

    /**
     * file - filepath
     * if index is grater than zero, recent files will not be deleted. number of files keeped = index
     * if limit is less than zero, all files from the folder removed
     * else all files older than today-limit will be removed
     */
    public function checkIsFileNeedToBeDeleted($file, $limit, $index = 0)
    {
        if (!is_file($file)) {
            return false;
        }

        if ($index > 0) {
            return false;
        }

        if ($limit < 0) {
            return true;
        }

        $fileUploadedDate = date("Y-m-d H:i:s.", filemtime($file));
        $nowDate = Carbon::now()->subDays($limit);
        $result = $nowDate->gt($fileUploadedDate);

        if ($result) {
            return true;
        }

        return false;
    }
}
