<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redirect;
use App\Services\AzureAuthService;
use Laravel\Socialite\Facades\Socialite;
use Illuminate\Support\Str;
use SocialiteProviders\Microsoft\Provider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User; 
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
class AzureAuthController extends Controller
{
    protected AzureAuthService $authService;

    public function __construct(AzureAuthService $authService)
    {
        $this->authService = $authService;
    }

    public function redirectToProvider()
    {
        return Socialite::driver('microsoft')
        ->scopes(['openid', 'offline_access', 'User.Read', 'Files.Read'])
        ->redirect();
    }

        public function handleProviderCallback(Request $request)
    {
        try {
            $user = Socialite::driver('microsoft')->stateless()->user(); 
            $email = strtolower($user->getEmail());
            $name  = $user->getName();
            $role  = null;

            // === Tentukan role berdasarkan email ===
            if (
                str_contains($email, 'adnyani') ||
                str_contains($email, 'titania')
            ) {
                $role = 'Regent';
            } elseif (
                str_contains($email, 'pebri') ||
                str_contains($email, 'pratiwi') ||
                str_contains($email, 'feybe')
            ) {
                $role = 'HIN';
            } elseif (
                str_contains($email, 'admin') ||
                str_contains($email, 'michael') ||
                str_contains($email, 'kristina') ||
                str_contains($email, 'costingho') ||
                str_contains($email, 'erlina')
            ) {
                $role = 'SUPER';
            } else {
                $role = 'Regent';
            }

            // === Buat/ambil user lokal ===
            $local = \App\Models\User::firstOrCreate(
                ['email' => $email],
                ['name' => $name, 'role' => $role]
            );

            // === Login user ke Laravel ===
            Auth::login($local, true);
            $request->session()->regenerate();

            // === Simpan session data ===
            session([
                'user' => [
                    'name'  => $user->getName(),
                    'email' => $user->getEmail(),
                    'role'  => $role,
                ],
                'graph' => [
                    'access_token'  => $user->token,
                    'refresh_token' => $user->refreshToken ?? null,
                    'expires_at'    => now()->addSeconds((int)($user->expiresIn ?? 3600))->toIso8601String(),
                ],
            ]);

            // === Validasi Role (hanya ADMIN / SUPER boleh lanjut) ===
            if (
                !in_array(strtoupper($role), ['SUPER', 'ADMIN']) &&
                (!isset($local->role_id) || $local->role_id != 1)
            ) {
                // 🚫 User tidak berhak → hapus semua session & token
                Auth::logout();
                $request->session()->invalidate();
                $request->session()->flush();
                $request->session()->regenerateToken();

                // 🚫 Redirect ke logout Microsoft global agar cookie Azure ikut terhapus
                $microsoftLogoutUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri='
                    . urlencode(route('login'));

                return redirect($microsoftLogoutUrl);
            }

            // ✅ Jika valid, lanjutkan ke halaman utama
            return redirect()->route('bc.create-transfer');

        } catch (\Exception $e) {
            Log::error('Socialite error: ' . $e->getMessage());

            // Pastikan session benar-benar bersih juga di error case
            Auth::logout();
            $request->session()->invalidate();
            $request->session()->flush();
            $request->session()->regenerateToken();

            // Langsung arahkan ulang ke Microsoft login
            return redirect()->route('login');
        }
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->flush();
        $request->session()->regenerateToken();

        // Logout juga dari Microsoft Identity (agar tidak auto-login)
        $microsoftLogoutUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/logout?post_logout_redirect_uri='
            . urlencode(route('microsoft.login'));

        return redirect($microsoftLogoutUrl);
    }
}

