<?php

namespace App\Livewire\Companies;

use App\Models\Company;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class CompanyManagement extends Component
{
    public string $search = '';

    public string $filterType = '';

    public string $filterEstado = '';

    public function getCompaniesProperty()
    {
        return Company::when($this->search, function ($q) {
            $s = '%'.$this->search.'%';
            $q->where(fn ($q2) => $q2
                ->where('name', 'like', $s)
                ->orWhere('apodo', 'like', $s)
                ->orWhere('tax_id', 'like', $s));
        })
            ->when($this->filterType, fn ($q) => $q->where('type', $this->filterType))
            ->when($this->filterEstado, fn ($q) => $q->where('estado', $this->filterEstado))
            ->withCount('projects')
            ->orderBy('name')
            ->get();
    }

    public function deleteCompany(Company $company): void
    {
        if ($company->logo_path) {
            Storage::disk('public')->delete($company->logo_path);
        }
        $company->delete();
        $this->dispatch('notify', 'Empresa eliminada.');
    }

    public function exportCsv()
    {
        $companies = $this->getCompaniesProperty();

        return response()->streamDownload(function () use ($companies) {
            $handle = fopen('php://output', 'w');
            fprintf($handle, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($handle, ['Nombre', 'Apodo', 'NIF/Tax ID', 'Tipo', 'Estado', 'Dirección', 'Teléfono', 'Email', 'Website', 'Proyectos', 'Creación']);
            foreach ($companies as $c) {
                fputcsv($handle, [
                    $c->name, $c->apodo ?? '', $c->tax_id ?? '',
                    $c->type, $c->estado, $c->address ?? '',
                    $c->phone ?? '', $c->email ?? '', $c->website ?? '',
                    $c->projects_count ?? 0,
                    $c->created_at?->format('d/m/Y'),
                ]);
            }
            fclose($handle);
        }, 'empresas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
    }

    public function render()
    {
        return view('livewire.companies.company-management');
    }
}
