<?php
/**
 * DZQCOD CustomProducts — Dimensions, Paid Options, File Upload, Dynamic Pricing for Workshops
 */
namespace DZQCOD;
defined('ABSPATH') || exit;

class CustomProducts {
    public function __construct() {
        // Own tab + panel
        add_filter('woocommerce_product_data_tabs', [$this, 'register_tab'], 25);
        add_action('woocommerce_product_data_panels', [$this, 'panel'], 30);
        add_action('woocommerce_process_product_meta', [$this, 'save'], 30);
        add_action('admin_footer', [$this, 'admin_scripts']);
        // File upload AJAX
        add_action('wp_ajax_dzqcod_upload_file', [$this, 'handle_upload']);
        add_action('wp_ajax_nopriv_dzqcod_upload_file', [$this, 'handle_upload']);
        // Price calc AJAX
        add_action('wp_ajax_dzqcod_calc_custom_price', [$this, 'calc_price']);
        add_action('wp_ajax_nopriv_dzqcod_calc_custom_price', [$this, 'calc_price']);
    }

    public function register_tab(array $tabs): array {
        $tabs['dzqcod_custom'] = [
            'label'    => '🏭 منتج مخصص',
            'target'   => 'dzqcod_custom_data',
            'class'    => ['show_if_simple', 'show_if_variable'],
            'priority' => 85,
        ];
        return $tabs;
    }

