<?php
namespace WTC_CHECKOUT\Modules\Contracts\Services;
defined('ABSPATH') || exit;
class ContractDownloadService {
    private $pdf_service;
    public function __construct() {
        $this->pdf_service = new PDFService();
        add_action('init', [$this, 'handle_download_request']);
    }
    public function handle_download_request() {
        if (!isset($_GET['wtc_action']) || $_GET['wtc_action'] !== 'download_contract') {
            return;
        }
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'wtc_download_contract')) {
            wp_die(esc_html__('Güvenlik doğrulaması başarısız.', 'wtc-checkout'), '', array('response' => 403));
        }
        $order_id = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
        $contract_type = isset($_GET['type']) ? sanitize_text_field(wp_unslash($_GET['type'])) : '';
        $token = isset($_GET['token']) ? sanitize_text_field(wp_unslash($_GET['token'])) : '';
        $timestamp = isset($_GET['ts']) ? (int)$_GET['ts'] : 0;
        if ($order_id <= 0) {
            wp_die(esc_html__('Geçersiz sipariş ID.', 'wtc-checkout'));
        }
        $allowed_types = array('mss', 'obf');
        if (!in_array($contract_type, $allowed_types)) {
            wp_die(esc_html__('Geçersiz sözleşme tipi.', 'wtc-checkout'));
        }
        $token_verify = $this->pdf_service->verifyToken($token, $timestamp, $order_id, $contract_type);
        if (!$token_verify) {
            wp_die(esc_html__('Geçersiz indirme linki.', 'wtc-checkout'), '', array('response' => 403));
        }
        $order = wc_get_order($order_id);
        if (!$order) {
            wp_die(esc_html__('Sipariş bulunamadı.', 'wtc-checkout'), '', array('response' => 404));
        }
        $current_user_id = get_current_user_id();
        if (!current_user_can('manage_woocommerce') && $order->get_customer_id() != $current_user_id) {
            wp_die(esc_html__('Bu sözleşmeyi görüntüleme yetkiniz yok.', 'wtc-checkout'), '', array('response' => 403));
        }
        $pdf_path = $order->get_meta('_wtc_' . $contract_type . '_pdf_path');
        if (empty($pdf_path) || !file_exists($pdf_path)) {
            wp_die(esc_html__('Sözleşme dosyası bulunamadı.', 'wtc-checkout'), '', array('response' => 404));
        }
        $upload_dir = wp_upload_dir();
        $contracts_base_dir = $upload_dir['basedir'] . '/sozlesmeler/';
        if (!str_starts_with($pdf_path, $contracts_base_dir)) {
            wp_die(esc_html__('Geçersiz dosya yolu.', 'wtc-checkout'), '', array('response' => 403));
        }
        if (!str_ends_with(strtolower($pdf_path), '.pdf')) {
            wp_die(esc_html__('Geçersiz dosya türü.', 'wtc-checkout'), '', array('response' => 403));
        }
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . basename($pdf_path) . '"');
        header('Cache-Control: private, no-store, no-cache, must-revalidate');
        header('Pragma: no-cache');
        header('Content-Length: ' . filesize($pdf_path));
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            WP_Filesystem();
        }
        $file_content = $wp_filesystem->get_contents($pdf_path);
        if ($file_content !== false) {
            // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo $file_content;
        }
        exit;
    }
} 