<?php
/**
 * ═══════════════════════════════════════════════════════════════
 * DZQCOD v3 — Addon Development Guide / دليل تطوير الإضافات
 * ═══════════════════════════════════════════════════════════════
 *
 * === FILE STRUCTURE ===
 * addons/
 * ├── my-addon.php              ← Single-file addon
 * └── my-addon/                 ← Multi-file addon (ZIP uploaded)
 *     ├── my-addon.php          ← Main file (required)
 *     ├── includes/
 *     └── templates/
 *
 * === ADDON HEADER (Required in main .php file) ===
 *
 * Addon Name: My Custom Addon
 * Description: وصف الإضافة بالعربية أو الإنجليزية
 * Version: 1.0.0
 * Author: Your Name
 * Type: free|pro|enterprise
 * Category: shipping|payment|marketing|sales|automation|analytics|security|channels|products|integrations|tools
 *
 *
 * === AVAILABLE HOOKS & FILTERS ===
 *
 * Actions:
 *   dzqcod_order_created         ($order_id, $order)      — fires after order created
 *   dzqcod_order_confirmed       ($order_id)              — fires after order confirmed
 *   dzqcod_order_shipped         ($order_id, $tracking)   — fires after shipment created
 *   woocommerce_order_status_changed ($id, $from, $to, $order)
 *
 * Filters:
 *   dzqcod_shipping_fee          ($fee, $wilaya_code, $mode)  — modify shipping fees
 *   dzqcod_order_data            ($data, $product_id)         — modify order data before save
 *   dzqcod_form_fields           ($fields, $product_id)       — add/remove form fields
 *   dzqcod_trust_badges          ($badges)                    — modify trust badge text
 *
 * === HELPER FUNCTIONS ===
 *
 *   \DZQCOD\Core::opt($key, $default)     — get plugin option
 *   \DZQCOD\Core::db()                    — get DB table prefix: {wp_prefix}dzqcod_
 *   \DZQCOD\Core::i()                     — get Core instance
 *   \DZQCOD\Core::is_pro()                — check PRO license
 *   \DZQCOD\Core::is_ent()                — check Enterprise license
 *   \DZQCOD\Modules::is_on($slug)         — check if addon is active
 *   \DZQCOD\Modules::installed_addons()   — array of slug => bool
 *
 * === REGISTERING ADMIN PAGES ===
 *
 *   add_action('admin_menu', function(){
 *       add_submenu_page(
 *           'dzqcod',                    // parent slug
 *           'My Addon Title',            // page title
 *           '🔌 My Addon',              // menu title
 *           'manage_options',             // capability
 *           'dzqcod-my-addon',           // menu slug
 *           function(){ include __DIR__.'/templates/my-page.php'; }
 *       );
 *   });
 *
 * === AJAX HANDLERS ===
 *
 *   add_action('wp_ajax_dzqcod_my_action', function(){
 *       check_ajax_referer('dzqcod_admin','nonce');
 *       // your logic...
 *       wp_send_json_success(['message'=>'Done!']);
 *   });
 *
 *   // Call from JS:
 *   $.post(dza.ajax, {action:'dzqcod_my_action', nonce:dza.nonce, data:'...'}, fn);
 *
 *
 * === EXAMPLE: SIMPLE ADDON (Telegram Notifications) ===
 */

// Addon Name: Telegram Notifications
// Description: إرسال إشعار تلجرام عند كل طلب جديد
// Version: 1.0.0
// Category: channels

defined('ABSPATH') || exit;

// Only run if this addon is active
if (!\DZQCOD\Modules::is_on('telegram-bot')) return;

// Hook into new orders
add_action('dzqcod_order_created', function(int $order_id, $order) {
    $bot_token = \DZQCOD\Core::opt('telegram_bot_token', '');
    $chat_id   = \DZQCOD\Core::opt('telegram_chat_id', '');
    if (!$bot_token || !$chat_id) return;

    // Build message
    $name  = $order->get_billing_first_name();
    $phone = $order->get_billing_phone();
    $total = $order->get_total();
    $items = [];
    foreach ($order->get_items() as $item) {
        $items[] = $item->get_name() . ' ×' . $item->get_quantity();
    }
    $msg = "🛒 *طلب جديد #" . $order_id . "*\n"
         . "👤 " . $name . "\n"
         . "📱 " . $phone . "\n"
         . "📦 " . implode(', ', $items) . "\n"
         . "💰 " . number_format($total, 0) . " دج";

    // Send via Telegram Bot API
    $tg_url = 'https://api.telegram.org/bot' . $bot_token . '/sendMessage';
    wp_remote_post(esc_url_raw($tg_url), [
        'body' => [
            'chat_id'    => $chat_id,
            'text'       => $msg,
            'parse_mode' => 'Markdown',
        ],
        'timeout' => 10,
    ]);
}, 20, 2);

