<?php

namespace App\Http\Livewire\Pages\Report;

use App\Exports\ServerLicenseExport;
use App\Jobs\ExportChunkJob;
use App\Jobs\ExportReportJob;
use App\Models\ConfServerLicense;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Throwable;

class ReportIndex extends Component
{
    public $searchBy = [
        'COMPANY' => 'Company',
        'SNKEY' => 'Server Key',
        'CUR_VERSION' => 'Current Version',
        'STATUS' => 'Status',
        'DATABASETYPE' => 'Database',
        'PHP_VERSION_ID' => 'PHP Version'
    ];

    public $searchSelected;
    public $keyword;
    protected $results;
    public $progress = 0;
    public $exporting = false;
    public $fileName;
    public $jobId;
    public $batchId;
    public $status = '';

    public function filterReport()
    {
        $query = ConfServerLicense::select('ID', 'SNKEY', 'COMPANY', 'STATUS', 'CUR_VERSION', 'DATABASETYPE', 'LICENSEDATE');

        if ($this->searchSelected && $this->keyword) {
            $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
        }

        $this->results = $query->orderBy('ID', 'DESC')->get();
    }

  
    public function exportReport()
    {
        $this->exporting = true;
        $fileName = 'report_' . time() . '.xlsx';
        
        $chunks = $this->getDataInChunks();

        // สร้าง batch jobs โดยไม่ต้องใช้ withBatchId
        $batch = Bus::batch(
            collect($chunks)->map(fn($rows) => new ExportChunkJob($rows, $fileName))->toArray()
        )->then(function (Batch $batch) {
            // เมื่อ batch เสร็จสมบูรณ์
            $this->progress = 100;
            $this->status = 'Completed';
            $this->exporting = false;
        })->catch(function (Batch $batch, Throwable $e) {
            // เมื่อ batch ล้มเหลว
            $this->status = 'Failed';
            $this->exporting = false;
        })->finally(function (Batch $batch) {
            $this->emit('checkProgress'); // เรียก Livewire เช็ค progress
        })->dispatch();

        $this->batchId = $batch->id; // เก็บ batchId ไว้เพื่อตรวจสอบ progress
        $this->emit('startPolling'); // เริ่ม polling เพื่อติดตาม progress
    }

    public function checkProgress()
    {
        // เช็ค progress โดยใช้ batchId
        if ($this->batchId) {
            $batch = Bus::findBatch($this->batchId);

            if ($batch) {
                $this->progress = $batch->progress(); // อัปเดต progress
                if ($batch->finished()) {
                    $this->status = 'Completed';
                    $this->exporting = false;
                }
            }
        }
    }
    public function getDataInChunks()
    {
         $chunks = [];

        // ใช้ chunk() โดยมี callback function เป็นพารามิเตอร์ที่สอง
        ConfServerLicense::select('ID', 'SNKEY', 'COMPANY', 'STATUS', 'CUR_VERSION', 'DATABASETYPE', 'LICENSEDATE')
            ->orderBy('ID', 'DESC')
            ->chunk(100, function($rows) use (&$chunks) {
                $chunks[] = $rows;
            });
    
        return $chunks;
    }


    public function render()
    {
        $this->filterReport();
        return view('livewire.pages.report.report-index');
    }
}