    // ═══════════════════════════════════════════════
    //  PRODUCT METABOX — Custom Product Config
    // ═══════════════════════════════════════════════
    public function panel(): void {
        global $post; $pid = $post->ID;
        $enabled = get_post_meta($pid, '_dzqcod_custom_enabled', true);
        $pricing_mode = get_post_meta($pid, '_dzqcod_pricing_mode', true) ?: 'fixed';
        $price_per_unit = get_post_meta($pid, '_dzqcod_price_per_unit', true) ?: '';
        $unit_label = get_post_meta($pid, '_dzqcod_unit_label', true) ?: 'م²';
        $min_area = get_post_meta($pid, '_dzqcod_min_area', true) ?: '';
        $max_area = get_post_meta($pid, '_dzqcod_max_area', true) ?: '';
        $base_price = get_post_meta($pid, '_dzqcod_custom_base', true) ?: '';
        $dims = json_decode(get_post_meta($pid, '_dzqcod_dimensions', true) ?: '', true) ?: [];
        $options_json = get_post_meta($pid, '_dzqcod_paid_options', true) ?: '';
        $options = $options_json ? json_decode($options_json, true) : [];
        $upload_enabled = get_post_meta($pid, '_dzqcod_upload_enabled', true);
        $upload_types = get_post_meta($pid, '_dzqcod_upload_types', true) ?: 'jpg,png,pdf';
        $upload_max = get_post_meta($pid, '_dzqcod_upload_max_mb', true) ?: '5';
        $upload_max_files = get_post_meta($pid, '_dzqcod_upload_max_files', true) ?: '3';
        $custom_note_enabled = get_post_meta($pid, '_dzqcod_custom_note', true);
        $custom_note_label = get_post_meta($pid, '_dzqcod_custom_note_label', true) ?: 'وصف الطلب المخصص';
        ?>
<div id="dzqcod_custom_data" class="panel woocommerce_options_panel" dir="rtl" style="padding:15px">
    <div style="border-bottom:3px solid #e74c3c;padding-bottom:10px;margin-bottom:16px;display:flex;justify-content:space-between;align-items:center">
        <h3 style="margin:0;font-size:16px;color:#e74c3c">🏭 منتج/خدمة مخصصة (ورشات)</h3>
        <span style="background:#e74c3c;color:#fff;padding:2px 10px;border-radius:10px;font-size:11px">Custom Builder</span>
    </div>
    <p style="color:#888;font-size:12px;margin-bottom:14px">هذا التبويب مخصص لأصحاب الورشات — أبواب، نوافذ، أثاث، طباعة. يتحسب السعر تلقائياً حسب الأبعاد والخيارات.</p>
    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:12px;font-weight:700;background:#fff5f5;padding:10px;border-radius:8px;border:2px solid #ffcccc">
        <input type="checkbox" name="_dzqcod_custom_enabled" value="yes" <?php checked($enabled, 'yes'); ?>>
        <span>✅ تفعيل وضع المنتج المخصص لهذا المنتج</span>
    </label>

    <!-- PRICING MODE -->
    <div style="background:#fff5f5;border:1px solid #ffcccc;border-radius:8px;padding:12px;margin-bottom:12px">
        <h4 style="margin:0 0 8px;font-size:13px">💰 وضع التسعير</h4>
        <select name="_dzqcod_pricing_mode" style="padding:6px;border:1px solid #ddd;border-radius:6px;margin-bottom:8px">
            <option value="fixed" <?php selected($pricing_mode, 'fixed'); ?>>سعر ثابت + خيارات مدفوعة</option>
            <option value="area" <?php selected($pricing_mode, 'area'); ?>>حسب المساحة (طول × عرض)</option>
            <option value="linear" <?php selected($pricing_mode, 'linear'); ?>>حسب الطول فقط (متر طولي)</option>
            <option value="volume" <?php selected($pricing_mode, 'volume'); ?>>حسب الحجم (طول × عرض × ارتفاع)</option>
            <option value="weight" <?php selected($pricing_mode, 'weight'); ?>>حسب الوزن (كغ)</option>
            <option value="custom_calc" <?php selected($pricing_mode, 'custom_calc'); ?>>حساب مخصص (سعر أساسي + خيارات فقط)</option>
        </select>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <div><label style="font-size:11px;font-weight:600">سعر الوحدة (دج/وحدة)</label>
            <input type="number" name="_dzqcod_price_per_unit" value="<?php echo esc_attr($price_per_unit); ?>" style="width:100px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="5000"></div>
            <div><label style="font-size:11px;font-weight:600">وحدة القياس</label>
            <input type="text" name="_dzqcod_unit_label" value="<?php echo esc_attr($unit_label); ?>" style="width:80px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="م²"></div>
            <div><label style="font-size:11px;font-weight:600">سعر أساسي (دج)</label>
            <input type="number" name="_dzqcod_custom_base" value="<?php echo esc_attr($base_price); ?>" style="width:100px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="0"></div>
            <div><label style="font-size:11px;font-weight:600">حد أدنى</label>
            <input type="number" name="_dzqcod_min_area" value="<?php echo esc_attr($min_area); ?>" step="0.01" style="width:70px;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
            <div><label style="font-size:11px;font-weight:600">حد أقصى</label>
            <input type="number" name="_dzqcod_max_area" value="<?php echo esc_attr($max_area); ?>" step="0.01" style="width:70px;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
        </div>
    </div>

    <!-- DIMENSIONS -->
    <div style="background:#f8f8ff;border:1px solid #e0e0ff;border-radius:8px;padding:12px;margin-bottom:12px">
        <h4 style="margin:0 0 8px;font-size:13px">📐 حقول الأبعاد</h4>
        <table style="width:100%" id="dzcd"><thead><tr style="background:#f0f0ff"><th style="padding:4px;text-align:right">اسم الحقل</th><th>وحدة</th><th>الحد الأدنى</th><th>الحد الأقصى</th><th>خطوة</th><th style="width:30px">×</th></tr></thead><tbody>
        <?php foreach ($dims as $d): ?>
        <tr><td style="padding:3px"><input type="text" name="dzcd_name[]" value="<?php echo esc_attr($d['name']); ?>" style="width:100%;padding:4px" placeholder="الطول"></td>
        <td style="padding:3px"><input type="text" name="dzcd_unit[]" value="<?php echo esc_attr($d['unit'] ?? 'سم'); ?>" style="width:60px;padding:4px"></td>
        <td style="padding:3px"><input type="number" name="dzcd_min[]" value="<?php echo esc_attr($d['min'] ?? ''); ?>" style="width:60px;padding:4px" step="0.1"></td>
        <td style="padding:3px"><input type="number" name="dzcd_max[]" value="<?php echo esc_attr($d['max'] ?? ''); ?>" style="width:60px;padding:4px" step="0.1"></td>
        <td style="padding:3px"><input type="number" name="dzcd_step[]" value="<?php echo esc_attr($d['step'] ?? '1'); ?>" style="width:50px;padding:4px" step="0.1"></td>
        <td style="text-align:center"><button type="button" class="button dzcd-rm" style="color:red;padding:2px 6px">✕</button></td></tr>
        <?php endforeach; ?>
        </tbody></table>
        <button type="button" class="button" id="dzcd-add" style="margin-top:4px">➕ حقل بُعد</button>
    </div>

    <!-- PAID OPTIONS -->
    <div style="background:#f5fff5;border:1px solid #ccffcc;border-radius:8px;padding:12px;margin-bottom:12px">
        <h4 style="margin:0 0 8px;font-size:13px">✨ ميزات/خيارات مدفوعة</h4>
        <p style="font-size:11px;color:#888;margin:0 0 6px">كل ميزة يختارها العميل تُضاف لسعره</p>
        <table style="width:100%" id="dzco"><thead><tr style="background:#f0fff0"><th style="padding:4px;text-align:right">اسم الخيار</th><th>النوع</th><th>السعر الإضافي (دج)</th><th>القيم (للقائمة)</th><th style="width:30px">×</th></tr></thead><tbody>
        <?php foreach ($options as $o): ?>
        <tr><td style="padding:3px"><input type="text" name="dzco_name[]" value="<?php echo esc_attr($o['name']); ?>" style="width:100%;padding:4px" placeholder="زجاج مزدوج"></td>
        <td style="padding:3px"><select name="dzco_type[]" style="padding:4px"><option value="checkbox" <?php selected($o['type'] ?? '', 'checkbox'); ?>>صح/خطأ</option><option value="select" <?php selected($o['type'] ?? '', 'select'); ?>>قائمة اختيار</option><option value="number" <?php selected($o['type'] ?? '', 'number'); ?>>رقم (كمية)</option><option value="color_pick" <?php selected($o['type'] ?? '', 'color_pick'); ?>>لون</option></select></td>
        <td style="padding:3px"><input type="number" name="dzco_price[]" value="<?php echo esc_attr($o['price'] ?? ''); ?>" style="width:90px;padding:4px" placeholder="0"></td>
        <td style="padding:3px"><input type="text" name="dzco_values[]" value="<?php echo esc_attr($o['values'] ?? ''); ?>" style="width:100%;padding:4px" placeholder="قيمة1:1000,قيمة2:2000"></td>
        <td style="text-align:center"><button type="button" class="button dzco-rm" style="color:red;padding:2px 6px">✕</button></td></tr>
        <?php endforeach; ?>
        </tbody></table>
        <button type="button" class="button" id="dzco-add" style="margin-top:4px">➕ خيار مدفوع</button>
        <small style="color:#888;display:block;margin-top:4px">للقائمة: القيم بصيغة <code>اسم:سعر,اسم:سعر</code> مثل: <code>خشب عادي:0,خشب زان:3000,خشب بلوط:6000</code></small>
    </div>

    <!-- FILE UPLOAD -->
    <div style="background:#fff8f0;border:1px solid #ffe0b0;border-radius:8px;padding:12px;margin-bottom:12px">
        <h4 style="margin:0 0 8px;font-size:13px">📁 رفع ملفات من العميل</h4>
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:6px">
            <input type="checkbox" name="_dzqcod_upload_enabled" value="yes" <?php checked($upload_enabled, 'yes'); ?>>
            <span>السماح للعميل برفع ملفات (تصميم، صورة، مخطط...)</span>
        </label>
        <div style="display:flex;gap:8px;flex-wrap:wrap">
            <div><label style="font-size:11px;font-weight:600">الأنواع المسموحة</label>
            <input type="text" name="_dzqcod_upload_types" value="<?php echo esc_attr($upload_types); ?>" style="width:200px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="jpg,png,pdf,ai,psd"></div>
            <div><label style="font-size:11px;font-weight:600">الحجم الأقصى (MB)</label>
            <input type="number" name="_dzqcod_upload_max_mb" value="<?php echo esc_attr($upload_max); ?>" style="width:60px;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
            <div><label style="font-size:11px;font-weight:600">عدد الملفات</label>
            <input type="number" name="_dzqcod_upload_max_files" value="<?php echo esc_attr($upload_max_files); ?>" style="width:60px;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
        </div>
    </div>

    <!-- CUSTOM NOTE -->
    <div style="display:flex;gap:8px;align-items:center">
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer">
            <input type="checkbox" name="_dzqcod_custom_note" value="yes" <?php checked($custom_note_enabled, 'yes'); ?>>
            <span style="font-size:13px">📝 حقل وصف الطلب المخصص</span>
        </label>
        <input type="text" name="_dzqcod_custom_note_label" value="<?php echo esc_attr($custom_note_label); ?>" style="padding:6px;border:1px solid #ddd;border-radius:6px;flex:1" placeholder="عنوان الحقل">
    </div>
</div>
</div>
<style>#woocommerce-product-data ul.wc-tabs li.dzqcod_custom_options a::before{content:'\f513';font-family:dashicons;color:#e74c3c}</style>
        <?php
    }

