<?php

// namespace App\Http\Controllers\authentications;

// use App\Http\Controllers\Controller;
// use Illuminate\Http\Request;
// use Illuminate\Support\Facades\Auth;
// use Illuminate\Support\Facades\Hash;
// use App\Models\User;

// class LoginController extends Controller
// {
//     // Show login page
//     public function showLoginForm()
//     {
//         if (Auth::check()) {
//             return redirect()->route('dashboard-analytics');
//         }

//         return view('content.authentications.login');
//     }

//     // Handle login POST
//  public function login(Request $request)
// {
//     $request->validate([
//         'name' => 'required|string|max:255',
//         'password' => 'required|string',
//     ]);

//     $user = User::where('u_email', $request->name)->first();
//     if ($user && Hash::check($request->password, $user->password)) {
//         Auth::login($user);
//         //dd(Auth::check(), Auth::user(), url()->previous());
//         //$request->session()->regenerate();
//         return redirect()->route('dashboard-analytics')->with('success', 'Welcome back, ' . $user->u_name . '!');
//     }

//     return back()->withErrors(['Invalid username or password.']);
// }

// // Handle logout
// public function logout(Request $request)
//     {
//         Auth::logout();
//         return redirect()->route('login');
//     }


// public function loginsso(string $email)
// {

//     $user = User::where('u_email', $email)->first();
//     if ($user) {
//         Auth::login($user);
//         //dd(Auth::check(), Auth::user(), url()->previous());
//         //$request->session()->regenerate();
//         return redirect()->route('dashboard-analytics')->with('success', 'Welcome back, ' . $user->u_name . '!');
//     }
//     else
//     {
//         // please insert function to create account in database
//     }
// }

// }



namespace App\Http\Controllers\authentications;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\User;

class LoginController extends Controller
{
    // Show login page
    public function showLoginForm()
    {
        if (Auth::check()) {
            return redirect()->route('dashboard-analytics');
        }
        return view('content.authentications.login');
    }

    // Handle form login (username = email)
    public function login(Request $request)
    {
        $request->validate([
            'name'     => 'required|string|max:255', // email
            'password' => 'required|string',
        ]);

        $user = User::where('u_email', $request->string('name'))->first();
        if ($user && Hash::check($request->string('password'), $user->password)) {
            Auth::login($user);
            $request->session()->regenerate();

            return redirect()
                ->route('dashboard-analytics')
                ->with('success', 'Welcome back, ' . $user->u_name . '!');
        }

        return back()->withErrors(['Invalid username or password.']);
    }

    // Handle logout
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('login');
    }

    /**
     * SSO login endpoint (called by public/sso/index.php via POST)
     * Accepts: email (required), and optional attributes.
     * If user doesn't exist, auto-create with basic fields.
     */
    public function loginsso(Request $request)
    {
        // In dev/local, allow override via 'email_override'
        if (app()->environment(['local', 'development', 'dev']) && $request->filled('email_override')) {
            $request->merge(['email' => $request->string('email_override')->toString()]);
        }

        $email = $request->string('email')->trim()->toString();
        if ($email === '') {
            return response('SSO email missing', 400);
        }

        // Optional extras from SAML (if you pass them): used to populate name etc.
        $upn     = $request->string('userPrincipalName')->toString();
        $sam     = $request->string('samAccountName')->toString();
        $attrs   = $request->input('attributes', []); // array from SP if provided

        // Try find user
        $user = User::where('u_email', $email)->first();

        // If not found, create one (minimal fields). Adjust to your schema.
        if (!$user) {
            // Decide a display name: prefer CN / displayName / UPN local part / samAccountName
            $displayName =
                data_get($attrs, 'displayName.0') ?:
                data_get($attrs, 'cn.0') ?:
                ($upn ? explode('@', $upn)[0] : null) ?:
                ($sam ?: explode('@', $email)[0]);

            $user = User::create([
                'u_name'   => $displayName ?: 'SSO User',
                'u_email'  => $email,
                // Random password so local login won’t accidentally work; users log in via SSO
                'password' => Hash::make(Str::random(40)),
                // Add/adjust any required columns in your users table:
                // 'role'   => 'user',
                // 'status' => 'active',
            ]);
            Log::info('SSO auto-created user', ['email' => $email, 'name' => $displayName]);
        }

        // Log in and regenerate session
        Auth::login($user);
        $request->session()->regenerate();

        // Keep some SSO context in session (optional)
        session([
            'samlSessionIndex' => $request->string('samlSessionIndex')->toString(),
            'sso_upn'          => $upn,
            'sso_sam'          => $sam,
        ]);

        return redirect()
            ->route('dashboard-analytics')
            ->with('success', 'Welcome back, ' . $user->u_name . '!');
    }
}
