<?php

namespace App\Http\Controllers;

use App\Models\Branches;
use App\Models\Users;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function adminlogin()
    {
        return view('auth.admin_login');
    }
    public function loginAdmin(Request $request)
    {
        $credentials = $request->only('username', 'password');
        if (auth()->attempt($credentials)) {
            $request->session()->regenerate(); // Critical fix
            session(['username' => auth()->user()->username, 'role' => auth()->user()->role, 'branch_id' => auth()->user()->branch_id]);
            return redirect()->intended('admin/dashboard');
        }
        return back()->withErrors([
            'username' => 'The provided credentials do not match our records.',
        ]);
    }

    public function logoutAdmin()
    {
        auth()->logout();
        session()->forget(['username', 'role', 'branch_id']);
        return redirect('/auth/admin-login');
    }

    public function branchlogin()
    {
        // return Hash::make(1);
        $branches = Branches::all();
        return view('auth.branch_login',['branches' => $branches]);
    }
    public function loginBranch(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'password' => 'required',
            'branch_id' => 'required|exists:branches,branch_id',
        ]);

        $user = Users::where('username', $request->username)
                    ->where('branch_id', $request->branch_id)
                    ->where('role', 'sales')
                    ->first();

        if ($user && Hash::check($request->password, $user->password)) {
            Auth::login($user);
            session(['username' => auth()->user()->username, 'role' => auth()->user()->role, 'branch_id' => auth()->user()->branch_id]);
            return redirect()->route('sales');
        }
       
        return back()->withErrors([
            'username' => 'The provided credentials do not match our records.',
        ]);
    }

    public function logoutBranch()
    {
        auth()->logout();
        session()->forget(['username', 'role', 'branch_id']);
        return redirect('/auth/branch-login');
    }
}
