<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class SyncLabResultsFTP extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:sync-lab-results-f-t-p';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Mengakses file di FTP server
        $ftpDisk = Storage::disk('ftp');  // Pastikan konfigurasi FTP ada di config/filesystems.php

        // Mendapatkan daftar file di FTP server
        $files = $ftpDisk->files('results');  // Misalnya folder 'results'

        foreach ($files as $file) {
            // Mengambil file dari FTP dan membaca isinya
            $fileContents = $ftpDisk->get($file);

            // Proses konten file (misalnya parsing CSV atau XML)
            $this->processFileContents($fileContents);
        }

        $this->info('Lab results synchronized from FTP.');
    }
    protected function processFileContents($contents)
    {
        // Misalnya, jika konten dalam format CSV
        $rows = str_getcsv($contents, "\n");

        foreach ($rows as $row) {
            $data = str_getcsv($row);

            // Menyimpan hasil tes ke database
            TestResult::create([
                'patient_id' => $data[0],  // Misal, data pasien ada di kolom pertama
                'test_id' => $data[1],     // Misal, data tes ada di kolom kedua
                'result_value' => $data[2],// Nilai hasil tes ada di kolom ketiga
                'timestamp' => now(),
            ]);
        }
    }

}
