<?php

namespace App\Http\Controllers;

use App\Services\SupabaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class PasswordController extends Controller
{
    public function __construct(private SupabaseService $supabase)
    {
    }

    public function showChangePasswordForm()
    {
        return view('change-password');
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'new_password' => 'required|min:8|confirmed',
        ], [
            'current_password.required' => 'Password lama wajib diisi.',
            'new_password.required' => 'Password baru wajib diisi.',
            'new_password.min' => 'Password baru minimal terdiri dari 8 karakter.',
            'new_password.confirmed' => 'Konfirmasi password baru tidak cocok.',
        ]);

        $user = Session::get('user');
        $authUid = $user['auth_uid'] ?? null;

        if (!$authUid) {
            return back()->with('error', 'Sesi tidak valid. Silakan login kembali.');
        }

        try {
            // Verifikasi password lama dengan mencoba login ulang ke Supabase Auth.
            $verified = $this->supabase->signInWithPassword($user['email'], $request->current_password);
            if (!$verified) {
                return back()->with('error', 'Password lama yang Anda masukkan tidak cocok.');
            }

            // Ubah password via Admin API.
            $this->supabase->adminUpdatePassword($authUid, $request->new_password);
        } catch (\Throwable $e) {
            return back()->with('error', 'Gagal mengubah password: ' . $e->getMessage());
        }

        // Logout user untuk keamanan setelah password diubah.
        Session::flush();

        return redirect()->route('login')->with('success', 'Password berhasil diubah! Silakan login kembali dengan password baru Anda.');
    }
}
