<?php

namespace App\Livewire\Account;

use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('layouts.dashboard')]
class Password extends Component
{
    public User $user;

    public function mount(): void
    {
        $this->user = Auth::user();
        $this->computeCanSave();
    }

    #[Validate('required')]
    public string $current_password = '';

    #[Validate('required|min:8|confirmed')]
    public string $password = '';

    public string $password_confirmation = '';

    public bool $loading = false;

    public bool $can_save = false;

    public bool $success = false;
    public bool $error = false;
    public ?string $successMessage = null;
    public ?string $errorMessage = null;

    public function computeCanSave(): void
    {
        $this->can_save = $this->current_password !== '' && $this->password !== '' && $this->password_confirmation !== '';
    }

    public function updatedCurrentPassword(): void { $this->computeCanSave(); }
    public function updatedPassword(): void { $this->computeCanSave(); }
    public function updatedPasswordConfirmation(): void { $this->computeCanSave(); }

    public function save(): void
    {
        $this->loading = true;
        $this->validate();

        $user = Auth::user();
        if (!$user instanceof User) {
            return;
        }
        // If owner, update remote API first
        if ($user->role === 'owner') {
            $apiResult = updateApiPassword($this->password);
            if (!($apiResult['success'] ?? false)) {
                $this->loading = false;
                $this->errorMessage = $apiResult['message'] ?? 'Échec de la mise à jour du mot de passe distant';
                $this->error = true;
                return;
            }
        }

        // Update local password only if remote update succeeded (for owners) or if not owner
        $user->password = Hash::make($this->password);
        $user->save();

        $this->reset(['current_password', 'password', 'password_confirmation']);
        $this->successMessage = 'Mot de passe mis à jour.';
        $this->success = true;
        $this->loading = false;
    }

    public function render(): \Illuminate\Contracts\View\View
    {
        return view('dashboard.account.password');
    }
}


