<?php
/**
 * Custom theme update checker
 *
 * @package Theme_An_Phat
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Theme_An_Phat_Update_Checker {
    private $theme_slug;
    private $api_url;

    public function __construct() {
        $this->theme_slug = 'theme-anphat'; // Stylesheet folder name
        $this->api_url = 'https://wp-plugin.io.vn/wp-json/thoibaoviet/v1/items/67?token=thoibaoviet_secret_token';
        
        // Hooks
        add_filter( 'pre_set_site_transient_update_themes', array( $this, 'check_update' ) );
        
        // Delete transient when theme is updated
        add_action( 'upgrader_process_complete', array( $this, 'clear_update_cache' ), 10, 2 );
    }

    /**
     * Check for updates
     */
    public function check_update( $transient ) {
        if ( empty( $transient->checked ) ) {
            return $transient;
        }

        // Get cached update data or fetch new
        $update_info = get_transient( 'theme_anphat_update_info' );
        
        if ( false === $update_info ) {
            $response = wp_remote_get( $this->api_url, array(
                'timeout' => 10,
                'headers' => array(
                    'Accept' => 'application/json',
                ),
            ) );

            if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
                return $transient;
            }

            $body = wp_remote_retrieve_body( $response );
            $data = json_decode( $body, true );

            if ( ! empty( $data ) && ! empty( $data['version'] ) && ! empty( $data['download_link'] ) ) {
                $update_info = $data;
                // Cache update info for 12 hours
                set_transient( 'theme_anphat_update_info', $update_info, 12 * HOUR_IN_SECONDS );
            } else {
                return $transient;
            }
        }

        // Compare versions
        $current_theme = wp_get_theme();
        $current_version = $current_theme->get( 'Version' );

        if ( version_compare( $current_version, $update_info['version'], '<' ) ) {
            $transient->response[ $this->theme_slug ] = array(
                'theme'       => $this->theme_slug,
                'new_version' => $update_info['version'],
                'url'         => 'https://anphatpharma.com/', // Details page
                'package'     => $update_info['download_link'],
            );
        }

        return $transient;
    }

    /**
     * Clear update cache transient
     */
    public function clear_update_cache( $upgrader_object, $options ) {
        if ( isset( $options['action'] ) && $options['action'] === 'update' && isset( $options['type'] ) && $options['type'] === 'theme' ) {
            if ( isset( $options['themes'] ) && in_array( $this->theme_slug, $options['themes'] ) ) {
                delete_transient( 'theme_anphat_update_info' );
            }
        }
    }
}

new Theme_An_Phat_Update_Checker();
