<?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 FirstLogin extends Component
{
    // Component properties
    public $name;
    public $cognome;
    public $email;
    public $telefono;
    public $cellulare;
    public $password;
    public $password_confirmation;
    public $isLoading = false; // Make sure this is defined

    protected $rules = [
        'password' => 'required|min:6|confirmed',
        'password_confirmation' => 'required|min:6',
    ];

    protected $messages = [
        'password.required' => 'La password è obbligatoria',
        'password.min' => 'La password deve essere di almeno 6 caratteri',
        'password.confirmed' => 'Le password non coincidono',
        'password_confirmation.required' => 'Conferma la password',
    ];

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

    public function mount()
    {
        $currentUser = Auth::user();

        if ($currentUser->first_login_completed) {
            return redirect('/dashboard');
        }

        $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 completeProfile()
    {
        $this->isLoading = true;

        $this->validate();

        $currentUser = Auth::user();

        try {
            DB::beginTransaction();

            $user = \App\Models\User::findOrFail($currentUser->id);
            $oldEmail = $user->email;

            $user->password = Hash::make($this->password);
            $user->first_login_completed = true;
            $user->email_verified_at = now();
            $user->save();

            $this->updateMasterDatabase($currentUser, $oldEmail);

            DB::commit();

            $this->sendAccountActivationEmail($user);

            session()->flash('success', 'Profilo completato con successo! Benvenuto in Leezard.cloud.');

            $this->isLoading = false;

            return redirect('/dashboard');

        } catch (\Exception $e) {
            DB::rollback();

            Log::error('First login profile completion failed', [
                'user_id' => $currentUser->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            $this->isLoading = false;
            session()->flash('error', 'Errore durante il completamento del profilo: ' . $e->getMessage());
        }
    }

    private function updateMasterDatabase($currentUser, $oldEmail)
    {
        try {
            $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 = [
                'password' => Hash::make($this->password),
                'first_login_completed' => true,
                'email_verified_at' => now(),
                'updated_at' => now()
            ];

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

            if ($updated) {
                Log::info('Successfully updated user in master database during first login', [
                    'old_email' => $oldEmail,
                    'new_email' => $this->email
                ]);
            }

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

    private function sendAccountActivationEmail($user)
    {
        try {
            $emailData = [
                'name' => $user->name,
                'email' => $user->email,
                'login_url' => url('/'),
                'activation_time' => now()->format('d/m/Y H:i'),
                'platform_name' => 'Leezard.cloud'
            ];

            Mail::send('emails.account-activated', $emailData, function ($message) use ($user) {
                $message->to($user->email, $user->name)
                        ->subject('Il tuo account è attivo – Benvenuto in Leezard.cloud')
                        ->from(config('mail.from.address'), config('mail.from.name'));
            });

            Log::info('Account activation email sent after first login completion', [
                'user_id' => $user->id,
                'email' => $user->email
            ]);

        } catch (\Exception $e) {
            Log::error('Failed to send account activation email', [
                'user_id' => $user->id,
                'email' => $user->email,
                'error' => $e->getMessage()
            ]);
        }
    }

    public function render()
    {
        return view('livewire.first-login');
    }
}
