<?php

namespace App\Extensions\Installed\Importer\Livewire\Jobs;

use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\WithPagination;
use App\Extensions\Installed\Importer\Models\ImportJob;

#[Layout('components.layouts.app', ['title' => 'Import Jobs', 'noPadding' => true])]
class JobsIndex extends Component
{
    use WithPagination;

    public $filterStatus = '';
    public $filterType = '';

    public function deleteJob($jobId)
    {
        $job = ImportJob::findOrFail($jobId);
        
        // Delete the file if it exists
        if ($job->file_path && file_exists($job->file_path)) {
            @unlink($job->file_path);
        }

        $job->delete();

        session()->flash('success', 'Import job deleted successfully!');
    }

    public function render()
    {
        $query = ImportJob::query()->latest();

        if ($this->filterStatus) {
            $query->where('status', $this->filterStatus);
        }

        if ($this->filterType) {
            $query->where('type', $this->filterType);
        }

        $jobs = $query->paginate(20);

        return view('extension.importer::jobs.index', [
            'jobs' => $jobs,
            'sources' => [
                'csv' => ['enabled' => true],
                'database' => ['enabled' => true],
            ],
        ]);
    }
}
