<?php

namespace App\Livewire\Employee;

use App\Livewire\Forms\DocumentForm;
use App\Livewire\Forms\EmployeeForm;
use App\Models\Employee;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component; // Add this line
use Livewire\WithFileUploads; // Import the Computed attribute
use Livewire\WithPagination;

class Index extends Component
{
    use WithFileUploads;
    use WithPagination; // Add this line

    public EmployeeForm $form;

    public DocumentForm $documentForm;

    public bool $isEditing = false;

    public string $filterStatus = 'active'; // 'active', 'trashed', 'all'

    public ?int $currentEmployeeId = null; // Changed to store ID

    #[Url]
    public $employee_id = null; // For query string

    #[Computed] // Computed property to get the Employee object
    public function currentEmployee()
    {
        return $this->currentEmployeeId ? Employee::withTrashed()->find($this->currentEmployeeId) : null;
    }

    public function create()
    {
        $this->isEditing = false;
        $this->form->reset();
        $this->dispatch('open-modal');
    }

    public function edit(Employee $employee)
    {
        $this->isEditing = true;
        $this->form->setEmployee($employee);
        $this->dispatch('open-modal');
    }

    public function save()
    {
        if ($this->isEditing) {
            $this->form->update();
        } else {
            $this->form->store();
        }

        $this->dispatch('close-modal');
        session()->flash('flash.banner', 'Employee saved successfully!');
    }

    public function delete(Employee $employee)
    {
        $employee->delete();
        session()->flash('flash.banner', 'Employee deleted successfully.');
    }

    public function restore($employeeId)
    {
        $employee = Employee::withTrashed()->findOrFail($employeeId);
        $employee->restore();
        session()->flash('flash.banner', 'Employee restored successfully!');
    }

    public function forceDelete($employeeId)
    {
        $employee = Employee::withTrashed()->findOrFail($employeeId);
        $employee->forceDelete();
        session()->flash('flash.banner', 'Employee permanently deleted!');
    }

    // --- Document Management Methods ---
    public function manageDocuments($employeeId)
    {
        $employee = Employee::withTrashed()->find($employeeId);
        if (! $employee) {
            return;
        }
        $this->currentEmployeeId = $employee->id; // Store ID
        $this->documentForm->resetDocumentForm(); // Reset document form for new entry
        $this->documentForm->documentable_id = $this->currentEmployeeId;
        $this->documentForm->documentable_type = \App\Models\Employee::class; // Use fully qualified class name
        $this->dispatch('open-document-form-modal'); // Dispatch event to open modal
    }

    public function createDocument()
    {
        $this->documentForm->resetDocumentForm();
        $this->documentForm->documentable_id = $this->currentEmployeeId;
        $this->documentForm->documentable_type = \App\Models\Employee::class; // Use fully qualified class name
        $this->dispatch('open-document-form-modal');
    }

    public function editDocument($document_id)
    {
        $document = \App\Models\Document::findOrFail($document_id); // Explicitly find the document
        $this->documentForm->setDocument($document);
        $this->dispatch('open-document-form-modal');
    }

    public function saveDocument()
    {
        if ($this->documentForm->document && $this->documentForm->document->exists) {
            $this->documentForm->update();
        } else {
            $this->documentForm->store();
        }
        // $this->dispatch('close-document-form-modal'); // Removed to keep modal open after save
        session()->flash('flash.banner', 'Document saved successfully!');
        $this->documentForm->resetDocumentForm(); // Reset form after saving
    }

    public function deleteDocument($document_id)
    {
        $document = \App\Models\Document::findOrFail($document_id);
        $document->delete();
        session()->flash('flash.banner', 'Document deleted successfully!');
        $this->documentForm->resetDocumentForm(); // Reset form after deleting
    }

    public function restoreDocument($documentId)
    {
        $document = Document::withTrashed()->findOrFail($documentId);
        $document->restore();
        session()->flash('flash.banner', 'Document restored successfully!');
    }

    public function forceDeleteDocument($documentId)
    {
        $document = Document::withTrashed()->findOrFail($documentId);
        // Optionally delete the file from storage before force deleting the record
        if ($document->file_path && \Storage::disk('public')->exists($document->file_path)) {
            \Storage::disk('public')->delete($document->file_path);
        }
        $document->forceDelete();
        session()->flash('flash.banner', 'Document permanently deleted!');
    }

    public function mount()
    {
        \Log::debug('EmployeeIndex mount called. employee_id: ' . $this->employee_id);
        if ($this->employee_id) {
            $employee = Employee::find($this->employee_id);
            if ($employee) {
                \Log::info('Employee found in mount. Calling manageDocuments for employee ID: ' . $employee->id);
                $this->manageDocuments($employee->id);
            } else {
                \Log::warning('Employee not found in mount for ID: ' . $this->employee_id);
            }
        }
    }

    public function render()
    {
        $query = Employee::query();

        if ($this->filterStatus === 'trashed') {
            $query->onlyTrashed();
        } elseif ($this->filterStatus === 'all') {
            $query->withTrashed();
        }

        $employees = $query->latest()->paginate(10);

        return view('livewire.employee.index', [
            'employees' => $employees,
            'employeeDocuments' => $this->currentEmployee ? $this->currentEmployee->documents()->latest()->get() : collect(),
        ]);
    }
}
