<?php
// app/Listeners/SetUserConfigCustom.php

namespace App\Listeners;

use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class SetUserConfigCustom
{
    public function handle(Login $event)
    {
        $logged = $event->user;
        // hapus cache lama
        Cache::forget('select_stores');
        Cache::forget('menus');
        Cache::forget('global_params');

        //select option stores====================  
        $datas = DB::select("SELECT m_stores.id, m_stores.name
                            FROM users_stores
                            JOIN m_stores ON users_stores.store_id = m_stores.id
                            WHERE users_stores.user_id = ?", [$logged->id]);
        Cache::forever('select_stores', $datas); //kegunaan di navbar.blade.php
        //====================select option stores

        //access menu====================
        $qry = DB::select("SELECT replace(replace(e.name, '.index', ''), 'reports.', '') AS menus
                                        FROM users a
                                        JOIN model_has_roles b ON b.model_id = a.id AND b.model_type = 'App\Models\User'
                                        JOIN roles c ON c.id = b.role_id
                                        JOIN role_has_permissions d ON d.role_id = c.id
                                        JOIN permissions e ON e.id = d.permission_id
                                        WHERE a.id = " . $logged->id . " AND (e.name ILIKE '%.index' OR e.name ILIKE '%reports%')");

        // Ubah dari array of stdClass jadi array biasa
        $datas = array_map(fn($row) => $row->menus, $qry);
        // echo '<pre>'; print_r($menus); exit;
        Cache::forever('menus', $datas); //contoh cara panggilnya : Cache::get('menus') :: kegunaan di sidebar.blade.php
        //====================access menu

        //set variable config==================== 
        $qry = DB::select("SELECT key, value FROM m_parameter_globals WHERE f_cache_web = 1 UNION SELECT concat(key,'_2') as key, value_2 as value FROM m_parameter_globals WHERE f_cache_web = 1 AND coalesce(value_2,'') !=''");
        $datas = collect($qry)->mapWithKeys(fn($row) => [$row->key => $row->value])->toArray();
        Cache::forever('global_params', $datas); //contoh cara panggilnya : Cache::get('global_params')['error_info_emails'] ?? null  :: kegunaan di navbar.blade.php
        //====================set variable config  
    }
}
