<?php
namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\{Storage, Artisan};

class Configuracion extends Component
{
    use WithFileUploads;

    // Entidad
    public string $entidad_nombre     = '';
    public string $entidad_nit        = '';
    public string $entidad_direccion  = '';
    public string $entidad_telefono   = '';
    public string $entidad_ciudad     = '';
    public string $entidad_web        = '';

    // Capital Semilla
    public string $smmlv              = '';
    public int    $max_smmlv          = 10;
    public int    $meses_gracia       = 6;
    public int    $puntaje_minimo     = 65;
    public string $email_comite       = '';
    public string $email_junta        = '';

    // Mail
    public string $mail_host         = '';
    public string $mail_port         = '';
    public string $mail_username     = '';
    public string $mail_password     = '';
    public string $mail_encryption   = 'tls';
    public string $mail_from_address = '';
    public string $mail_from_name    = '';

    // Logo
    public $logo_nuevo;
    public string $logo_actual = '';

    public string $tab = 'entidad';

    public function mount(): void
    {
        // Cargar valores del .env
        $this->entidad_nombre    = env('ENTIDAD_NOMBRE', config('app.name', 'FEMPHA'));
        $this->entidad_nit       = env('ENTIDAD_NIT', '');
        $this->entidad_direccion = env('ENTIDAD_DIRECCION', '');
        $this->entidad_telefono  = env('ENTIDAD_TELEFONO', '');
        $this->entidad_ciudad    = env('ENTIDAD_CIUDAD', 'Bogotá');
        $this->entidad_web       = env('ENTIDAD_WEB', 'https://www.fempha.com.co');

        $this->smmlv          = (string) env('SMMLV_VALOR', config('fempha.smmlv', 1300000));
        $this->max_smmlv      = (int) env('FEMPHA_MAX_SMMLV', config('fempha.max_smmlv', 10));
        $this->meses_gracia   = (int) env('FEMPHA_MESES_GRACIA', config('fempha.meses_gracia', 6));
        $this->puntaje_minimo = (int) env('FEMPHA_PUNTAJE_MINIMO', config('fempha.puntaje_minimo', 65));
        $this->email_comite   = env('FEMPHA_EMAIL_COMITE', config('fempha.email_comite', ''));
        $this->email_junta    = env('FEMPHA_EMAIL_JUNTA', config('fempha.email_junta', ''));

        $this->mail_host         = env('MAIL_HOST', '');
        $this->mail_port         = (string) env('MAIL_PORT', '587');
        $this->mail_username     = env('MAIL_USERNAME', '');
        $this->mail_password     = env('MAIL_PASSWORD', '');
        $this->mail_encryption   = env('MAIL_ENCRYPTION', 'tls');
        $this->mail_from_address = env('MAIL_FROM_ADDRESS', '');
        $this->mail_from_name    = env('MAIL_FROM_NAME', '');

        $this->logo_actual = file_exists(public_path('images/logo.png')) ? 'logo.png' : '';
    }

    public function guardarEntidad(): void
    {
        $this->validate([
            'entidad_nombre'   => 'required|string|max:100',
            'entidad_nit'      => 'nullable|string|max:20',
            'entidad_ciudad'   => 'nullable|string|max:60',
            'entidad_telefono' => 'nullable|string|max:20',
            'entidad_web'      => 'nullable|url',
        ]);

        $this->updateEnv([
            'ENTIDAD_NOMBRE'    => $this->entidad_nombre,
            'ENTIDAD_NIT'       => $this->entidad_nit,
            'ENTIDAD_DIRECCION' => $this->entidad_direccion,
            'ENTIDAD_TELEFONO'  => $this->entidad_telefono,
            'ENTIDAD_CIUDAD'    => $this->entidad_ciudad,
            'ENTIDAD_WEB'       => $this->entidad_web,
        ]);

        Artisan::call('config:clear');
        session()->flash('success_entidad', 'Datos de la entidad actualizados.');
    }

    public function guardarCapitalSemilla(): void
    {
        $this->validate([
            'smmlv'          => 'required|numeric|min:100000',
            'max_smmlv'      => 'required|integer|min:1|max:50',
            'meses_gracia'   => 'required|integer|min:1|max:24',
            'puntaje_minimo' => 'required|integer|min:0|max:100',
            'email_comite'   => 'nullable|email',
            'email_junta'    => 'nullable|email',
        ]);

        $this->updateEnv([
            'SMMLV_VALOR'            => $this->smmlv,
            'FEMPHA_MAX_SMMLV'       => $this->max_smmlv,
            'FEMPHA_MESES_GRACIA'    => $this->meses_gracia,
            'FEMPHA_PUNTAJE_MINIMO'  => $this->puntaje_minimo,
            'FEMPHA_EMAIL_COMITE'    => $this->email_comite,
            'FEMPHA_EMAIL_JUNTA'     => $this->email_junta,
        ]);

        Artisan::call('config:clear');
        session()->flash('success_capital', 'Parámetros de Capital Semilla actualizados.');
    }

    public function guardarMail(): void
    {
        $this->validate([
            'mail_host'         => 'required|string',
            'mail_port'         => 'required|numeric',
            'mail_username'     => 'required|string',
            'mail_password'     => 'required|string',
            'mail_encryption'   => 'required|in:tls,ssl,none',
            'mail_from_address' => 'required|email',
            'mail_from_name'    => 'required|string',
        ]);

        $this->updateEnv([
            'MAIL_MAILER'       => 'smtp',
            'MAIL_HOST'         => $this->mail_host,
            'MAIL_PORT'         => $this->mail_port,
            'MAIL_USERNAME'     => $this->mail_username,
            'MAIL_PASSWORD'     => $this->mail_password,
            'MAIL_ENCRYPTION'   => $this->mail_encryption,
            'MAIL_FROM_ADDRESS' => $this->mail_from_address,
            'MAIL_FROM_NAME'    => '"' . $this->mail_from_name . '"',
        ]);

        Artisan::call('config:clear');
        session()->flash('success_mail', 'Configuración de correo actualizada.');
    }

    public function subirLogo(): void
    {
        $this->validate([
            'logo_nuevo' => 'required|image|mimes:png,jpg,jpeg|max:2048',
        ]);

        $this->logo_nuevo->storeAs('images', 'logo.png', 'public_path');

        // Guardar en public/images directamente
        $path = public_path('images/logo.png');
        if (!is_dir(dirname($path))) mkdir(dirname($path), 0755, true);
        $this->logo_nuevo->move(public_path('images'), 'logo.png');

        $this->logo_actual = 'logo.png';
        $this->logo_nuevo = null;
        session()->flash('success_logo', 'Logo actualizado correctamente.');
    }

    protected function updateEnv(array $data): void
    {
        $envPath = base_path('.env');
        $envContent = file_get_contents($envPath);

        foreach ($data as $key => $value) {
            // Escapar valor si tiene espacios
            $escapedValue = str_contains((string)$value, ' ') ? '"' . $value . '"' : $value;

            if (preg_match("/^{$key}=/m", $envContent)) {
                $envContent = preg_replace(
                    "/^{$key}=.*/m",
                    "{$key}={$escapedValue}",
                    $envContent
                );
            } else {
                $envContent .= "\n{$key}={$escapedValue}";
            }
        }

        file_put_contents($envPath, $envContent);
    }

    public function render()
    {
        return view('admin.configuracion')->layout('layouts.fempha');
    }
}