<?php

namespace App\Filament\Resources\DriverMasterResource\Pages;

use App\Filament\Resources\DriverMasterResource;
use App\Models\DriverMaster;
use Filament\Actions;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use phpseclib3\Net\SFTP;

class CreateDriverMaster extends CreateRecord
{
    protected static string $resource = DriverMasterResource::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)));

        DriverMaster::create([
            'name' => $lines[0] ?? '',
            'identification1' => $lines[1] ?? '',
            'identification2' => $lines[2] ?? '',
            'identification3' => $lines[3] ?? '',
            'contact_number' => $lines[4] ?? '',
            'alternate_number' => $lines[5] ?? '',
        ]);

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