<?php

namespace Daylight\Core\Modules\FormBuilder\Livewire;

use Daylight\Core\Livewire\Tables\BaseTable;
use Daylight\Core\Livewire\Tables\Concerns\WithBulkActions;
use Daylight\Core\Livewire\Tables\Concerns\WithSearch;
use Daylight\Core\Modules\FormBuilder\Models\FormSubmission;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use Livewire\Attributes\Computed;

class FormSubmissionTable extends BaseTable
{
    use WithBulkActions;
    use WithSearch;

    public int $formId;

    public ?string $dateFrom = null;

    public ?string $dateTo = null;

    public bool $showBulkDeleteConfirm = false;

    public function mount(int $formId): void
    {
        $this->formId = $formId;
        $this->searchable = false;
        $this->bulkActions = false;
    }

    protected function getBaseQuery(): Builder
    {
        return FormSubmission::query()
            ->where('form_id', $this->formId)
            ->when($this->searchQuery, fn (Builder $q) => $q->where('data', 'like', "%{$this->searchQuery}%"))
            ->when($this->dateFrom, fn (Builder $q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn (Builder $q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->latest();
    }

    protected function applySearch(Builder $query, ?string $searchQuery): Builder
    {
        return $query;
    }

    #[Computed]
    protected function availableBulkActions(): array
    {
        return [
            'delete' => [
                'name' => __('daylight::forms.bulk_delete'),
                'action' => 'bulkDeleteSubmissions',
            ],
        ];
    }

    public function bulkDeleteSubmissions(): void
    {
        $this->showBulkDeleteConfirm = true;
    }

    public function confirmBulkDelete(): void
    {
        $submissions = FormSubmission::query()
            ->where('form_id', $this->formId)
            ->whereIn('id', $this->selectedIds)
            ->get();

        $disk = Storage::disk('media');

        foreach ($submissions as $submission) {
            if (! empty($submission->files)) {
                foreach ($submission->files as $fieldId => $filePaths) {
                    foreach ((array) $filePaths as $path) {
                        if ($disk->exists($path)) {
                            $disk->delete($path);
                        }
                    }
                }
            }

            $submission->delete();
        }

        $this->selectedIds = [];
        $this->showBulkDeleteConfirm = false;
    }

    public function cancelBulkDelete(): void
    {
        $this->showBulkDeleteConfirm = false;
    }

    public function clearDateFilters(): void
    {
        $this->dateFrom = null;
        $this->dateTo = null;
    }

    public function render(): View
    {
        return view('daylight::livewire.form-builder.form-submission-table');
    }
}
