<?php
/**
 * CargoHub Free Email Class
 * 
 * Handles email notifications for the FREE version (limited functionality)
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class CargoHub_Free_Email {
    
    /**
     * Database instance
     */
    private $database;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->database = new CargoHub_Free_Database();
        $this->init_hooks();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Only basic email functionality in FREE version
        add_action('cargohub_free_tracking_added', array($this, 'send_tracking_email'), 10, 3);
    }
    
    /**
     * Send tracking email to customer (Fixed template in FREE version)
     * 
     * @param int $order_id
     * @param string $carrier
     * @param string $tracking_number
     * @return bool
     */
    public function send_tracking_email($order_id, $carrier, $tracking_number) {
        try {
            // Avoid heavy backtrace in production; keep a lightweight marker
            CargoHub_Free_Logger::info("Email trigger for order {$order_id}");
            
            $order = wc_get_order($order_id);
            
            if (!$order) {
                CargoHub_Free_Logger::error("Order not found for tracking email: {$order_id}");
                return false;
            }
            
            // Check for changes in tracking data to determine if email should be sent
            $current_tracking_hash = md5($carrier . '|' . $tracking_number);
            $last_email_hash = is_object($order) && method_exists($order, 'get_meta') ? $order->get_meta('_cargohub_last_email_hash') : '';
            if (empty($last_email_hash)) {
                $last_email_hash = get_post_meta($order_id, '_cargohub_last_email_hash', true);
            }
            
            if ($current_tracking_hash === $last_email_hash) {
                CargoHub_Free_Logger::info("Tracking data unchanged for order {$order_id}, skipping email.");
                return true; // Return true since no change occurred
            }
            
            $customer_email = $order->get_billing_email();
            $customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
            
            if (empty($customer_email)) {
                CargoHub_Free_Logger::error("No customer email found for order: {$order_id}");
                return false;
            }
            
            // Get carrier information
            $carrier_info = CargoHub_Free_Carriers::get_carrier($carrier);
            $carrier_name = $carrier_info ? $carrier_info['name'] : ucfirst($carrier);
            // For email, we only want the base tracking URL without the tracking number
            $tracking_url = ($carrier_info && isset($carrier_info['tracking_url'])) ? $carrier_info['tracking_url'] : null;
            $formatted_tracking = CargoHub_Free_Carriers::format_tracking_number($tracking_number, $carrier);
            
            // Fixed email template for FREE version (not customizable)
            $subject = sprintf(
                /* translators: %s: sipariş numarası. */
                __('Siparişiniz #%s kargoya verildi!', 'cargohub-kargo-takip'),
                $order->get_order_number()
            );
            
            $message = $this->get_free_email_template($order, $carrier_name, $formatted_tracking, $tracking_url, $customer_name);
            
            // Email headers
            $headers = array(
                'Content-Type: text/html; charset=UTF-8',
                'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>'
            );
            
            $sent = wp_mail($customer_email, $subject, $message, $headers);
            
            if ($sent) {
                // Update tracking hash to prevent sending same email again
                if (is_object($order) && method_exists($order, 'update_meta_data')) {
                    $order->update_meta_data('_cargohub_last_email_hash', $current_tracking_hash);
                    $order->update_meta_data('_cargohub_tracking_email_sent', 1);
                    $order->save_meta_data();
                }
                update_post_meta($order_id, '_cargohub_last_email_hash', $current_tracking_hash);
                update_post_meta($order_id, '_cargohub_tracking_email_sent', 1);
                CargoHub_Free_Logger::info("Tracking email sent successfully to {$customer_email} for order {$order_id}. Hash: {$current_tracking_hash}");
                return true;
            } else {
                CargoHub_Free_Logger::error("Failed to send tracking email to {$customer_email} for order {$order_id}");
                return false;
            }
            
        } catch (Exception $e) {
            CargoHub_Free_Logger::critical("Email sending failed: " . $e->getMessage(), array(
                'order_id' => $order_id,
                'carrier' => $carrier,
                'tracking_number' => $tracking_number
            ));
            return false;
        }
    }
    
    /**
     * Get fixed email template for FREE version
     * 
     * @param WC_Order $order
     * @param string $carrier_name
     * @param string $formatted_tracking
     * @param string $tracking_url
     * @param string $customer_name
     * @return string
     */
    private function get_free_email_template($order, $carrier_name, $formatted_tracking, $tracking_url, $customer_name) {
        ob_start();
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title><?php esc_html_e('Siparişiniz Kargoya Verildi', 'cargohub-kargo-takip'); ?></title>
            
        </head>
        <body style="margin:0;padding:0;background:#f4f4f4;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;">
            <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#f4f4f4;">
                <tr>
                    <td align="center">
                        <table role="presentation" cellpadding="0" cellspacing="0" width="600" class="container" style="width:600px;max-width:100%;background:#ffffff;border-collapse:separate;border-radius:10px;">
                            <tr>
                                <td align="center" style="padding:24px 24px 12px 24px;border-bottom:2px solid #0073aa;">
                                    <h1 style="margin:0;font-family:Arial,sans-serif;font-size:24px;line-height:1.3;color:#0073aa;"><?php echo esc_html(get_bloginfo('name')); ?></h1>
                                     <p style="margin:8px 0 0 0;font-family:Arial,sans-serif;font-size:14px;color:#333333;">&nbsp;<?php esc_html_e('Siparişiniz kargoya verildi!', 'cargohub-kargo-takip'); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <td class="p-24" style="padding:24px;font-family:Arial,sans-serif;color:#333333;">
                                     <?php /* translators: %s: müşteri adı. */ ?>
                                     <p style="margin:0 0 12px 0;">&nbsp;<?php printf(esc_html__('Sayın %s,', 'cargohub-kargo-takip'), esc_html($customer_name)); ?></p>
                                    <p style="margin:0 0 20px 0;">
                                        <span style="font-size:12px;line-height:1;vertical-align:baseline;">✨</span>
                                        <?php
                                        printf(
                                            /* translators: 1: sipariş numarası, 2: kargo firması adı. */
                                            esc_html__('Size güzel bir haberimiz var! #%1$s numaralı siparişiniz %2$s ile gönderildi ve size doğru yola çıktı.', 'cargohub-kargo-takip'),
                                            esc_html($order->get_order_number()),
                                            esc_html($carrier_name)
                                        ); ?>
                                        <span style="font-size:12px;line-height:1;vertical-align:baseline;">✨</span>
                                    </p>

                                    <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:8px;">
                                        <tr>
                                            <td align="center" style="padding:20px 16px 8px 16px;">
                                                <h3 style="margin:0;font-family:Arial,sans-serif;font-size:18px;color:#333333;">
                                                    <span style="font-size:14px;line-height:1;vertical-align:baseline;">📦</span>
                                                     <?php esc_html_e('Takip Bilgileri', 'cargohub-kargo-takip'); ?>
                                                </h3>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="center" style="padding:6px 16px;">
                                                <p style="margin:0;font-family:Arial,sans-serif;font-size:14px;color:#333333;"><strong><?php esc_html_e('Kargo Firması:', 'cargohub-kargo-takip'); ?></strong> <?php echo esc_html($carrier_name); ?></p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="center" style="padding:6px 16px;">
                                                <p style="margin:0 0 6px 0;font-family:Arial,sans-serif;font-size:14px;color:#333333;"><strong><?php echo esc_html__('Takip Numarası:', 'cargohub-kargo-takip'); ?></strong></p>
                                                <span style="display:inline-block;font-family:'Courier New',monospace;font-size:16px;font-weight:bold;color:#2c3e50;background:#ffffff;padding:10px 14px;border:1px solid #dddddd;border-radius:5px;letter-spacing:1px;"><?php echo esc_html($formatted_tracking); ?></span>
                                            </td>
                                        </tr>
                                        <?php if ($tracking_url): ?>
                                        <tr>
                                            <td align="center" style="padding:18px 16px 6px 16px;">
                                                <!--[if mso]>
                                                <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="<?php echo esc_url($tracking_url); ?>" style="height:44px;v-text-anchor:middle;width:300px;" arcsize="8%" strokecolor="#0073aa" fillcolor="#0073aa">
                                                    <w:anchorlock/>
                                                    <center style="color:#ffffff;font-family:Arial,sans-serif;font-size:14px;font-weight:bold;">
                                                         <?php echo esc_html__('Kargonuzu Takip Edin', 'cargohub-kargo-takip'); ?>
                                                    </center>
                                                </v:roundrect>
                                                <![endif]-->
                                                <!--[if !mso]><!-- -->
                                                <a class="btn" href="<?php echo esc_url($tracking_url); ?>" target="_blank" style="background:#0073aa;border:1px solid #0073aa;border-radius:6px;color:#ffffff;display:inline-block;font-family:Arial,sans-serif;font-size:14px;font-weight:bold;line-height:42px;text-align:center;text-decoration:none;padding:0 18px;min-width:260px;white-space:nowrap;">
                                                    <span style="font-size:14px;line-height:1;vertical-align:baseline;">🔍</span> <?php echo esc_html__('Kargonuzu Takip Edin', 'cargohub-kargo-takip'); ?>
                                                </a>
                                                <!--<![endif]-->
                                            </td>
                                        </tr>
                                        <?php endif; ?>
                                        <tr>
                                            <td align="center" style="padding:10px 16px 20px 16px;">
                                                <p style="margin:0;font-family:Arial,sans-serif;font-size:12px;color:#666666;">&nbsp;<?php esc_html_e('Paketinizi yukarıdaki takip numarasını kullanarak kargo firmasının web sitesinden de takip edebilirsiniz.', 'cargohub-kargo-takip'); ?></p>
                                            </td>
                                        </tr>
                                    </table>

                                    <p style="margin:20px 0 6px 0;font-family:Arial,sans-serif;color:#333333;">&nbsp;<?php esc_html_e('Siparişinizle ilgili herhangi bir sorunuz varsa, bizimle iletişime geçmekten çekinmeyin.', 'cargohub-kargo-takip'); ?></p>
                                    <p style="margin:0 0 10px 0;font-family:Arial,sans-serif;color:#333333;"><b><?php esc_html_e('Bizi tercih ettiğiniz için teşekkür ederiz.', 'cargohub-kargo-takip'); ?></b></p>

                                    <table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background:#fff3cd;border:1px solid #ffeaa7;border-radius:5px;">
                                        <tr>
                                            <td align="center" style="padding:12px 16px;">
                                                <p style="margin:0;font-family:Arial,sans-serif;font-size:12px;color:#856404;">&nbsp;<?php esc_html_e('📦 This email was sent using CargoHub Wordpress Free Plugin. 🎗', 'cargohub-kargo-takip'); ?></p>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td align="center" style="padding:16px 24px;border-top:1px solid #eeeeee;background:#ffffff;color:#666666;font-family:Arial,sans-serif;font-size:12px;">
                                    <p style="margin:0;"><?php echo esc_html(get_bloginfo('name')); ?> | <?php echo esc_html(get_bloginfo('url')); ?></p>
                                    <p style="margin:6px 0 0 0;"><?php esc_html_e('Powered by CargoHub', 'cargohub-kargo-takip'); ?></p>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </body>
        </html>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Get upgrade message for email customization
     * 
     * @return string
     */
    public static function get_email_upgrade_message() {
        return sprintf(
            /* translators: %s: PRO satın alma bağlantısı. */
            __('🔒 Email template customization is available in CargoHub PRO. <a href="%s" target="_blank" class="cargohub-free-upgrade-link">Upgrade now</a> to create custom email templates, add your branding, and unlock SMS notifications!', 'cargohub-kargo-takip'),
            esc_url(CARGOHUB_PRO_URL)
        );
    }
    
    /**
     * Check if custom email templates are enabled (always false in FREE)
     * 
     * @return bool
     */
    public static function is_custom_email_enabled() {
        return false; // Always false in FREE version
    }
}
