<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class EnsureSalesIsValid
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // $accessCode = $request->input('access_code');
        // $department = DB::table('department_auths')
        //     ->select('access_code')
        //     ->value('department');
        //     dd($department);

        // if (!$department){
        //     $notify[] = ['error','Invalid Access Code'];
        //     dd($notify);
        $data = DB::table('department_auths')->where('department', '=', 'sales')->get();
        $accessCode = $data['access_code'];

        $validAccessCode = $accessCode; // Replace with your actual valid access code

        $providedAccessCode = $request->header('Access-Code');

        if ($providedAccessCode !== $validAccessCode) {
            return response()->json(['error' => 'Invalid access code'], 401);
        }
        else{
            return view('sales.index');
        }



        // dd('hey');

        return $next($request);
    }
}
