<?php
/**
 * TamRank WebP Module (init + hooks)
 */

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

class TamRank_WebP_Module
{

    private $generator;

    public function __construct()
    {
        $this->generator = new TamRank_WebP_Generator();

        // Assets
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));

        // Hook upload
        add_filter('wp_generate_attachment_metadata', array($this, 'maybe_generate_on_upload'), 15, 2);

        // Admin notice als geen server support
        add_action('admin_notices', array($this, 'maybe_show_support_notice'));

        // Clean up generated .webp twins when an attachment is deleted.
        add_action('delete_attachment', array($this, 'delete_webp_twins'));
    }

    /**
     * Generate on upload if enabled
     */
    public function maybe_generate_on_upload($metadata, $attachment_id)
    {
        $settings = tamrank_webp_get_settings();
        if (empty($settings['auto_upload'])) {
            return $metadata;
        }

        $this->generator->generate_for_attachment($attachment_id, $settings);
        return $metadata;
    }

    /**
     * Remove the .webp twins we generated for an attachment when it is deleted,
     * so they don't linger as orphans in the uploads directory.
     */
    public function delete_webp_twins($attachment_id)
    {
        $file = get_attached_file($attachment_id);
        if (!$file) {
            return;
        }
        $candidates = array($file);

        $meta = wp_get_attachment_metadata($attachment_id);
        if (!empty($meta['sizes']) && is_array($meta['sizes'])) {
            $dir = trailingslashit(pathinfo($file, PATHINFO_DIRNAME));
            foreach ($meta['sizes'] as $size) {
                if (!empty($size['file'])) {
                    $candidates[] = $dir . $size['file'];
                }
            }
        }

        foreach ($candidates as $path) {
            $info = pathinfo($path);
            if (empty($info['dirname']) || empty($info['filename'])) {
                continue;
            }
            $webp = $info['dirname'] . '/' . $info['filename'] . '.webp';
            if (file_exists($webp)) {
                wp_delete_file($webp);
            }
        }
    }

    /**
     * Admin notice bij ontbrekende server support
     */
    public function maybe_show_support_notice()
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        if (TamRank_WebP_Generator::server_supports_webp()) {
            return;
        }
        // Only surface this on TamRank's own admin screens — never nag site-wide.
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || strpos($screen->id, 'tam-rank') === false) {
            return;
        }
        echo '<div class="notice notice-warning is-dismissible"><p><strong>TamRank WebP:</strong> ' . esc_html(tamrank__('webp_not_supported', 'WebP is not supported by this server (Imagick/GD missing or without WebP support). Enable support or contact your host.')) . '</p></div>';
    }

    /**
     * Assets registreren
     */
    public function enqueue_assets($hook)
    {
        // The WebP controls (quality slider + bulk-convert button) live only on
        // the TamRank Settings page.
        if (strpos($hook, 'tam-rank-settings') === false) {
            return;
        }

        // tam-rank-toast carries window.TamRank.confirm(), the branded dialog
        // this script asks for instead of the browser's own confirm box. It is
        // already enqueued on every TamRank page; declaring it here makes the
        // load order a guarantee rather than a coincidence.
        wp_enqueue_script(
            'tamrank-webp-admin',
            TAM_RANK_PLUGIN_URL . 'assets/js/tamrank-webp-admin.js',
            array('jquery', 'tam-rank-toast'),
            TAM_RANK_VERSION,
            true
        );

        wp_localize_script('tamrank-webp-admin', 'tamrankWebP', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('tamrank_webp_nonce'),
            'i18n'    => array(
                'converting'   => tamrank__('webp_converting', 'Converting images...'),
                'done'         => tamrank__('webp_bulk_done', 'Done — %d images processed.'),
                'error'        => tamrank__('webp_bulk_error', 'Conversion failed. Please try again.'),
                'confirm'      => tamrank__('webp_bulk_confirm', 'Generate WebP versions for all existing images? This can take a while on large libraries.'),
                'confirmTitle' => tamrank__('webp_bulk_confirm_title', 'Convert existing images?'),
                'confirmLabel' => tamrank__('webp_bulk_confirm_label', 'Convert'),
                'cancel'       => tamrank__('cancel', 'Cancel'),
            ),
        ));
    }
}

/**
 * Haal WebP settings op
 */
function tamrank_webp_get_settings($defaults_only = false)
{
    $defaults = array(
        'auto_upload' => 0,
        'quality' => 80,
        'convert_png' => 1,
        'picture_output' => 0,
        'sizes' => array('full', 'large', 'medium_large', 'medium', '1536x1536', '2048x2048')
    );
    if ($defaults_only) {
        return $defaults;
    }

    // Single source of truth: the Image-optimization UI writes into
    // tam_rank_general_settings. Map those keys onto the engine's shape so the
    // one "WebP conversion" master toggle drives BOTH conversion on upload and
    // <picture> serving (existing images without a .webp twin are skipped at
    // serve time, so flipping it on never breaks anything).
    $g = get_option('tam_rank_general_settings', array());
    $g = is_array($g) ? $g : array();
    $enabled = !empty($g['enable_webp']);

    return array(
        'auto_upload'    => $enabled ? 1 : 0,
        'quality'        => isset($g['webp_quality']) ? max(40, min(100, (int) $g['webp_quality'])) : 80,
        'convert_png'    => array_key_exists('convert_png', $g) ? (empty($g['convert_png']) ? 0 : 1) : 1,
        'picture_output' => $enabled ? 1 : 0,
        'sizes'          => $defaults['sizes'],
    );
}
