<?php

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

class WPDD_Watermark {
    
    public static function apply_watermark($file_path, $order) {
        $file_extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION));
        
        if (filter_var($file_path, FILTER_VALIDATE_URL)) {
            $upload_dir = wp_upload_dir();
            if (strpos($file_path, $upload_dir['baseurl']) === 0) {
                $file_path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $file_path);
            } else {
                return false;
            }
        }
        
        if (!file_exists($file_path)) {
            return false;
        }
        
        $product_id = $order->product_id;
        $watermark_text = get_post_meta($product_id, '_wpdd_watermark_text', true);
        
        if (empty($watermark_text)) {
            $watermark_text = '{customer_email}';
        }
        
        $watermark_text = self::parse_watermark_placeholders($watermark_text, $order);
        
        switch ($file_extension) {
            case 'jpg':
            case 'jpeg':
            case 'png':
            case 'gif':
                return self::watermark_image($file_path, $watermark_text);
            case 'pdf':
                return self::watermark_pdf($file_path, $watermark_text);
            default:
                return false;
        }
    }
    
    private static function parse_watermark_placeholders($text, $order) {
        $customer = get_userdata($order->customer_id);
        
        $replacements = array(
            '{customer_name}' => $order->customer_name,
            '{customer_email}' => $order->customer_email,
            '{order_id}' => $order->order_number,
            '{date}' => date_i18n(get_option('date_format')),
            '{site_name}' => get_bloginfo('name')
        );
        
        return str_replace(array_keys($replacements), array_values($replacements), $text);
    }
    
    private static function watermark_image($file_path, $watermark_text) {
        if (!function_exists('imagecreatefrompng')) {
            return false;
        }
        
        $file_info = pathinfo($file_path);
        $extension = strtolower($file_info['extension']);
        
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                $image = imagecreatefromjpeg($file_path);
                break;
            case 'png':
                $image = imagecreatefrompng($file_path);
                break;
            case 'gif':
                $image = imagecreatefromgif($file_path);
                break;
            default:
                return false;
        }
        
        if (!$image) {
            return false;
        }
        
        $width = imagesx($image);
        $height = imagesy($image);
        
        $font_size = max(10, min(30, $width / 40));
        $font_file = WPDD_PLUGIN_PATH . 'assets/fonts/arial.ttf';
        
        if (!file_exists($font_file)) {
            $font = 5;
            $text_width = imagefontwidth($font) * strlen($watermark_text);
            $text_height = imagefontheight($font);
        } else {
            $bbox = imagettfbbox($font_size, 0, $font_file, $watermark_text);
            $text_width = $bbox[2] - $bbox[0];
            $text_height = $bbox[1] - $bbox[7];
        }
        
        $x = ($width - $text_width) / 2;
        $y = $height - 50;
        
        $text_color = imagecolorallocatealpha($image, 255, 255, 255, 30);
        $shadow_color = imagecolorallocatealpha($image, 0, 0, 0, 50);
        
        if (file_exists($font_file)) {
            imagettftext($image, $font_size, 0, $x + 2, $y + 2, $shadow_color, $font_file, $watermark_text);
            imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $watermark_text);
        } else {
            imagestring($image, $font, $x + 2, $y + 2, $watermark_text, $shadow_color);
            imagestring($image, $font, $x, $y, $watermark_text, $text_color);
        }
        
        $temp_dir = get_temp_dir();
        $temp_file = $temp_dir . 'wpdd_watermark_' . uniqid() . '.' . $extension;
        
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                imagejpeg($image, $temp_file, 90);
                break;
            case 'png':
                imagepng($image, $temp_file, 9);
                break;
            case 'gif':
                imagegif($image, $temp_file);
                break;
        }
        
        imagedestroy($image);
        
        return $temp_file;
    }
    
    private static function watermark_pdf($file_path, $watermark_text) {
        if (!class_exists('TCPDF') && !class_exists('FPDF')) {
            return self::watermark_pdf_basic($file_path, $watermark_text);
        }
        
        if (class_exists('TCPDF')) {
            return self::watermark_pdf_tcpdf($file_path, $watermark_text);
        }
        
        return false;
    }
    
    private static function watermark_pdf_basic($file_path, $watermark_text) {
        $temp_dir = get_temp_dir();
        $temp_file = $temp_dir . 'wpdd_watermark_' . uniqid() . '.pdf';
        
        if (copy($file_path, $temp_file)) {
            return $temp_file;
        }
        
        return false;
    }
    
    private static function watermark_pdf_tcpdf($file_path, $watermark_text) {
        require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
        
        $pdf = new TCPDF();
        $pdf->SetProtection(array('print'), '', null, 0, null);
        
        $pagecount = $pdf->setSourceFile($file_path);
        
        for ($i = 1; $i <= $pagecount; $i++) {
            $tplidx = $pdf->importPage($i);
            $pdf->AddPage();
            $pdf->useTemplate($tplidx);
            
            $pdf->SetFont('helvetica', '', 12);
            $pdf->SetTextColor(200, 200, 200);
            $pdf->SetAlpha(0.5);
            
            $pdf->StartTransform();
            $pdf->Rotate(45, $pdf->getPageWidth() / 2, $pdf->getPageHeight() / 2);
            $pdf->Text(
                $pdf->getPageWidth() / 2 - 50,
                $pdf->getPageHeight() / 2,
                $watermark_text
            );
            $pdf->StopTransform();
            
            $pdf->SetAlpha(1);
        }
        
        $temp_dir = get_temp_dir();
        $temp_file = $temp_dir . 'wpdd_watermark_' . uniqid() . '.pdf';
        
        $pdf->Output($temp_file, 'F');
        
        return $temp_file;
    }
    
    public static function add_text_watermark($content, $watermark_text) {
        $watermark_html = sprintf(
            '<div style="position: fixed; top: 50%%; left: 50%%; transform: translate(-50%%, -50%%) rotate(-45deg); 
                        opacity: 0.1; font-size: 48px; color: #000; z-index: -1; user-select: none;">%s</div>',
            esc_html($watermark_text)
        );
        
        return $watermark_html . $content;
    }
    
    public static function get_watermark_settings() {
        return array(
            'enabled' => get_option('wpdd_watermark_enabled', false),
            'text' => get_option('wpdd_watermark_text', '{customer_email}'),
            'position' => get_option('wpdd_watermark_position', 'center'),
            'opacity' => get_option('wpdd_watermark_opacity', 30),
            'font_size' => get_option('wpdd_watermark_font_size', 'auto'),
            'color' => get_option('wpdd_watermark_color', '#ffffff')
        );
    }
    
    public static function preview_watermark($file_type = 'image') {
        $settings = self::get_watermark_settings();
        $preview_text = str_replace(
            array('{customer_name}', '{customer_email}', '{order_id}', '{date}', '{site_name}'),
            array('John Doe', 'john@example.com', 'WPDD-123456', date_i18n(get_option('date_format')), get_bloginfo('name')),
            $settings['text']
        );
        
        if ($file_type === 'image') {
            $width = 600;
            $height = 400;
            
            $image = imagecreatetruecolor($width, $height);
            $bg_color = imagecolorallocate($image, 240, 240, 240);
            imagefill($image, 0, 0, $bg_color);
            
            $text_color = imagecolorallocatealpha($image, 100, 100, 100, 50);
            
            $font_size = 20;
            $x = ($width - (strlen($preview_text) * 10)) / 2;
            $y = $height / 2;
            
            imagestring($image, 5, $x, $y, $preview_text, $text_color);
            
            header('Content-Type: image/png');
            imagepng($image);
            imagedestroy($image);
        }
    }
}