<?php

namespace App\Observers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Database\Eloquent\Model;
use App\Models\Notice;
use App\Models\HeroSlide;
use App\Models\Teacher;
use App\Models\Setting;

class CacheObserver
{
    public function saved(Model $model)
    {
        $this->clearCache($model);
    }

    public function deleted(Model $model)
    {
        $this->clearCache($model);
    }

    protected function clearCache($model)
    {
        if ($model instanceof Notice) {
            Cache::forget('home_pinned_notices');
            Cache::forget('home_latest_notices');
            // Notice pages expire in 5 mins, acceptable.
            
            // Clear specific detail cache
            Cache::forget('notice_details_' . $model->id);
        }

        if ($model instanceof HeroSlide) {
            Cache::forget('home_hero_slides');
        }

        if ($model instanceof Teacher) {
            Cache::forget('teachers_list');
        }

        if ($model instanceof Setting) {
            Cache::forget('website_settings');
            Cache::forget('contact_info');
            Cache::forget('principal_message');
            Cache::forget('global_settings'); // Critical for header/footer updates
        }
    }
}