    public function save(int $pid): void {
        $fields = ['_dzqcod_custom_enabled', '_dzqcod_pricing_mode', '_dzqcod_price_per_unit', '_dzqcod_unit_label',
            '_dzqcod_custom_base', '_dzqcod_min_area', '_dzqcod_max_area', '_dzqcod_upload_enabled',
            '_dzqcod_upload_types', '_dzqcod_upload_max_mb', '_dzqcod_upload_max_files',
            '_dzqcod_custom_note', '_dzqcod_custom_note_label'];
        foreach ($fields as $f) {
            $v = sanitize_text_field($_POST[$f] ?? '');
            if (in_array($f, ['_dzqcod_custom_enabled', '_dzqcod_upload_enabled', '_dzqcod_custom_note']))
                $v = isset($_POST[$f]) ? 'yes' : 'no';
            update_post_meta($pid, $f, $v);
        }
        // Dimensions
        if (isset($_POST['dzcd_name']) && is_array($_POST['dzcd_name'])) {
            $dims = [];
            foreach ($_POST['dzcd_name'] as $i => $name) {
                $name = sanitize_text_field($name); if (!$name) continue;
                $dims[] = ['name' => $name, 'unit' => sanitize_text_field($_POST['dzcd_unit'][$i] ?? 'سم'),
                    'min' => floatval($_POST['dzcd_min'][$i] ?? 0), 'max' => floatval($_POST['dzcd_max'][$i] ?? 0),
                    'step' => floatval($_POST['dzcd_step'][$i] ?? 1)];
            }
            update_post_meta($pid, '_dzqcod_dimensions', json_encode($dims, JSON_UNESCAPED_UNICODE));
        }
        // Paid options
        if (isset($_POST['dzco_name']) && is_array($_POST['dzco_name'])) {
            $opts = [];
            foreach ($_POST['dzco_name'] as $i => $name) {
                $name = sanitize_text_field($name); if (!$name) continue;
                $opts[] = ['name' => $name, 'type' => sanitize_text_field($_POST['dzco_type'][$i] ?? 'checkbox'),
                    'price' => floatval($_POST['dzco_price'][$i] ?? 0),
                    'values' => sanitize_text_field($_POST['dzco_values'][$i] ?? '')];
            }
            update_post_meta($pid, '_dzqcod_paid_options', json_encode($opts, JSON_UNESCAPED_UNICODE));
        }
    }

