<?php
namespace DZQCOD;
defined('ABSPATH') || exit;

class ProductEnhanced {
    public function __construct() {
        add_action('woocommerce_product_data_panels', [$this, 'panel'], 20);
        add_action('woocommerce_process_product_meta', [$this, 'save'], 20);
        add_filter('woocommerce_product_data_tabs', [$this, 'tabs'], 20);
        add_action('admin_footer', [$this, 'scripts']);
        // Stock alerts
        add_action('woocommerce_low_stock', [$this, 'low_stock_alert']);
        add_action('woocommerce_no_stock', [$this, 'no_stock_alert']);
    }

    public function tabs(array $tabs): array {
        $tabs['dzqcod'] = [
            'label' => 'DZQCOD',
            'target' => 'dzqcod_data',
            'class' => ['show_if_simple', 'show_if_variable'],
            'priority' => 80,
        ];
        return $tabs;
    }

    public function panel(): void {
        global $post;
        $pid = $post->ID;
        $off = get_post_meta($pid, '_dzqcod_disabled', true);
        $qj = get_post_meta($pid, '_dzqcod_qty_pricing', true) ?: '';
        $tiers = $qj ? json_decode($qj, true) : [];
        $colors = get_post_meta($pid, '_dzqcod_colors', true) ?: '';
        $sizes = get_post_meta($pid, '_dzqcod_sizes', true) ?: '';
        $wa = get_post_meta($pid, '_dzqcod_whatsapp', true) ?: '';
        $is_digital = get_post_meta($pid, '_dzqcod_digital', true);
        $dl_url = get_post_meta($pid, '_dzqcod_download_url', true) ?: '';
        $dl_limit = get_post_meta($pid, '_dzqcod_download_limit', true) ?: '';
        $custom_fields_json = get_post_meta($pid, '_dzqcod_custom_fields', true) ?: '';
        $custom_fields = $custom_fields_json ? json_decode($custom_fields_json, true) : [];
        $stock_alert = get_post_meta($pid, '_dzqcod_stock_alert', true) ?: '5';
        $max_per_order = get_post_meta($pid, '_dzqcod_max_per_order', true) ?: '';
        $min_per_order = get_post_meta($pid, '_dzqcod_min_per_order', true) ?: '';
        $countdown = get_post_meta($pid, '_dzqcod_countdown', true) ?: '';
        $badge = get_post_meta($pid, '_dzqcod_badge', true) ?: '';
        ?>
<div id="dzqcod_data" class="panel woocommerce_options_panel" dir="rtl" style="padding:15px">
    <div style="border-bottom:3px solid #667eea;padding-bottom:10px;margin-bottom:16px;display:flex;justify-content:space-between;align-items:center">
        <h3 style="margin:0;font-size:16px">🛒 DZQCOD — إعدادات متقدمة</h3>
        <span style="background:#667eea;color:#fff;padding:2px 10px;border-radius:10px;font-size:11px">v<?php echo esc_html(\DZQCOD_VER); ?></span>
    </div>

    <!-- Toggle & Shortcode -->
    <div style="background:#f0f4ff;border:1px solid #d0d8ff;border-radius:8px;padding:12px;margin-bottom:16px">
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:8px">
            <input type="checkbox" name="_dzqcod_disabled" value="yes" <?php checked($off, 'yes'); ?>>
            <strong>تعطيل DZQCOD لهذا المنتج (استخدام فورم ووكومرس العادي)</strong>
        </label>
        <div><strong>شورتكود:</strong> <code onclick="navigator.clipboard.writeText(this.textContent)" style="cursor:pointer;background:#fff;padding:3px 8px;border-radius:4px">[dzqcod_order product_id="<?php echo esc_html($pid); ?>"]</code> <small>← انقر للنسخ</small></div>
    </div>

    <!-- === VARIANTS: Colors & Sizes === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">🎨 الألوان والمقاسات</h4>
        <p style="font-size:12px;color:#888;margin:0 0 8px">يتم عرضها كأزرار اختيار في الفورم. افصل بفاصلة.</p>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
            <div style="flex:1;min-width:200px">
                <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px">الألوان المتاحة</label>
                <input type="text" name="_dzqcod_colors" value="<?php echo esc_attr($colors); ?>"
                    placeholder="أسود, أبيض, أزرق, أحمر" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">
            </div>
            <div style="flex:1;min-width:200px">
                <label style="font-size:13px;font-weight:600;display:block;margin-bottom:4px">المقاسات المتاحة</label>
                <input type="text" name="_dzqcod_sizes" value="<?php echo esc_attr($sizes); ?>"
                    placeholder="S, M, L, XL, XXL" style="width:100%;padding:8px;border:1px solid #ddd;border-radius:6px">
            </div>
        </div>
    </div>

    <!-- === QTY PRICING === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">🏷️ التسعير حسب الكمية</h4>
        <table style="width:100%;border-collapse:collapse" id="dzt">
            <thead><tr style="background:#f8f9fa"><th style="padding:6px;text-align:right">من (كمية)</th><th>السعر/قطعة</th><th>عنوان</th><th style="width:40px">×</th></tr></thead>
            <tbody>
            <?php foreach ($tiers as $t): ?>
            <tr><td style="padding:4px"><input type="number" name="dzt_min[]" value="<?php echo (int)$t['min_qty']; ?>" min="1" style="width:70px;padding:4px"></td>
            <td style="padding:4px"><input type="number" name="dzt_price[]" value="<?php echo esc_html((float)$t['price']); ?>" min="0" step="1" style="width:100px;padding:4px"></td>
            <td style="padding:4px"><input type="text" name="dzt_label[]" value="<?php echo esc_attr($t['label'] ?? ''); ?>" style="width:100%;padding:4px"></td>
            <td style="text-align:center"><button type="button" class="button dzt-rm" style="color:red">✕</button></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <button type="button" class="button" id="dzt-add" style="margin-top:6px">➕ شريحة سعرية</button>
    </div>

    <!-- === STOCK MANAGEMENT === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">📦 متابعة المخزون</h4>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
            <div><label style="font-size:12px;font-weight:600">تنبيه عند وصول المخزون إلى</label>
            <input type="number" name="_dzqcod_stock_alert" value="<?php echo esc_attr($stock_alert); ?>" min="1" style="width:80px;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
            <div><label style="font-size:12px;font-weight:600">أقل كمية للطلب</label>
            <input type="number" name="_dzqcod_min_per_order" value="<?php echo esc_attr($min_per_order); ?>" min="1" style="width:80px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="1"></div>
            <div><label style="font-size:12px;font-weight:600">أقصى كمية للطلب</label>
            <input type="number" name="_dzqcod_max_per_order" value="<?php echo esc_attr($max_per_order); ?>" min="1" style="width:80px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="99"></div>
        </div>
    </div>

    <!-- === DIGITAL PRODUCT === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">💾 منتج رقمي</h4>
        <label style="display:flex;align-items:center;gap:8px;cursor:pointer;margin-bottom:8px">
            <input type="checkbox" name="_dzqcod_digital" value="yes" <?php checked($is_digital, 'yes'); ?>>
            <strong>هذا منتج رقمي (بدون شحن، تحميل فوري بعد الدفع)</strong>
        </label>
        <div style="display:flex;gap:10px;flex-wrap:wrap">
            <div style="flex:1"><label style="font-size:12px;font-weight:600">رابط التحميل</label>
            <input type="url" name="_dzqcod_download_url" value="<?php echo esc_attr($dl_url); ?>" placeholder="https://..." style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>
            <div><label style="font-size:12px;font-weight:600">حد التحميلات</label>
            <input type="number" name="_dzqcod_download_limit" value="<?php echo esc_attr($dl_limit); ?>" min="1" style="width:80px;padding:6px;border:1px solid #ddd;border-radius:6px" placeholder="5"></div>
        </div>
    </div>

    <!-- === MARKETING === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">📣 التسويق</h4>
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:8px">
            <div style="flex:1"><label style="font-size:12px;font-weight:600">واتساب خاص بالمنتج</label>
            <input type="text" name="_dzqcod_whatsapp" value="<?php echo esc_attr($wa); ?>" placeholder="213555123456" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px;direction:ltr"></div>
            <div style="flex:1"><label style="font-size:12px;font-weight:600">شارة المنتج (Badge)</label>
            <input type="text" name="_dzqcod_badge" value="<?php echo esc_attr($badge); ?>" placeholder="🔥 الأكثر مبيعاً" style="width:100%;padding:6px;border:1px solid #ddd;border-radius:6px"></div>
        </div>
        <div><label style="font-size:12px;font-weight:600">مؤقت العرض (Countdown)</label>
        <input type="datetime-local" name="_dzqcod_countdown" value="<?php echo esc_attr($countdown); ?>" style="padding:6px;border:1px solid #ddd;border-radius:6px">
        <small style="color:#888">اتركه فارغاً لتعطيل المؤقت</small></div>
    </div>

    <!-- === CUSTOM FIELDS === -->
    <div style="background:#fff;border:1px solid #eee;border-radius:8px;padding:14px;margin-bottom:14px">
        <h4 style="margin:0 0 10px;font-size:14px">📝 حقول مخصصة في الفورم</h4>
        <p style="font-size:12px;color:#888;margin:0 0 8px">أضف حقول إضافية تظهر في نموذج الطلب لهذا المنتج فقط</p>
        <table style="width:100%" id="dzcf">
            <thead><tr style="background:#f8f9fa"><th style="padding:6px;text-align:right">اسم الحقل</th><th>النوع</th><th>مطلوب</th><th style="width:40px">×</th></tr></thead>
            <tbody>
            <?php foreach ($custom_fields as $cf): ?>
            <tr><td style="padding:4px"><input type="text" name="dzcf_name[]" value="<?php echo esc_attr($cf['name']); ?>" style="width:100%;padding:4px"></td>
            <td style="padding:4px"><select name="dzcf_type[]" style="padding:4px"><option value="text" <?php selected($cf['type']??'', 'text'); ?>>نص</option><option value="select" <?php selected($cf['type']??'', 'select'); ?>>قائمة</option><option value="textarea" <?php selected($cf['type']??'', 'textarea'); ?>>نص طويل</option></select></td>
            <td style="padding:4px;text-align:center"><input type="checkbox" name="dzcf_req[]" value="<?php echo (int)count($custom_fields); ?>" <?php checked($cf['required']??false); ?>></td>
            <td style="text-align:center"><button type="button" class="button dzcf-rm" style="color:red">✕</button></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <button type="button" class="button" id="dzcf-add" style="margin-top:6px">➕ حقل مخصص</button>
    </div>
</div>
<style>#woocommerce-product-data ul.wc-tabs li.dzqcod_options a::before{content:'\f174';font-family:dashicons;color:#667eea}
#dzqcod_data,#dzqcod_custom_data{direction:rtl!important;text-align:right!important}
#dzqcod_data *,#dzqcod_custom_data *{box-sizing:border-box}
#dzqcod_data input[type=text],#dzqcod_data input[type=number],#dzqcod_data input[type=url],#dzqcod_data select,
#dzqcod_custom_data input[type=text],#dzqcod_custom_data input[type=number],#dzqcod_custom_data select{max-width:100%}
</style>
        <?php
    }

