<?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);
       // dd($fileName);
        if (!$fileName)
        {
            Notification::make()
                ->title('File name is required!')
                ->danger()
                ->send();
            return;
        }

        $ftpHost = env('FTP_HOST');
        $ftpUser = env('FTP_USERNAME');
        $ftpPass = env('FTP_PASSWORD');
        $remoteDir = env('FTP_ROOT');
       // $port = env('FTP_PORT');

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

        if (!$conn) {
            Notification::make()->title("Could not connect to FTP server")->danger()->send();
            return;
        }

        // Login
        if (!ftp_login($conn, $ftpUser, $ftpPass)) {
            Notification::make()->title("FTP login failed")->danger()->send();
            ftp_close($conn);
            return;
        }

        if (!ftp_chdir($conn, $remoteDir)) {
            Notification::make()->title("Folder {$remoteDir} not found")->danger()->send();
            ftp_close($conn);
            return;
        }

        // List files
        $files = ftp_nlist($conn, '.'); // list all files in folder

        // if (!in_array($fileName = $get('file_name') . '.txt', $files)) {
        //     Notification::make()->title("File {$fileName} not found on FTP")->danger()->send();
        //     ftp_close($conn);
        //     return;
        // }

        // Get file content
        $tmpFile = tempnam(sys_get_temp_dir(), 'ftp');
        if (!ftp_get($conn, $tmpFile, $fileName, FTP_ASCII)) {
            Notification::make()->title("Failed to download {$fileName}")->danger()->send();
            ftp_close($conn);
            return;
        }

        // Read content
        $content = file_get_contents($tmpFile);
        unlink($tmpFile); // cleanup

        // Close connection
        ftp_close($conn);

        // Split lines and insert into DB
        $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');
    }
}
