<?php
/**
 * کلاس PWA (Progressive Web App)
 */
if (!defined('ABSPATH')) exit;

class Dima_PWA {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        if (!get_option('dima_pwa_enabled')) return;
        
        add_action('wp_head', array($this, 'add_manifest_link'));
        add_action('wp_head', array($this, 'add_theme_color'));
        add_action('wp_head', array($this, 'add_apple_meta'));
        add_action('init', array($this, 'register_service_worker'));
    }
    
    /**
     * اضافه کردن لینک manifest
     */
    public function add_manifest_link() {
        echo '<link rel="manifest" href="' . esc_url(home_url('/manifest.json')) . '">' . "\n";
    }
    
    /**
     * رنگ تم
     */
    public function add_theme_color() {
        echo '<meta name="theme-color" content="#667eea">' . "\n";
    }
    
    /**
     * متا تگ‌های اپل
     */
    public function add_apple_meta() {
        echo '<meta name="apple-mobile-web-app-capable" content="yes">' . "\n";
        echo '<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">' . "\n";
        echo '<meta name="apple-mobile-web-app-title" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
    }
    
    /**
     * ثبت Service Worker
     */
    public function register_service_worker() {
        if (isset($_GET['dima_sw']) && $_GET['dima_sw'] === '1') {
            header('Content-Type: application/javascript');
            echo $this->get_service_worker_code();
            exit;
        }
    }
    
    /**
     * کد Service Worker
     */
    private function get_service_worker_code() {
        $cache_name = 'dima-shop-v1';
        $assets = array(
            home_url('/'),
            home_url('/wp-content/plugins/dima-shop/assets/css/style.css'),
            home_url('/wp-content/plugins/dima-shop/assets/js/script.js')
        );
        
        return "
            const CACHE_NAME = '{$cache_name}';
            const ASSETS = " . wp_json_encode($assets) . ";
            
            self.addEventListener('install', event => {
                event.waitUntil(
                    caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
                );
            });
            
            self.addEventListener('fetch', event => {
                event.respondWith(
                    caches.match(event.request).then(response => {
                        return response || fetch(event.request);
                    })
                );
            });
        ";
    }
}