<?php
namespace WTC_CHECKOUT\Modules\Contracts\Services;
use Dompdf\Dompdf;
use Dompdf\Options;
defined('ABSPATH') || exit;
class PDFService {
    private $dompdf;
    private $options;
    public function __construct() {
        $this->options = new Options();
        $this->options->set('isHtml5ParserEnabled', true);
        $this->options->set('isPhpEnabled', true);
        $this->options->set('defaultFont', 'DejaVu Sans');
        $this->options->set('isFontSubsettingEnabled', true);
        $this->options->set('defaultMediaType', 'print');
    }
    public function generateContractPDF($html_content, $order_id, $contract_type, $order_date) {
        $styles = '
            <style>
                body {
                    font-family: DejaVu Sans;
                    font-size: 9pt;
                    line-height: 1.3;
                }
                h1 { font-size: 14pt; }
                h2 { font-size: 12pt; }
                h3 { font-size: 10pt; }
                .small-text { font-size: 8pt; }
                table { 
                    width: 100%;
                    border-collapse: collapse;
                }
                table td, table th {
                    padding: 3px 10px;
                    border: 1px solid #000;
                }
            </style>
        ';
        $html_content = $styles . $html_content;
        $this->dompdf = new Dompdf($this->options);
        $this->dompdf->loadHtml($html_content);
        $this->dompdf->setPaper('A4', 'portrait');
        $this->dompdf->render();
        $filename = $this->generateFileName($order_id, $contract_type, $order_date);
        $upload_dir = wp_upload_dir();
        $contracts_dir = $upload_dir['basedir'] . '/sozlesmeler/' . gmdate('Y', strtotime($order_date));
        if (!file_exists($contracts_dir)) {
            wp_mkdir_p($contracts_dir);
            file_put_contents($contracts_dir . '/index.php', '<?php // Silence is golden');
            file_put_contents($contracts_dir . '/.htaccess', "
# Nginx ve Apache için güvenlik
<FilesMatch \".(pdf)$\">
    Order Deny,Allow
    Deny from all
</FilesMatch>
# Dizin listelemesini kapat
Options -Indexes
# Özel erişim kuralı
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} !^" . site_url() . "/ [NC]
    RewriteRule \.(pdf)$ - [F,L]
</IfModule>
");
        }
        $filename = sanitize_file_name($this->generateFileName($order_id, $contract_type, $order_date));
        $file_path = $contracts_dir . '/' . $filename;
        file_put_contents($file_path, $this->dompdf->output());
        return [
            'path' => $file_path,
            'url' => $this->generateSecureUrl($order_id, $contract_type),
            'filename' => $filename
        ];
    }
    private function generateFileName($order_id, $contract_type, $order_date) {
        $unique = substr(md5($order_id . $contract_type . $order_date . wp_salt('auth')), 0, 6);
        $date_formatted = gmdate('Ymd', strtotime($order_date));
        return sprintf('%s-%s-%s-%s.pdf', 
            $order_id,
            $contract_type,
            $date_formatted,
            $unique
        );
    }
    public function getContractPath($order_id, $contract_type, $order_date) {
        $upload_dir = wp_upload_dir();
        $filename = $this->generateFileName($order_id, $contract_type, $order_date);
        return $upload_dir['basedir'] . '/sozlesmeler/' . gmdate('Y', strtotime($order_date)) . '/' . $filename;
    }
    private function generateSecureToken($order_id, $contract_type) {
        $secret_key = wp_salt('auth');  
        $timestamp = time();  
        $data = sprintf('%s|%s|%s', $order_id, $contract_type, $timestamp);
        $hash = hash('crc32b', $data . $secret_key);
        return [
            'token' => $hash,
            'timestamp' => $timestamp
        ];
    }
    public function verifyToken($token, $timestamp, $order_id, $contract_type) {
        $secret_key = wp_salt('auth');
        $data = sprintf('%s|%s|%s', $order_id, $contract_type, $timestamp);
        $expected = hash('crc32b', $data . $secret_key);
        return hash_equals($expected, $token);
    }
    public function generateSecureUrl($order_id, $contract_type) {
        $token_data = $this->generateSecureToken($order_id, $contract_type);
        $order = wc_get_order($order_id);
        $site_url = rtrim(site_url(), '/');
        $args = [
            'wtc_action' => 'download_contract',
            'order_id' => $order_id,
            'type' => $contract_type,
            'token' => $token_data['token'],
            'ts' => $token_data['timestamp']
        ];
        if ($order && !$order->get_customer_id()) {
            $args['email'] = $order->get_billing_email();
        }
        $url = add_query_arg($args, $site_url);
        return $url;
    }
} 