<?php

namespace App\Livewire\Forms;

use App\Models\Document;
use Livewire\Form;
use Livewire\WithFileUploads;

class DocumentForm extends Form
{
    use WithFileUploads; // Required for file uploads

    public ?Document $document = null;

    public $documentable_id;

    public $documentable_type;

    public $name = '';

    public $description = '';

    public $file_path = ''; // For existing file path

    public $file; // For new file upload

    public $issue_date = '';

    public $expiry_date = '';

    public $status = 'valid';

    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:2048', // Max 2MB, allowed types
            'file_path' => 'nullable|string|url', // For URL input
            'issue_date' => 'nullable|date',
            'expiry_date' => 'nullable|date|after_or_equal:issue_date',
            'status' => 'required|in:valid,expired,pending_review',
            'documentable_id' => 'required',
            'documentable_type' => 'required|string',
        ];
    }

    public function setDocument(Document $document)
    {
        $this->document = $document;
        $this->name = $document->name;
        $this->description = $document->description;
        $this->file_path = $document->file_path;
        $this->issue_date = $document->issue_date?->format('Y-m-d');
        $this->expiry_date = $document->expiry_date?->format('Y-m-d');
        $this->status = $document->status;
        $this->documentable_id = $document->documentable_id;
        $this->documentable_type = $document->documentable_type;
    }

    public function store()
    {
        $validated = $this->validate();

        if ($this->file) {
            $validated['file_path'] = $this->file->store('documents', 'public'); // Store in storage/app/public/documents
        } else {
            // If no file uploaded, use the file_path from the input (which could be a URL)
            $validated['file_path'] = $this->file_path;
        }

        Document::create($validated);
    }

    public function update()
    {
        $validated = $this->validate();

        if ($this->file) {
            // Delete old file if exists
            if ($this->document->file_path && \Storage::disk('public')->exists($this->document->file_path)) {
                \Storage::disk('public')->delete($this->document->file_path);
            }
            $validated['file_path'] = $this->file->store('documents', 'public');
        } else {
            // If no new file, use the file_path from the input (which could be a URL)
            $validated['file_path'] = $this->file_path;
        }

        $this->document->update($validated);
    }

    public function resetDocumentForm()
    {
        $this->reset(['document', 'name', 'description', 'file_path', 'file', 'issue_date', 'expiry_date', 'status']);
    }
}
