<?php
/**
 * Class ZUTALW_Plugin_Updater
 * Handles automatic updates for the plugin via the custom Django backend.
 */

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

class ZUTALW_Plugin_Updater {

    private $plugin_slug;
    private $version;
    private $api_url;

    public function __construct() {
        $this->plugin_slug = plugin_basename( dirname( __DIR__ ) . '/zuta-lucky-wheel.php' );
        $this->version     = defined( 'ZUTALW_VERSION' ) ? ZUTALW_VERSION : '1.1.0';
        
        // Dynamically build the update URL from the global constant
        $this->api_url     = ZUTALW_API_BASE_URL . 'license/check-update/';

        add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'check_update' ) );
        add_filter( 'plugins_api', array( $this, 'plugin_info' ), 20, 3 );
    }

    /**
     * Request update info from the Django backend
     */
    private function request_update_info() {
        $license_data = get_option( 'zutalw_license_info' );

        if ( ! $license_data || empty( $license_data['license_key'] ) || $license_data['license_status'] !== 'active' ) {
            return false;
        }

        $payload_data = array(
            'license_key' => $license_data['license_key'],
            'domain'      => home_url(),
            'version'     => $this->version
        );

        $json_payload = wp_json_encode( $payload_data, JSON_UNESCAPED_SLASHES );
        
        // Generate HMAC signature using the global shared secret
        $signature  = hash_hmac( 'sha256', $json_payload, ZUTALW_SHARED_SECRET );

        $args = array(
            'body'        => $json_payload,
            'headers'     => array(
                'Content-Type'       => 'application/json',
                'Accept'             => 'application/json',
                'X-Plugin-Signature' => $signature 
            ),
            'timeout'     => 15,
            'sslverify'   => false 
        );

        $response = wp_remote_post( $this->api_url, $args );

        if ( is_wp_error( $response ) ) {
            return false;
        }

        $response_code = wp_remote_retrieve_response_code( $response );
        if ( $response_code === 200 ) {
            return json_decode( wp_remote_retrieve_body( $response ) );
        }

        return false;
    }

    /**
     * Bơm thông tin bản cập nhật vào hệ thống WordPress
     */
    public function check_update( $transient ) {
        if ( empty( $transient->checked ) ) {
            return $transient;
        }

        $remote_info = $this->request_update_info();

        // Kiểm tra nếu có bản mới (version trên Django lớn hơn version hiện tại)
        if ( $remote_info && isset( $remote_info->new_version ) && version_compare( $this->version, $remote_info->new_version, '<' ) ) {
            $obj              = new stdClass();
            $obj->slug        = $this->plugin_slug;
            $obj->new_version = $remote_info->new_version;
            $obj->url         = $remote_info->url;
            $obj->package      = $remote_info->package;
            $obj->tested       = $remote_info->tested ?? '6.7';
            $obj->requires     = $remote_info->requires ?? '6.2';
            $obj->requires_php = $remote_info->requires_php ?? '7.4';
            // Icon hiển thị trong bảng Update
            $obj->icons = array(
                '1x' => ZUTALW_ASSETS_URL . 'images/icon-128x128.png',
                '2x' => ZUTALW_ASSETS_URL . 'images/icon-256x256.png'
            );

            $transient->response[ $this->plugin_slug ] = $obj;
        }

        return $transient;
    }

    /**
     * Hiển thị bảng chi tiết (Changelog) khi người dùng bấm "View version details"
     */
    public function plugin_info( $res, $action, $args ) {
        if ( 'plugin_information' !== $action || $this->plugin_slug !== $args->slug ) {
            return $res;
        }

        $remote_info = $this->request_update_info();

        if ( $remote_info ) {
            $res               = new stdClass();
            $res->name         = 'Zuta Lucky Wheel Pro';
            $res->slug         = $this->plugin_slug;
            $res->version      = $remote_info->new_version;
            $res->tested       = $remote_info->tested ?? '6.7';
            $res->requires     = $remote_info->requires ?? '6.2';
            $res->requires_php = $remote_info->requires_php ?? '7.4';
            $res->author       = 'Zuta Themes';
            $res->author_profile = 'https://zutathemes.com';
            $res->download_link  = $remote_info->package;
            $res->trunk          = $remote_info->package;
            $res->last_updated   = $remote_info->last_updated ?? date( 'Y-m-d' );
            
            $res->sections = array(
                'description' => $remote_info->sections->description ?? 'Zuta Lucky Wheel Pro Update.',
                'changelog'   => $remote_info->sections->changelog ?? '<h3>What is new?</h3><ul><li>Bug fixes and performance improvements.</li></ul>'
            );

            return $res;
        }

        return $res;
    }
}