<?php

namespace App\Filament\Resources\ModuleListResource\Pages;

use App\Filament\Resources\ModuleListResource;
use App\Models\ModuleList;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use phpseclib3\Net\SFTP;

class CreateModuleList extends CreateRecord
{
    protected static string $resource = ModuleListResource::class;

    public function process($fileName)
    {
        //$file = trim($fileName);
        if (!$fileName)
        {
            Notification::make()
                ->title('File name is required!')
                ->danger()
                ->send();
            return;
        }

        $ftpHost = env('SFTP_HOST');
        $ftpUser = env('SFTP_USERNAME');
        $ftpPass = env('SFTP_PASSWORD');
        $remoteDir = env('SFTP_ROOT');
        $port = env('SFTP_PORT');

        $sftp = new SFTP($ftpHost, $port, 10);
        if (! $sftp->login($ftpUser, $ftpPass)) {
            Notification::make()->title('SFTP login failed')->danger()->send();
            return;
        }

        $remoteFile = $remoteDir . '/' . $fileName . '.txt';
        $content = $sftp->get($remoteFile);

        if ($content == false) {
            Notification::make()
                ->title("File {$remoteFile} not found")
                ->danger()
                ->send();
            return;
        }

        if ($content == false) {
            Notification::make()
                ->title("Failed to read {$remoteDir} from SFTP")
                ->danger()
                ->send();
            return;
        }

        $lines = array_map('trim', explode("\n", str_replace("\r", "", $content)));

        ModuleList::create([
            'module_name' => $lines[0] ?? '',
            'dashboard_name' => $lines[1] ?? '',
            'filter_name' => $lines[2] ?? '',
        ]);

        Notification::make()
            ->title("File {$remoteDir} read and saved successfully!")
            ->success()
            ->send();
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('create');
    }
}
