<?php
namespace App\Http\Controllers\backend;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Artisan;
use Carbon\Carbon;
use App\Jobs\UploadToDrive;

class BackupController extends Controller
{
    /**
    * Role and permission implement by ****** 
    * >>>>>> Md Azharul Islam
    * >>>>>> email: azharul787@gmail.com
    *>>>>>>> Software Developer
    * >>>>>> This function call automatically when call this method
    */
    /*function __construct(){
        $this->middleware('permission:backup-list|backup-create|backup-edit|backup-delete', ['only' => ['index','store']]);
        $this->middleware('permission:backup-create', ['only' => ['create','store']]);
        $this->middleware('permission:backup-download', ['only' => ['download']]);
        $this->middleware('permission:backup-delete', ['only' => ['clean','destroy']]);
    }*/
    
    public function index(){
       /* $diskName = 'local'; // Or retrieve this from your configuration if it's different
        $disk = Storage::disk($diskName);
        $backupDirectory = 'backups'; // Path to your backups directory

        $files = $disk->files($backupDirectory);
        */
        $files = storage_path('app/backups/')->allFiles();
        return $files;
        //return 'Hello';
        //$diskName = config('backup.backup.destination.disks')[0];
        //$disk = Storage::disk($diskName);
        //$backupDirectory = config('backup.backup.name');
        // Get all files in the backup directory
        //$files = $disk->allFiles($backupDirectory);
       
        //$disk = Storage::disk(config('backup.backup.destination.disks')[0]);
        //$files = $disk->files(config('backup.backup.name'));
        
        //return $files;
        // Sort files by modified time
        usort($files, function($a, $b) use ($disk) {
            return $disk->lastModified($b) - $disk->lastModified($a);
        });

        $backups = collect($files)->filter(function ($file) use ($disk, $backupDirectory) {
            return basename($file) !== '.gitignore'; // Ignore .gitignore file
        })->map(function ($file) use ($disk) {
            return [
                'path' => $file,
                'file_name' => basename($file),
                'last_modified' => Carbon::createFromTimestamp($disk->lastModified($file))->toDateTimeString(),
                'file_size' => $this->bytesToHuman($disk->size($file)),
            ];
        });
        //dd($backups);
        //return $backups;
        return view('backend.backup.index',compact('backups'));
    }
    private function bytesToHuman($bytes){
        $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];

        for ($i = 0; $bytes > 1024; $i++) {
            $bytes /= 1024;
        }

        return round($bytes, 2) . ' ' . $units[$i];
    }
    public function create(){
        // Artisan::call('backup:run');
        // return back()->with('success','Backup Created Successfull');
    }
    public function store(Request $request){
        Artisan::call('backup:database');
        return back()->with('success','Backup Created Successfull');
    }
    public function clean(){
        return 'ddddd';
        Artisan::call('backup:clean');

        return back()->with('success','All Old Backups Successfully Deleted.');
    }
    public function destroy($file_name){
        return $file_name;
        $disk = Storage::disk(config('backup.backup.destination.disks')[0]);

        if ($disk->exists(config('backup.backup.name') . '/' . $file_name)) {
            $disk->delete(config('backup.backup.name') . '/' . $file_name);
        }
    
        return back()->with('success','Backup Deleted Success');
    }
    public function downloadBackup($file_name){
        //return $file_name;
        /*$diskName = config('backup.backup.destination.disks')[0];
        $disk = Storage::disk($diskName);
        $backupDirectory = 'backups'; // Ensure this matches the directory name
        $path = $backupDirectory . '/' . $file_name;

        if ($disk->exists($path)) {
            return response()->download(storage_path('app/' . $path));
        }*/
        
        /*$diskName = 'local'; // Or retrieve this from your configuration if it's different
        $disk = Storage::disk($diskName);
        $backupDirectory = 'backups'; // Path to your backups directory

        $filePath = $backupDirectory . '/' . $file_name;

        if ($disk->exists($filePath)) {
            $fileContent = $disk->get($filePath);
            $fileName = basename($filePath);

            return response()->streamDownload(function () use ($fileContent) {
                echo $fileContent;
            }, $fileName);
        } else {
            //abort(404, 'File not found.');
            return redirect()->route('admin.backup.index')->withErrors('The requested file does not exist.');
        }*/
        
       /* $file = config('backup.backup.name') . '/' . $file_name;
        $disk = Storage::disk(config('backup.backup.destination.disks')[0]);
        if ($disk->exists($file)) {
            $fs = Storage::disk(config('backup.backup.destination.disks')[0])->getDriver();
            $stream = $fs->readStream($file);
            return \Response::stream(function () use ($stream) {
                fpassthru($stream);
            }, 200, [
                "Content-Type" => $fs->getMimetype($file),
                "Content-Length" => $fs->getSize($file),
                "Content-disposition" => "attachment; filename=\"" . basename($file) . "\"",
            ]);
        }*/
        
        /*$diskName = 'local'; // Or retrieve this from your configuration if it's different
        $disk = Storage::disk($diskName);
        $backupDirectory = 'backups'; // Path to your backups directory

        $filePath = $backupDirectory . '/' . $file_name;

        if ($disk->exists($filePath)) {
            $fileName = basename($filePath);

            return response()->stream(function () use ($disk, $filePath) {
                echo $disk->get($filePath);
            }, 200, [
                'Content-Type' => 'application/octet-stream',
                'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
            ]);
        } else {
            abort(404, 'File not found.');
        }*/
        
        $diskName = 'local'; // Or retrieve this from your configuration if it's different
        $disk = Storage::disk($diskName);
        $backupDirectory = 'backups'; // Path to your backups directory
    
        $filePath = $backupDirectory . '/' . $file_name;
    
        if ($disk->exists($filePath)) {
            $fileName = basename($filePath);
    
            return new StreamedResponse(function () use ($disk, $filePath) {
                echo $disk->get($filePath);
            }, 200, [
                'Content-Type' => 'application/octet-stream',
                'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
            ]);
        } else {
            abort(404, 'File not found.');
        }
    }
}