// Add settings page
add_action('wp_ajax_dzqcod_telegram_save', function() {
    check_ajax_referer('dzqcod_admin', 'nonce');
    update_option('dzqcod_telegram_bot_token', sanitize_text_field($_POST['bot_token'] ?? ''));
    update_option('dzqcod_telegram_chat_id',   sanitize_text_field($_POST['chat_id']   ?? ''));
    wp_send_json_success(['message' => 'تم حفظ إعدادات تلجرام ✅']);
});

/**
 * === ADDON STATUS AUDIT (v3.0.8) ===
 *
 * ✅ FULLY FUNCTIONAL (has real code in Modules.php):
 * ──────────────────────────────────────────────────
 * whatsapp-auto    — wa_on_order, wa_on_status, wa_send_manual, wa_save_templates
 * chargily         — chargily_save, chargily_webhook (CIB/EDAHABIA payments)
 * sms-auto         — sms_on_order, sms_on_status, sms_save_config, sms_test
 * baridimob        — baridimob_save, baridimob_confirm (BaridiMob payments)
 * digital          — digital_delivery (auto-send download link)
 * canva            — canva_generate (AI creative designs)
 * custom-products  — CustomProducts class (dimensions, options, file upload, calculator)
 * export           — dzqcod_export_orders (CSV/Excel export built into Core)
 * profit-calc      — Built into profit.php template (profit calculator)
 *
 * 📝 UI ONLY (admin page exists, feature is placeholder/settings-only):
 * ─────────────────────────────────────────────────────────────────────
 * yalidine         — Settings page, API key input, no auto-shipment yet
 * zr-express       — Settings page, API key input, no auto-shipment yet
 * ecotrack         — Settings page, API key input, no auto-shipment yet
 * noest            — Settings page + fee sync (syncNoestFees), partially functional
 * meta-capi        — Pixel/CAPI config in campaigns page, tracking code injection
 * tiktok-events    — Pixel config in campaigns page
 * google-ads       — Pixel config in campaigns page
 * ab-testing       — UI template only, no backend test engine
 * popup-form       — Settings exist but popup rendering basic
 *
 * 🔲 EMPTY SHELL (registered in marketplace, no code):
 * ────────────────────────────────────────────────────
 * ai-copilot       — No code yet, needs OpenAI/Claude API integration
 * retargeting      — No code yet, needs pixel + email/SMS retarget
 * multi-store      — No code yet, needs multi-site/tenant architecture
 * workflows        — No code yet, needs visual workflow builder
 * upsell           — UI template, no real upsell engine
 * order-bump       — UI template, no checkout bump logic
 * abandoned-cart   — No abandonment tracking/recovery
 * loyalty          — No points system
 * referral         — No referral tracking/commission
 * smart-confirm    — UI template, no auto-confirm logic
 * auto-ship        — No auto-create-shipment logic
 * followup         — No sequence/drip system
 * analytics        — Basic stats only, no advanced analytics
 * cohort           — No cohort analysis
 * heatmap          — No form interaction tracking
 * ip-geo           — No IP geolocation check
 * phone-otp        — OTP built into Core, not standalone addon
 * telegram-bot     — Example in this file, can be uploaded
 * instagram-shop   — No code, needs IG API
 * google-sheets    — No code, needs Sheets API
 * zapier-make      — No webhook endpoint
 * tracking-page    — Basic page, no carrier tracking
 * reviews          — No post-delivery review system
 * email-marketing  — No Mailchimp/Sendinblue integration
 * crm              — No HubSpot/Zoho integration
 * multi-country    — NOW BUILT INTO CORE (v3.0.8) via country settings
 *
 * === HOW TO EXTEND AN EMPTY ADDON ===
 *
 * 1. Create file: addons/{slug}.php
 * 2. Add header: Addon Name: ..., Description: ...
 * 3. Hook into DZQCOD events
 * 4. ZIP it and upload from Admin → متجر الإضافات → رفع إضافة
 *
 * The addon will auto-load when installed/activated.
 */
