<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class OptimizationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Cache view composers
        $this->registerViewComposers();
        
        // Optimize database queries
        $this->optimizeDatabase();
    }

    /**
     * Register view composers for caching
     */
    protected function registerViewComposers(): void
    {
        // Cache navigation data
        View::composer('layouts.app', function ($view) {
            $navigationData = Cache::remember('navigation_data', 3600, function () {
                return [
                    'statusList' => \App\Models\Anggota::select('status_keanggotaan')
                        ->distinct()
                        ->pluck('status_keanggotaan'),
                    'provinsiList' => \App\Models\Anggota::select('provinsi')
                        ->whereNotNull('provinsi')
                        ->distinct()
                        ->pluck('provinsi'),
                    'kategoriList' => \App\Models\JenisKegiatan::select('kategori')
                        ->whereNotNull('kategori')
                        ->distinct()
                        ->pluck('kategori'),
                ];
            });
            
            $view->with('navigationData', $navigationData);
        });
    }

    /**
     * Optimize database settings
     */
    protected function optimizeDatabase(): void
    {
        // Set connection timeout
        DB::getPdo()->setAttribute(\PDO::ATTR_TIMEOUT, 30);
        
        // Enable query caching if not in debug mode
        if (!config('app.debug')) {
            DB::getPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        }
    }
}