<?php
if (!defined('ABSPATH')) exit;

class SIMPINBY_Logo {

    public static function get_pdf_logo_url() {
        $pdf = get_option("simpinby_pdf_settings", []);
        $logo_url = $pdf["logo_url"] ?? "";

        if (!$logo_url) return "";

        // If GD not available → fallback
        if (!extension_loaded("gd")) {
            return $logo_url;
        }

        $converted = self::convert_to_jpg($logo_url);
        return $converted ?: $logo_url;
    }

    private static function convert_to_jpg($logo_url) {

        // LOAD REQUIRED WP FILES (FIX FOR YOUR ERROR)
        if (!function_exists('download_url')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        if (!function_exists('wp_delete_file')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        // Upload paths
        $upload_dir = wp_upload_dir();
        $dir = trailingslashit($upload_dir["basedir"]) . "simpinby-invoice-manager/";
        $url_dir = trailingslashit($upload_dir["baseurl"]) . "simpinby-invoice-manager/";

        if (!file_exists($dir)) {
            wp_mkdir_p($dir);
        }

        // CACHE FILE (NO REPROCESSING EVERY TIME)
        $hash = md5($logo_url);
        $dest_path = $dir . "logo-" . $hash . ".jpg";
        $dest_url  = $url_dir . "logo-" . $hash . ".jpg";

        // If already exists → return instantly
        if (file_exists($dest_path)) {
            return $dest_url;
        }

        // Download file
        $tmp = download_url($logo_url);
        if (is_wp_error($tmp)) return false;

        $info = @getimagesize($tmp);
        if (!$info) {
            wp_delete_file($tmp);
            return false;
        }

        $mime = $info["mime"] ?? "";

        // If already JPG → just move
        if ($mime === "image/jpeg") {
            copy($tmp, $dest_path);
            wp_delete_file($tmp);
            return $dest_url;
        }

        // Create image resource
        if ($mime === "image/png") {
            $img = @imagecreatefrompng($tmp);
        } elseif ($mime === "image/gif") {
            $img = @imagecreatefromgif($tmp);
        } elseif ($mime === "image/webp" && function_exists('imagecreatefromwebp')) {
            $img = @imagecreatefromwebp($tmp);
        } else {
            wp_delete_file($tmp);
            return false;
        }

        if (!$img) {
            wp_delete_file($tmp);
            return false;
        }

        // Handle transparency → white background
        $w = imagesx($img);
        $h = imagesy($img);

        $bg = imagecreatetruecolor($w, $h);
        $white = imagecolorallocate($bg, 255, 255, 255);
        imagefill($bg, 0, 0, $white);
        imagecopy($bg, $img, 0, 0, 0, 0, $w, $h);

        // Save JPG
        imagejpeg($bg, $dest_path, 90);

        imagedestroy($img);
        imagedestroy($bg);
        wp_delete_file($tmp);

        return $dest_url;
    }
}