<?php

namespace App\Http\Livewire;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
use App\Http\Middleware\TenantMiddleware;
use Illuminate\Support\Facades\Mail;

class Profile extends Component
{
    public $editMode = false;

    public $name;
    public $cognome;
    public $email;
    public $telefono;
    public $cellulare;
    public $password;

    public function boot()
    {
        app(TenantMiddleware::class)->setupTenantConnection();
    }

    public function mount()
    {
        $currentUser = Auth::user();
        $user = \App\Models\User::findOrFail($currentUser->id);
        $this->name = $user->name;
        $this->cognome = $user->cognome;
        $this->email = $user->email;
        $this->telefono = $user->telefono;
        $this->cellulare = $user->cellulare;
    }

    public function enableEditMode()
    {
        $this->editMode = true;
    }

    public function save()
    {
        $this->validate([
            'name' => 'required',
            'cognome' => 'required',
            'email' => 'required|email',
            'password' => 'nullable|min:6',
        ]);

        $currentUser = Auth::user();

        try {
            // Update user in tenant database
            $user = \App\Models\User::findOrFail($currentUser->id);
            $oldEmail = $user->email;
            $oldName = $user->name;
            $passwordChanged = !empty($this->password);
            $emailChanged = $oldEmail !== $this->email;
            $nameChanged = $oldName !== $this->name;

            $user->name = $this->name;
            $user->cognome = $this->cognome;
            $user->email = $this->email;
            $user->telefono = $this->telefono;
            $user->cellulare = $this->cellulare;

            if ($passwordChanged) {
                $user->password = Hash::make($this->password);
            }

            $user->save();

            Log::info('Updated user in tenant database', [
                'user_id' => $user->id,
                'tenant_database' => DB::connection()->getDatabaseName(),
                'email_changed' => $emailChanged,
                'name_changed' => $nameChanged,
                'password_changed' => $passwordChanged
            ]);

            // Update master database if needed
            if ($emailChanged || $passwordChanged || $nameChanged) {
                $masterUpdated = $this->updateMasterDatabase($currentUser, $oldEmail, $passwordChanged);
            }

            // Send password change notification if password was changed
            if ($passwordChanged) {
                $notificationSent = $this->sendPasswordChangeNotification($this->email, $this->name);

                if ($notificationSent) {
                    session()->flash('message', 'Profilo aggiornato con successo! Ti abbiamo inviato una email di conferma per la modifica della password.');
                } else {
                    session()->flash('message', 'Profilo aggiornato con successo! (Errore nell\'invio dell\'email di notifica)');
                }
            } else {
                session()->flash('message', 'Profilo aggiornato con successo!');
            }

            $this->editMode = false;
            $this->password = ''; // Clear password field

        } catch (\Exception $e) {
            Log::error('Profile update failed', [
                'user_id' => $currentUser->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            session()->flash('error', 'Errore durante l\'aggiornamento: ' . $e->getMessage());
        }
    }
    /**
     * Update user information in master database
     */
    private function updateMasterDatabase($currentUser, $oldEmail, $passwordChanged)
    {
        try {
            // Store current tenant connection info
            $currentConnection = DB::getDefaultConnection();
            $currentDatabase = DB::connection()->getDatabaseName();

            Log::info('Updating master database', [
                'current_connection' => $currentConnection,
                'current_database' => $currentDatabase,
                'user_id' => $currentUser->id,
                'old_email' => $oldEmail,
                'new_email' => $this->email
            ]);

            $masterConfig = [
                'driver' => 'mysql',
                'host' => env('DB_HOST', '127.0.0.1'),
                'port' => env('DB_PORT', '3306'),
                'database' => env('DB_DATABASE'),
                'username' => env('DB_USERNAME'),
                'password' => env('DB_PASSWORD'),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => '',
                'strict' => true,
                'engine' => null,
            ];

            config(['database.connections.master_temp' => $masterConfig]);

            $updateData = [
                'name' => $this->name,
                'email' => $this->email
            ];

            if ($passwordChanged) {
                $updateData['password'] = Hash::make($this->password);
            }

            $updated = DB::connection('master_temp')
                ->table('users')
                ->where('email', $oldEmail)
                ->update($updateData);

            if ($updated) {
                Log::info('Successfully updated user in master database', [
                    'old_email' => $oldEmail,
                    'new_email' => $this->email,
                    'password_changed' => $passwordChanged
                ]);
            } else {
                Log::warning('No user found in master database to update', [
                    'email' => $oldEmail
                ]);
            }

            config(['database.default' => $currentConnection]);
            DB::purge('master_temp');
        } catch (\Exception $e) {
            Log::error('Failed to update master database', [
                'error' => $e->getMessage(),
                'user_id' => $currentUser->id,
                'old_email' => $oldEmail,
                'new_email' => $this->email
            ]);
        }
    }

    public function cancel()
    {
        return redirect()->to('/dashboard');

        // $this->editMode = false;
        // $this->password = '';

        // $this->mount();
    }

    private function resetInputFields()
    {
        $this->name = '';
        $this->cognome = '';
        $this->email = '';
        $this->telefono = '';
        $this->cellulare = '';
        $this->password = '';
    }

    public function render()
    {
        return view('livewire.profile');
    }

    private function sendPasswordChangeNotification($email, $name)
    {
        try {
            $emailData = [
                'name' => $name,
                'email' => $email,
                'change_time' => now()->format('d/m/Y H:i'),
                'ip_address' => request()->ip()
            ];

            Mail::send('emails.password-changed', $emailData, function ($message) use ($email, $name) {
                $message->to($email, $name)
                    ->subject('La tua password è stata modificata')
                    ->from(config('mail.from.address'), config('mail.from.name'));
            });

            Log::info('Password change notification sent from profile', [
                'email' => $email,
                'name' => $name
            ]);

            return true;
        } catch (\Exception $e) {
            Log::error('Failed to send password change notification from profile', [
                'email' => $email,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}