    public function save(int $pid): void {
        update_post_meta($pid, '_dzqcod_disabled', isset($_POST['_dzqcod_disabled']) ? 'yes' : 'no');
        update_post_meta($pid, '_dzqcod_colors', sanitize_text_field($_POST['_dzqcod_colors'] ?? ''));
        update_post_meta($pid, '_dzqcod_sizes', sanitize_text_field($_POST['_dzqcod_sizes'] ?? ''));
        update_post_meta($pid, '_dzqcod_whatsapp', sanitize_text_field($_POST['_dzqcod_whatsapp'] ?? ''));
        update_post_meta($pid, '_dzqcod_digital', isset($_POST['_dzqcod_digital']) ? 'yes' : 'no');
        update_post_meta($pid, '_dzqcod_download_url', esc_url_raw($_POST['_dzqcod_download_url'] ?? ''));
        update_post_meta($pid, '_dzqcod_download_limit', absint($_POST['_dzqcod_download_limit'] ?? 5));
        update_post_meta($pid, '_dzqcod_stock_alert', absint($_POST['_dzqcod_stock_alert'] ?? 5));
        update_post_meta($pid, '_dzqcod_min_per_order', absint($_POST['_dzqcod_min_per_order'] ?? 1));
        update_post_meta($pid, '_dzqcod_max_per_order', absint($_POST['_dzqcod_max_per_order'] ?? 99));
        update_post_meta($pid, '_dzqcod_badge', sanitize_text_field($_POST['_dzqcod_badge'] ?? ''));
        update_post_meta($pid, '_dzqcod_countdown', sanitize_text_field($_POST['_dzqcod_countdown'] ?? ''));

        // Qty pricing
        if (isset($_POST['dzt_min']) && is_array($_POST['dzt_min'])) {
            $tiers = [];
            foreach ($_POST['dzt_min'] as $i => $m) {
                $m = absint($m); $p = floatval($_POST['dzt_price'][$i] ?? 0);
                if ($m < 1 || $p <= 0) continue;
                $tiers[] = ['min_qty' => $m, 'price' => $p, 'label' => sanitize_text_field($_POST['dzt_label'][$i] ?? '')];
            }
            usort($tiers, fn($a, $b) => $a['min_qty'] - $b['min_qty']);
            update_post_meta($pid, '_dzqcod_qty_pricing', !empty($tiers) ? wp_json_encode($tiers) : '');
        }

        // Custom fields
        if (isset($_POST['dzcf_name']) && is_array($_POST['dzcf_name'])) {
            $fields = [];
            foreach ($_POST['dzcf_name'] as $i => $name) {
                $name = sanitize_text_field($name);
                if (!$name) continue;
                $fields[] = ['name' => $name, 'type' => sanitize_text_field($_POST['dzcf_type'][$i] ?? 'text'), 'required' => in_array($i, $_POST['dzcf_req'] ?? [])];
            }
            update_post_meta($pid, '_dzqcod_custom_fields', wp_json_encode($fields));
        }
    }

