<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Models\School;

class AdminAuthController extends Controller
{
    public function showLogin()
    {
        return view('admin.auth.login');
    }


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

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();



            return redirect()->intended('admin.dashboard');
        }

        return back()->withErrors([
            'username' => 'The provided credentials do not match our records.',
        ])->onlyInput('username');
    }

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

//     public function login(LoginRequest $request)
//     {

//     //    dd($request->all());
//        // $schooldb = School::on('central')->where('name', $request->school)->first();
//         $school = DB::connection('central')
//                     ->table('schools')
//                     ->where('name', $request->school)
//                     ->first();
//         if (! $school) {
//             return back()->withErrors(['school' => 'Selected school not found.']);
//         }
//         $request->session()->put('school_database', $school->database_name);
//         $request->session()->put('school', $request->school);

//         $request->authenticate();

//         // Config::set('database.connections.mysql.database', $school->database_name);
//         // DB::purge('mysql');
//         // DB::reconnect('mysql');


//         $request->session()->regenerate();

//         $role = Auth::user()->role;
 
//         // Role-based redirect
//         if ($role === 'parent') {
//             return redirect()->route('parent.dashboard');
//         }

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

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