<?php

namespace App\Livewire;

use Livewire\Component;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;

class ChangePasswordForm extends Component
{
    public $newPassword, $confirmPassword;

    public function submit()
    {
        $this->validate([
            'newPassword' => 'required|min:8',
            'confirmPassword' => 'same:newPassword',
        ]);

        $token = Session::get('user.access_token');
        $admin_uuid = Session::get('user.admin_uuid');

        try {
            $response = Http::withToken($token)
                ->post(config('services.backend_api.url') . '/api/cms/login_changePassword', [
                    'admin_uuid' => $admin_uuid,
                    'password' => $this->newPassword,
                ]);

            $data = $response->json();

            if ($response->successful() && $data['code'] === 200) {
                // Update session flag to show password has been changed
                $userSession = Session::get('user');
                $userSession['is_passwordChange'] = 0;
                Session::put('user', $userSession);

                return redirect('/login');
            } else {
                $this->addError('newPassword', $data['message'] ?? 'Failed to update password');
            }
        } catch (\Exception $e) {
            $this->addError('newPassword', 'Error: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.auth.change-password-form');
    }
}