    public function admin_scripts(): void {
        $screen = get_current_screen(); if (!$screen || $screen->id !== 'product') return; ?>
<script>jQuery(function($){
    var dimRow='<tr><td style="padding:3px"><input type="text" name="dzcd_name[]" style="width:100%;padding:4px" placeholder="الطول"></td><td style="padding:3px"><input type="text" name="dzcd_unit[]" value="سم" style="width:60px;padding:4px"></td><td style="padding:3px"><input type="number" name="dzcd_min[]" style="width:60px;padding:4px" step="0.1"></td><td style="padding:3px"><input type="number" name="dzcd_max[]" style="width:60px;padding:4px" step="0.1"></td><td style="padding:3px"><input type="number" name="dzcd_step[]" value="1" style="width:50px;padding:4px" step="0.1"></td><td style="text-align:center"><button type="button" class="button dzcd-rm" style="color:red;padding:2px 6px">✕</button></td></tr>';
    $('#dzcd-add').on('click',function(){$('#dzcd tbody').append(dimRow)});
    $(document).on('click','.dzcd-rm',function(){$(this).closest('tr').remove()});
    var optRow='<tr><td style="padding:3px"><input type="text" name="dzco_name[]" style="width:100%;padding:4px"></td><td style="padding:3px"><select name="dzco_type[]" style="padding:4px"><option value="checkbox">صح/خطأ</option><option value="select">قائمة</option><option value="number">رقم</option><option value="color_pick">لون</option></select></td><td style="padding:3px"><input type="number" name="dzco_price[]" style="width:90px;padding:4px" placeholder="0"></td><td style="padding:3px"><input type="text" name="dzco_values[]" style="width:100%;padding:4px"></td><td style="text-align:center"><button type="button" class="button dzco-rm" style="color:red;padding:2px 6px">✕</button></td></tr>';
    $('#dzco-add').on('click',function(){$('#dzco tbody').append(optRow)});
    $(document).on('click','.dzco-rm',function(){$(this).closest('tr').remove()});
});</script>
        <?php
    }

