<?php

namespace App\Http\Controllers;

use App\Models\TransaksiModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class LoginController extends Controller
{
    public function index(){
        return view ('component.login');
    }

    public function masuk(){
        // Menghitung jumlah data unik pada kolom kode_pesanan
        $dataTotalCustomers = TransaksiModel::whereNotNull('kode_pesanan')->distinct('kode_pesanan')->count('kode_pesanan');
        $dataTotalPesanan   = TransaksiModel::whereNotNull('pesanan')->count();
        return view('index', compact('dataTotalCustomers','dataTotalPesanan'));
    }
    
    public function authenticate(Request $request)
    {
       
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);
        
 
        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
 
            return redirect()->intended('dashboard')
            ->with('success', 'Selamat Datang'. Auth::user()->name);
        }
 
        return back()->withErrors([
            'email' => 'Email atau Password anda salah!',
        ])->onlyInput('email');
    }

    
  
  
    
    public function logout(Request $request): RedirectResponse
    {
        // Log out the user
        Auth::logout();
    
        // Invalidate the session
        $request->session()->invalidate();
    
        // Remove session data completely
        $request->session()->flush();
    
        // Regenerate the session ID to avoid session fixation attacks
        $request->session()->regenerateToken();
        dd($request);
        // Generate a new payload
        $newPayload = Str::random(40); // Menghasilkan payload baru acak sepanjang 40 karakter
    
        // Update the payload in the sessions table
        DB::table('sessions')
            ->where('id', $request->session()->getId())
            ->update(['payload' => $newPayload]);
        
           
        return redirect('/');
    }
    

}
