<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Kreait\Firebase\Auth as FirebaseAuth;
use Illuminate\Support\Facades\Session;
use Kreait\Firebase\Exception\Auth\InvalidPassword;
use Kreait\Firebase\Exception\Auth\UserNotFound;
use Kreait\Firebase\Exception\Auth\EmailExists;

class AuthController extends Controller
{
    protected $auth;

    public function __construct(FirebaseAuth $auth)
    {
        $this->auth = $auth;
    }

    // ── LOGIN ──────────────────────────────────────────
    public function showLogin()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'password' => 'required',
        ]);

        try {
            $signInResult = $this->auth->signInWithEmailAndPassword(
                $request->email,
                $request->password
            );

            Session::put('firebase_user', $signInResult->data());

            return redirect()->intended('/');

        } catch (InvalidPassword $e) {
            return back()->withErrors(['email' => 'Email atau password salah.']);
        } catch (UserNotFound $e) {
            return back()->withErrors(['email' => 'Akun tidak ditemukan.']);
        } catch (\Exception $e) {
            return back()->withErrors(['email' => $e->getMessage()]);
        }
    }

    public function logout()
    {
        Session::forget('firebase_user');
        return redirect()->route('login');
    }

    // ── REGISTER ───────────────────────────────────────
    public function showRegister()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $request->validate([
            'name'                  => 'required|string|max:100',
            'email'                 => 'required|email',
            'password'              => 'required|min:6|confirmed',
        ]);

        try {
            // Buat user baru di Firebase Authentication
            $user = $this->auth->createUserWithEmailAndPassword(
                $request->email,
                $request->password
            );

            // Update display name di Firebase
            $this->auth->updateUser($user->uid, [
                'displayName' => $request->name,
            ]);

            // Langsung login setelah register
            $signInResult = $this->auth->signInWithEmailAndPassword(
                $request->email,
                $request->password
            );

            Session::put('firebase_user', $signInResult->data());

            return redirect('/');

        } catch (EmailExists $e) {
            return back()->withErrors(['email' => 'Email sudah terdaftar.']);
        } catch (\Exception $e) {
            dd($e->getMessage(), $e->getCode(), get_class($e)); // ← DEBUG SEMENTARA
            return back()->withErrors(['email' => $e->getMessage()]);
        }
    }
}