    // ═══════════════════════════════════════════════
    //  FILE UPLOAD HANDLER
    // ═══════════════════════════════════════════════
    public function handle_upload(): void {
        check_ajax_referer('dzqcod_order', '_n');
        if (empty($_FILES['dzqcod_file'])) wp_send_json_error(['message' => 'لا يوجد ملف']);
        $file = $_FILES['dzqcod_file'];
        $pid = absint($_POST['product_id'] ?? 0);

        // Validate type
        $allowed = array_map('trim', explode(',', get_post_meta($pid, '_dzqcod_upload_types', true) ?: 'jpg,png,pdf'));
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed)) wp_send_json_error(['message' => 'نوع الملف غير مسموح: ' . $ext]);

        // Validate size
        $max_mb = (float)(get_post_meta($pid, '_dzqcod_upload_max_mb', true) ?: 5);
        if ($file['size'] > $max_mb * 1024 * 1024) wp_send_json_error(['message' => 'حجم الملف يتجاوز ' . $max_mb . ' MB']);

        // Upload to WP uploads/dzqcod-files/
        $upload_dir = wp_upload_dir();
        $target_dir = $upload_dir['basedir'] . '/dzqcod-files/' . gmdate('Y/m/');
        if (!file_exists($target_dir)) wp_mkdir_p($target_dir);

        $safe_name = wp_unique_filename($target_dir, sanitize_file_name($file['name']));
        $target = $target_dir . $safe_name;

        if (!move_uploaded_file($file['tmp_name'], $target)) wp_send_json_error(['message' => 'فشل رفع الملف']);

        $url = $upload_dir['baseurl'] . '/dzqcod-files/' . gmdate('Y/m/') . $safe_name;
        wp_send_json_success(['url' => $url, 'name' => $safe_name, 'size' => round($file['size'] / 1024) . ' KB']);
    }

    // ═══════════════════════════════════════════════
    //  DYNAMIC PRICE CALCULATOR
    // ═══════════════════════════════════════════════
    public function calc_price(): void {
        $pid = absint($_POST['product_id'] ?? 0);
        if (!$pid) wp_send_json_error();

        $mode = get_post_meta($pid, '_dzqcod_pricing_mode', true) ?: 'fixed';
        $base = (float)(get_post_meta($pid, '_dzqcod_custom_base', true) ?: 0);
        $ppu = (float)(get_post_meta($pid, '_dzqcod_price_per_unit', true) ?: 0);
        $product = wc_get_product($pid);
        $product_price = $product ? (float)$product->get_price() : 0;

        // Dimensions calculation
        $dims_input = $_POST['dimensions'] ?? [];
        $dim_values = [];
        foreach ($dims_input as $k => $v) $dim_values[$k] = max(0, floatval($v));

        $dim_price = 0;
        switch ($mode) {
            case 'area':
                $vals = array_values($dim_values);
                $area = ($vals[0] ?? 0) * ($vals[1] ?? 0);
                // Convert to m² if in cm
                $unit = get_post_meta($pid, '_dzqcod_unit_label', true) ?: 'م²';
                if (stripos($unit, 'سم') !== false || stripos($unit, 'cm') !== false) $area /= 10000;
                $dim_price = $area * $ppu;
                break;
            case 'linear':
                $dim_price = (array_values($dim_values)[0] ?? 0) * $ppu;
                break;
            case 'volume':
                $vals = array_values($dim_values);
                $vol = ($vals[0] ?? 0) * ($vals[1] ?? 0) * ($vals[2] ?? 0);
                $dim_price = $vol * $ppu;
                break;
            case 'weight':
                $dim_price = (array_values($dim_values)[0] ?? 0) * $ppu;
                break;
            default:
                $dim_price = $product_price; // fixed price from product
        }

        // Paid options
        $options_json = get_post_meta($pid, '_dzqcod_paid_options', true) ?: '';
        $options_config = $options_json ? json_decode($options_json, true) : [];
        $selected = $_POST['options'] ?? [];
        $options_total = 0;
        $options_detail = [];

        foreach ($options_config as $i => $opt) {
            $key = 'opt_' . $i;
            if (!isset($selected[$key]) || $selected[$key] === '' || $selected[$key] === '0') continue;

            if ($opt['type'] === 'checkbox' && $selected[$key] === 'yes') {
                $options_total += (float)$opt['price'];
                $options_detail[] = ['name' => $opt['name'], 'price' => (float)$opt['price']];
            } elseif ($opt['type'] === 'select' && !empty($opt['values'])) {
                // Parse "name:price,name:price"
                $pairs = array_map('trim', explode(',', $opt['values']));
                foreach ($pairs as $pair) {
                    $parts = explode(':', $pair);
                    if (count($parts) === 2 && trim($parts[0]) === $selected[$key]) {
                        $p = (float)$parts[1];
                        $options_total += $p;
                        $options_detail[] = ['name' => $opt['name'] . ': ' . trim($parts[0]), 'price' => $p];
                    }
                }
            } elseif ($opt['type'] === 'number') {
                $qty_opt = max(0, (int)$selected[$key]);
                $p = $qty_opt * (float)$opt['price'];
                $options_total += $p;
                if ($qty_opt > 0) $options_detail[] = ['name' => $opt['name'] . ' ×' . $qty_opt, 'price' => $p];
            }
        }

        $qty = max(1, absint($_POST['quantity'] ?? 1));
        $subtotal = ($mode === 'fixed' || $mode === 'custom_calc') ? ($base + $dim_price) : ($base + $dim_price);
        $total_per_unit = $subtotal + $options_total;
        $total = $total_per_unit * $qty;

        wp_send_json_success([
            'base_price' => round($base), 'dimension_price' => round($dim_price),
            'options_total' => round($options_total), 'options_detail' => $options_detail,
            'unit_price' => round($total_per_unit), 'quantity' => $qty, 'total' => round($total),
        ]);
    }

    // ═══════════════════════════════════════════════
    //  GET CONFIG FOR FORM RENDERING
    // ═══════════════════════════════════════════════
    public static function get_config(int $pid): ?array {
        if (get_post_meta($pid, '_dzqcod_custom_enabled', true) !== 'yes') return null;
        return [
            'mode' => get_post_meta($pid, '_dzqcod_pricing_mode', true) ?: 'fixed',
            'ppu' => (float)(get_post_meta($pid, '_dzqcod_price_per_unit', true) ?: 0),
            'unit' => get_post_meta($pid, '_dzqcod_unit_label', true) ?: 'م²',
            'base' => (float)(get_post_meta($pid, '_dzqcod_custom_base', true) ?: 0),
            'min_area' => (float)(get_post_meta($pid, '_dzqcod_min_area', true) ?: 0),
            'max_area' => (float)(get_post_meta($pid, '_dzqcod_max_area', true) ?: 0),
            'dimensions' => json_decode(get_post_meta($pid, '_dzqcod_dimensions', true) ?: '', true) ?: [],
            'options' => json_decode(get_post_meta($pid, '_dzqcod_paid_options', true) ?: '', true) ?: [],
            'upload' => get_post_meta($pid, '_dzqcod_upload_enabled', true) === 'yes',
            'upload_types' => get_post_meta($pid, '_dzqcod_upload_types', true) ?: 'jpg,png,pdf',
            'upload_max_mb' => (float)(get_post_meta($pid, '_dzqcod_upload_max_mb', true) ?: 5),
            'upload_max_files' => (int)(get_post_meta($pid, '_dzqcod_upload_max_files', true) ?: 3),
            'custom_note' => get_post_meta($pid, '_dzqcod_custom_note', true) === 'yes',
            'note_label' => get_post_meta($pid, '_dzqcod_custom_note_label', true) ?: 'وصف الطلب المخصص',
        ];
    }
}
