<?php
class ControllerProductPdfExport extends Controller {
    
    // =============================================================
    // 1. ADIM: İSTEĞİ AL, KONTROL ET VE TEMİZLİK YAP
    // =============================================================
    public function add() {
        // Dil dosyasını yükle
        $this->load->language('extension/module/pdf_catalog');

        $json = array();

        // --- A. OTOMATİK ÇÖP TEMİZLİĞİ ---
        $this->db->query("DELETE FROM " . DB_PREFIX . "pdf_queue WHERE status IN ('completed', 'failed') AND date_modified < DATE_SUB(NOW(), INTERVAL 30 MINUTE)");

        $files = glob(DIR_SYSTEM . 'storage/download/katalog_*.pdf');
        if ($files) {
            foreach ($files as $file) {
                if (is_file($file)) {
                    if (time() - filemtime($file) >= 1800) {
                        unlink($file);
                    }
                }
            }
        }
        // -------------------------------------------------------

        // Ürün var mı kontrolü
        if (empty($this->request->post['product_ids'])) {
            $json['error'] = $this->language->get('error_no_product');
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
        }

        $product_ids_clean = $this->db->escape($this->request->post['product_ids']);
        $session_id = $this->db->escape($this->session->getId());
        $product_ids_array = explode(',', $this->request->post['product_ids']);
        $product_count = count($product_ids_array);

        // --- GÜVENLİK VE LİMİT KODLARI ---
        $is_admin = false;
        try {
            if (class_exists('\Cart\User')) {
                $user = new \Cart\User($this->registry);
                if ($user->isLogged()) { $is_admin = true; }
            } else {
                $this->load->library('cart/user');
                $user = new \Cart\User($this->registry);
                if ($user->isLogged()) { $is_admin = true; }
            }
        } catch (\Exception $e) { $is_admin = false; }

        if ($is_admin) {
            $setting_limit = (int)$this->config->get('config_pdf_export_limit_admin');
        } else {
            $setting_limit = (int)$this->config->get('config_pdf_export_limit_user');
        }

        if ($setting_limit > 0 && $product_count > $setting_limit) {
            $role_name = $is_admin ? $this->language->get('text_admin') : $this->language->get('text_user');
            $json['error'] = sprintf($this->language->get('error_limit'), $role_name, $setting_limit);
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
        }
        
        // --- AKILLI KONTROL ---
        $existing_job = $this->db->query("SELECT queue_id FROM " . DB_PREFIX . "pdf_queue WHERE session_id = '" . $session_id . "' AND product_ids = '" . $product_ids_clean . "' AND status IN ('pending', 'processing') LIMIT 1");

        if ($existing_job->num_rows) {
            $json['success'] = true;
            $json['queue_id'] = $existing_job->row['queue_id'];
            $this->response->addHeader('Content-Type: application/json');
            $this->response->setOutput(json_encode($json));
            return;
        }

        // Kilitli kalan temizliği
        $this->db->query("DELETE FROM " . DB_PREFIX . "pdf_queue WHERE status = 'processing' AND date_modified < DATE_SUB(NOW(), INTERVAL 5 MINUTE)");

        // YENİ KUYRUK
        $this->db->query("INSERT INTO " . DB_PREFIX . "pdf_queue SET 
            session_id = '" . $session_id . "',
            product_ids = '" . $product_ids_clean . "',
            status = 'pending',
            date_added = NOW(),
            date_modified = NOW()");
        
        $json['success'] = true;
        $json['queue_id'] = $this->db->getLastId();
        
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    // =============================================================
    // 2. ADIM: DURUM SORGULA
    // =============================================================
public function status() {
    
    $this->load->language('extension/module/pdf_catalog');
    $queue_id = (int)$this->request->get['queue_id'];
    $json = array();

    // Stuck processing temizliği
    $this->db->query("UPDATE " . DB_PREFIX . "pdf_queue SET status = 'failed', date_modified = NOW() WHERE status = 'processing' AND date_modified < DATE_SUB(NOW(), INTERVAL 5 MINUTE)");

    $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "pdf_queue WHERE queue_id = '" . $queue_id . "'");
    
    if ($query->num_rows) {
        $my_job = $query->row;

        if ($my_job['status'] == 'completed') {
            $json['status'] = 'completed';
            $download_link = $this->url->link('product/pdf_export/download', 'f=' . $my_job['file_file']);
            $json['download'] = str_replace('&amp;', '&', $download_link);

        } elseif ($my_job['status'] == 'processing') {
            $json['status'] = 'processing';
            
        } elseif ($my_job['status'] == 'failed') {
            $json['error'] = $this->language->get('error_pdf_creation');

        } else {
            $active_or_waiting = $this->db->query("SELECT COUNT(*) as total FROM " . DB_PREFIX . "pdf_queue WHERE (status = 'processing') OR (status = 'pending' AND queue_id < '" . $queue_id . "')");
            $position = (int)$active_or_waiting->row['total'];

            if ($position == 0 && $my_job['status'] == 'pending') {
                // Sıra bende - atomik kilitleme
                $this->db->query("UPDATE " . DB_PREFIX . "pdf_queue SET status = 'processing', date_modified = NOW() WHERE queue_id = '" . (int)$queue_id . "' AND status = 'pending'");
                
                if ($this->db->countAffected() > 0) {
                    $result = $this->generatePdf($queue_id, $my_job['product_ids']);
                    
                    if ($result['status'] == 'success') {
                        $json['status'] = 'completed';
                        $download_link = $this->url->link('product/pdf_export/download', 'f=' . $result['file']);
                        $json['download'] = str_replace('&amp;', '&', $download_link);
                    } else {
                        $json['error'] = sprintf($this->language->get('error_general'), $result['message']);
                    }
                } else {
                    // Başkası kapmış, bekle
                    $json['status'] = 'waiting';
                    $json['position'] = 1;
                    $json['estimated'] = 5;
                }
            } else {
                // Önümde başka işler var
                $json['status'] = 'waiting';
                $json['position'] = $position + 1;
                $json['estimated'] = ($position + 1) * 5;
            }
        }
    } else {
        $json['error'] = $this->language->get('error_process_not_found');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

    // =============================================================
    // 3. ADIM: PDF OLUŞTUR
    // =============================================================
    private function generatePdf($queue_id, $product_ids_string) {
        // Dil dosyasını burada da yükle (Garanti olsun)
        $this->load->language('extension/module/pdf_catalog');

        try {
            $this->db->query("UPDATE " . DB_PREFIX . "pdf_queue SET status = 'processing', date_modified = NOW() WHERE queue_id = '" . (int)$queue_id . "'");

            ini_set('pcre.backtrack_limit', '5000000');
            ini_set('pcre.recursion_limit', '5000000');
            ini_set('memory_limit', '1024M');
            set_time_limit(300);

            if (file_exists(DIR_SYSTEM . 'library/vendor/autoload.php')) {
                require_once(DIR_SYSTEM . 'library/vendor/autoload.php');
            }

            $this->load->model('catalog/product');
            $this->load->model('tool/image');

            $lang_id = (int)$this->config->get('config_language_id');
            $pdf_settings = [
                'front_cover'     => $this->config->get('config_pdf_front_image'),
                'back_cover'      => $this->config->get('config_pdf_back_image'),
                'page_bg'         => $this->config->get('config_pdf_page_background'),
                'logo'            => $this->config->get('config_pdf_logo'),
                'qr_status'       => $this->config->get('config_pdf_qr_status'),
                'show_competitor' => $this->config->get('config_pdf_show_competitor'),
                'cover_text'      => $this->config->get('config_pdf_cover_text')[$lang_id] ?? '',
                'footer_text'     => $this->config->get('config_pdf_footer_text')[$lang_id] ?? '',
                'cover_color'     => $this->config->get('config_pdf_cover_color') ?: '#000000',
                'cover_font_size' => $this->config->get('config_pdf_cover_font_size') ?: '30',
                'cover_font'      => $this->config->get('config_pdf_cover_font') ?: 'dejavusans',
                'footer_color'    => $this->config->get('config_pdf_footer_color') ?: '#FFFFFF',
                'footer_size'     => $this->config->get('config_pdf_footer_font_size') ?: '8',
                'footer_font'     => $this->config->get('config_pdf_footer_font') ?: 'dejavusans',
                'cover_x'         => $this->config->get('config_pdf_cover_x') ?: '50',
                'cover_y'         => $this->config->get('config_pdf_cover_y') ?: '50',
            ];

            $mpdf = new \Mpdf\Mpdf([
                'mode' => 'utf-8', 'format' => 'A4',
                'margin_left' => 6, 'margin_right' => 6, 'margin_top' => 35, 'margin_bottom' => 20,
                'tempDir' => DIR_SYSTEM . 'storage/cache'
            ]);

            // --- 1. ÖN KAPAK ---
            if ($pdf_settings['front_cover'] && is_file(DIR_IMAGE . $pdf_settings['front_cover'])) {
                $mpdf->AddPage('P', '', '', '', '', 0, 0, 0, 0, 0, 0);
                $front_image_path = DIR_IMAGE . $pdf_settings['front_cover'];
                $html = '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0;"><img src="' . $front_image_path . '" style="width: 210mm; height: 297mm; margin: 0; padding: 0;" /></div>';
                if ($pdf_settings['cover_text']) {
                    $html .= '<div style="position: absolute; left: ' . $pdf_settings['cover_x'] . '%; top: ' . $pdf_settings['cover_y'] . '%; color: ' . $pdf_settings['cover_color'] . '; font-size: ' . $pdf_settings['cover_font_size'] . 'pt; font-family: ' . $pdf_settings['cover_font'] . ', sans-serif; font-weight: bold; z-index: 9999; white-space: nowrap;">' . $pdf_settings['cover_text'] . '</div>';
                }
                $mpdf->WriteHTML($html);
            }

            // --- İÇERİK ---
            $mpdf->AddPage('P', '', 1, '', '', 6, 6, 35, 20, 10, 5);

            $footer_style = 'color: ' . $pdf_settings['footer_color'] . '; font-family: ' . $pdf_settings['footer_font'] . ', sans-serif; font-size: ' . $pdf_settings['footer_size'] . 'pt;';
            $footer_html = '<div style="background-color: #666666; border-radius: 50px; padding: 5px 15px;">
                <table width="100%" style="border: none; border-collapse: collapse;">
                    <tr><td width="5%" style="' . $footer_style . ' font-weight: bold; text-align: left;">{PAGENO}</td>
                    <td width="95%" style="' . $footer_style . ' text-align: center;">' . $pdf_settings['footer_text'] . '</td></tr>
                </table></div>';
            $mpdf->SetHTMLFooter($footer_html);

            if ($pdf_settings['logo'] && is_file(DIR_IMAGE . $pdf_settings['logo'])) {
                $logo_path = DIR_IMAGE . $pdf_settings['logo'];
                $mpdf->SetHTMLHeader('<div style="padding: 10px; border-bottom: 3px solid #b32d2e;"><img src="'.$logo_path.'" style="height: 40px;" /></div>');
            }

            if ($pdf_settings['page_bg'] && is_file(DIR_IMAGE . $pdf_settings['page_bg'])) {
                $bg_path = DIR_IMAGE . $pdf_settings['page_bg'];
                $mpdf->SetDefaultBodyCSS('background', "url('" . $bg_path . "')");
                $mpdf->SetDefaultBodyCSS('background-image-resize', '6');
            }

            $stylesheet = "
                body { font-family: sans-serif; }
                .main-grid { width: 100%; border-collapse: collapse; table-layout: fixed; }
                .grid-cell { width: 50%; vertical-align: top; padding: 6px; }
                .product-container { width: 100%; background: #fff; }
                .prod-header { font-size: 10px; font-weight: normal; color: #000; margin-bottom: 5px; height: 14px; overflow: hidden; }
                .prod-code { font-weight: bold; }
                .layout-table { width: 100%; border-collapse: collapse; table-layout: fixed; }
                .td-img { width: 28%; vertical-align: top; text-align: center; padding-right: 2px; }
                .p-img { width: 90px; max-height: 110px; } 
                .td-mid { width: 50%; vertical-align: top; font-size: 8px; color: #000; padding-right: 2px; overflow: hidden; }
                .td-qr { width: 22%; vertical-align: top; text-align: right; }
                .spec-table { width: 100%; margin-bottom: 5px; border-collapse: collapse; }
                .spec-lbl { width: 60px; font-weight: normal; font-size: 8px; color: #666; }
                .spec-val { font-weight: bold; font-size: 8px; }
                .list-header-table { width: 100%; margin-bottom: 1px; border-bottom: 1px solid #ccc; }
                .list-head { font-size: 7px; font-weight: normal; color: #000; padding-bottom: 1px; }
                .list-content-table { width: 100%; border-collapse: collapse; font-size: 7px; table-layout: fixed; }
                .list-col-left { width: 55%; vertical-align: top; padding-right: 2px; }
                .list-col-right { width: 45%; vertical-align: top; text-align: right; }
                .item-row { display: block; margin-bottom: 1px; word-wrap: break-word; overflow-wrap: break-word; word-break: break-all; } 
            ";
            $mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);

            $product_ids = explode(',', $product_ids_string);
            $html = '<table class="main-grid">';
            $i = 0;

            // --- DİL DEĞİŞKENLERİNİ HAZIRLA ---
            $text_oe_reference = $this->language->get('text_oe_reference');
            $text_compatible_vehicles = $this->language->get('text_compatible_vehicles');

            foreach ($product_ids as $product_id) {
                $p = $this->model_catalog_product->getProduct($product_id);
                if (!$p) continue;

                $image_path = $this->model_tool_image->resizeForPDF($p['image'] ?: 'no_image.png', 400, 400);
                if (!$image_path || !is_file($image_path)) {
                    $image_path = DIR_IMAGE . 'no_image.png';
                }
                
                $product_url = $this->url->link('product/product', 'product_id=' . $product_id);
                $attributes = $this->model_catalog_product->getProductAttributes($product_id);
                $oem_results = $this->model_catalog_product->getProductOEMs($product_id, $pdf_settings['show_competitor']);
                $oem_codes = [];
                foreach ($oem_results as $oem) { $oem_codes[] = $oem['oem_code']; }
                $vehicle_counts = $this->model_catalog_product->getProductVehicleCounts($product_id);

                if ($i % 2 == 0) $html .= '<tr>';

                $html .= '<td class="grid-cell">';
                $html .= '<div class="product-container">';
                $html .= '<div class="prod-header"><span class="prod-code">' . $p['model'] . '</span> ' . $p['name'] . '</div>';
                $html .= '<table class="layout-table"><tr>';

                $html .= '<td class="td-img"><img src="' . $image_path . '" class="p-img"></td>';

                $html .= '<td class="td-mid">';
                $html .= '<table class="spec-table">';
                foreach ($attributes as $attribute_group) {
                    foreach ($attribute_group['attribute'] as $attribute) {
                        $html .= '<tr><td class="spec-lbl">' . $attribute['name'] . '</td><td class="spec-val">' . $attribute['text'] . '</td></tr>';
                    }
                }
                $html .= '</table>';

                // --- DİL DESTEKLİ BAŞLIKLAR BURADA KULLANILIYOR ---
                $html .= '<table class="list-header-table"><tr><td width="55%" class="list-head">'.$text_oe_reference.'</td><td width="45%" class="list-head" style="text-align:right;">'.$text_compatible_vehicles.'</td></tr></table>';

                $html .= '<table class="list-content-table"><tr>';
                $html .= '<td class="list-col-left">';
                if (!empty($oem_codes)) {
                    $limit = 0;
                    foreach ($oem_codes as $code) {
                        if($limit++ > 5) break;
                        $safe_code = wordwrap($code, 15, " ", true); 
                        $html .= '<span class="item-row">' . $safe_code . '</span><br>';
                    }
                } else { $html .= '-'; }
                $html .= '</td>';

                $html .= '<td class="list-col-right">';
                if (!empty($vehicle_counts)) {
                    $limit = 0;
                    foreach ($vehicle_counts as $row) {
                        if($limit++ > 5) break;
                        $html .= '<div class="item-row">' . $row['marka'] . ' <b>' . $row['toplam'] . '</b></div>';
                    }
                } else { $html .= '-'; }
                $html .= '</td>';
                $html .= '</tr></table>';
                $html .= '</td>';

                $html .= '<td class="td-qr">';
                if ($pdf_settings['qr_status']) {
                    $html .= '<barcode code="' . $product_url . '" type="QR" size="0.5" error="M" disableborder="1" />';
                }
                $html .= '</td>';

                $html .= '</tr></table></div></td>';

                if ($i % 2 == 1) $html .= '</tr>';
                $i++;
            }
            
            if ($i % 2 != 0) $html .= '<td class="grid-cell">&nbsp;</td></tr>';
            $html .= '</table>';
            
            $mpdf->WriteHTML($html);

            // --- ARKA KAPAK ---
            if ($pdf_settings['back_cover'] && is_file(DIR_IMAGE . $pdf_settings['back_cover'])) {
                $mpdf->AddPage('P', '', '', '', '', 0, 0, 0, 0, 0, 0);
                $mpdf->SetHTMLHeader(''); $mpdf->SetHTMLFooter('');
                $back_image_path = DIR_IMAGE . $pdf_settings['back_cover'];
                $html = '<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;"><img src="' . $back_image_path . '" style="width: 210mm; height: 297mm;" /></div>';
                $mpdf->WriteHTML($html);
            }

            // DOSYAYI KAYDET
            $filename = 'katalog_' . $queue_id . '_' . time() . '.pdf';
            if (!is_dir(DIR_SYSTEM . 'storage/download/')) {
                 mkdir(DIR_SYSTEM . 'storage/download/', 0777, true);
            }
            $filepath = DIR_SYSTEM . 'storage/download/' . $filename;
            
            $mpdf->Output($filepath, 'F');

            $this->db->query("UPDATE " . DB_PREFIX . "pdf_queue SET status = 'completed', file_file = '" . $this->db->escape($filename) . "', date_modified = NOW() WHERE queue_id = '" . (int)$queue_id . "'");
            
            return ['status' => 'success', 'file' => $filename];

        } catch (Exception $e) {
            $this->db->query("UPDATE " . DB_PREFIX . "pdf_queue SET status = 'failed', date_modified = NOW() WHERE queue_id = '" . (int)$queue_id . "'");
            return ['status' => 'error', 'message' => $e->getMessage()];
        }
    }

public function download() {
    $this->load->language('extension/module/pdf_catalog');
    
    if (!isset($this->request->get['f'])) {
        echo $this->language->get('error_file_missing');
        return;
    }

    $filename = basename($this->request->get['f']);
    $file = DIR_SYSTEM . 'storage/download/' . $filename;

    if (file_exists($file)) {
        // ============================================
        // ÜLKE BAZLI İNDİRME İSTATİSTİĞİ KAYDET
        // ============================================
        $this->trackDownload();
        // ============================================
        
        // Tüm buffer'ları temizle
        while (ob_get_level()) {
            ob_end_clean();
        }
        
        // Output buffering'i kapat
        @ini_set('output_buffering', 'Off');
        @ini_set('zlib.output_compression', 'Off');
        @ini_set('implicit_flush', '1');
        
        // Headers
        header('Content-Description: File Transfer');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="'.basename($filename).'"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        
        // Chunk'lı okuma (hızlı indirme)
        $handle = fopen($file, 'rb');
        if ($handle) {
            while (!feof($handle)) {
                echo fread($handle, 1024 * 1024); // 1MB chunk
                flush();
            }
            fclose($handle);
        }
        exit;
    } else {
        echo $this->language->get('error_file_not_found');
    }
}

// ============================================
// ÜLKE TESPİT VE KAYIT FONKSİYONU
// ============================================
private function trackDownload() {
    $ip = $this->getClientIP();
    $country_data = $this->getCountryFromIP($ip);
    
    if ($country_data) {
        // Ülke daha önce var mı kontrol et
        $check = $this->db->query("SELECT * FROM " . DB_PREFIX . "pdf_download_stats WHERE country_code = '" . $this->db->escape($country_data['code']) . "'");
        
        if ($check->num_rows) {
            // Varsa sadece sayacı artır
            $this->db->query("UPDATE " . DB_PREFIX . "pdf_download_stats SET 
                download_count = download_count + 1,
                last_download_date = NOW()
                WHERE country_code = '" . $this->db->escape($country_data['code']) . "'");
        } else {
            // Yoksa yeni kayıt ekle
            $this->db->query("INSERT INTO " . DB_PREFIX . "pdf_download_stats SET 
                country_code = '" . $this->db->escape($country_data['code']) . "',
                country_name = '" . $this->db->escape($country_data['name']) . "',
                download_count = 1,
                first_download_date = NOW(),
                last_download_date = NOW()");
        }
    }
}

// IP adresini al
private function getClientIP() {
    $ip = '';
    
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    
    return $ip;
}

// IP'den ülke bilgisi al (Ücretsiz API kullanarak)
private function getCountryFromIP($ip) {
    // Localhost kontrolü
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return ['code' => 'TR', 'name' => 'Turkey (Localhost)'];
    }
    
    try {
        // ip-api.com kullanarak (ücretsiz, dakikada 45 istek limiti var)
        $url = "http://ip-api.com/json/{$ip}?fields=status,country,countryCode";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $response = curl_exec($ch);
        curl_close($ch);
        
        if ($response) {
            $data = json_decode($response, true);
            
            if ($data && $data['status'] == 'success') {
                return [
                    'code' => $data['countryCode'],
                    'name' => $data['country']
                ];
            }
        }
    } catch (Exception $e) {
        // Hata durumunda varsayılan değer
    }
    
    // API başarısız olursa veya hata varsa varsayılan ülke
    return ['code' => 'XX', 'name' => 'Unknown'];
}
}
?>