    public function scripts(): void {
        $screen = get_current_screen();
        if (!$screen || $screen->id !== 'product') return;
        ?>
<script>jQuery(function($){
    var tierRow='<tr><td style="padding:4px"><input type="number" name="dzt_min[]" min="1" style="width:70px;padding:4px"></td><td style="padding:4px"><input type="number" name="dzt_price[]" min="0" style="width:100px;padding:4px"></td><td style="padding:4px"><input type="text" name="dzt_label[]" style="width:100%;padding:4px"></td><td style="text-align:center"><button type="button" class="button dzt-rm" style="color:red">✕</button></td></tr>';
    $('#dzt-add').on('click',function(){$('#dzt tbody').append(tierRow)});
    $(document).on('click','.dzt-rm',function(){$(this).closest('tr').remove()});
    var cfRow='<tr><td style="padding:4px"><input type="text" name="dzcf_name[]" style="width:100%;padding:4px" placeholder="اسم الحقل"></td><td style="padding:4px"><select name="dzcf_type[]" style="padding:4px"><option value="text">نص</option><option value="select">قائمة</option><option value="textarea">نص طويل</option></select></td><td style="text-align:center;padding:4px"><input type="checkbox" name="dzcf_req[]"></td><td style="text-align:center"><button type="button" class="button dzcf-rm" style="color:red">✕</button></td></tr>';
    $('#dzcf-add').on('click',function(){$('#dzcf tbody').append(cfRow)});
    $(document).on('click','.dzcf-rm',function(){$(this).closest('tr').remove()});
});</script>
        <?php
    }

    public function low_stock_alert($product): void {
        $threshold = (int) get_post_meta($product->get_id(), '_dzqcod_stock_alert', true) ?: 5;
        if ($product->get_stock_quantity() <= $threshold) {
            do_action('dzqcod_stock_alert', $product->get_id(), $product->get_stock_quantity(), 'low');
        }
    }

    public function no_stock_alert($product): void {
        do_action('dzqcod_stock_alert', $product->get_id(), 0, 'out');
    }
}
