<?php

/**
 * Title: SunnahTi Ultimate Enterprise Engine (All-in-One Dashboard)
 * Version: 3.0 Enterprise Super-Fast
 * New: Pagination + Media Manager + Google Sheet + SIP Dialer + Fraud Detection Tab
 *      + Loyal Customer + Incomplete Order Tracking + AJAX Search + Branding Tab
 *      + Language Toggle (Bn/EN) + Size/Weight Variants + Page Duplicate + Bug Fixes
 * Author: Specialized High-Performance Core
 */

date_default_timezone_set('Asia/Dhaka');
ini_set('session.cookie_httponly', 1);
session_start();

define('DB_HOST', 'localhost');
define('DB_NAME', 'sunnahti_bzr');
define('DB_USER', 'sunnahti_bzr');
define('DB_PASS', 'x[wYQKY-+ax[J{~S');

// mbstring এক্সটেনশন না থাকলে বেসিক ফলব্যাক (সাইট যেন কখনো ক্র্যাশ না করে)
if (!function_exists('mb_strpos')) { function mb_strpos($h, $n, $o = 0) { return strpos($h, $n, $o); } }
if (!function_exists('mb_strtolower')) { function mb_strtolower($str) { return strtolower($str); } }
if (!function_exists('mb_substr')) { function mb_substr($str, $start, $len = null) { return $len === null ? substr($str, $start) : substr($str, $start, $len); } }

define('MEDIA_DIR', __DIR__ . '/uploads/media');
define('REC_DIR', __DIR__ . '/uploads/recordings'); // কল রেকর্ডিং সেভ ফোল্ডার (৩০ দিন পর অটো ডিলিট)
define('ADV_DIR', __DIR__ . '/uploads/advance'); // এডভান্স পেমেন্ট স্ক্রিনশট
define('MEDIA_URL_PATH', 'uploads/media');

// Establish Database Connection
try {
    $db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4", DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci"
    ]);
} catch (PDOException $e) {
    die("<div style='padding: 20px; background: #fee2e2; color: #991b1b; font-family: sans-serif; border-radius: 8px;'>
            <strong>Database Connection Error:</strong> " . htmlspecialchars($e->getMessage()) . "
         </div>");
}

$db->exec("
    CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        role ENUM('admin', 'agent', 'office_team') DEFAULT 'agent',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS system_settings (
        setting_key VARCHAR(100) PRIMARY KEY,
        setting_value TEXT
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        slug VARCHAR(255) UNIQUE NOT NULL,
        price DECIMAL(10,2) NOT NULL,
        sale_price DECIMAL(10,2) DEFAULT NULL,
        description TEXT,
        image_url VARCHAR(500) DEFAULT NULL,
        colors TEXT,
        stock INT DEFAULT 0,
        checkout_fields TEXT DEFAULT NULL,
        variant_options TEXT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS pages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        slug VARCHAR(255) UNIQUE NOT NULL,
        content LONGTEXT,
        bottom_content LONGTEXT,
        seo_title VARCHAR(255) DEFAULT NULL,
        seo_desc TEXT,
        product_ids TEXT DEFAULT NULL,
        checkout_fields TEXT DEFAULT NULL,
        variant_config TEXT DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        customer_name VARCHAR(150) NOT NULL,
        phone VARCHAR(15) NOT NULL,
        alternative_phone VARCHAR(15) DEFAULT NULL,
        address TEXT NOT NULL,
        product_id INT,
        color_selected VARCHAR(50) DEFAULT NULL,
        size_selected VARCHAR(50) DEFAULT NULL,
        weight_selected VARCHAR(50) DEFAULT NULL,
        cod_amount DECIMAL(10,2) DEFAULT 0.00,
        status VARCHAR(50) DEFAULT 'pending',
        fraud_score INT DEFAULT NULL,
        fraud_summary TEXT,
        customer_ip VARCHAR(64) DEFAULT NULL,
        consignment_id VARCHAR(50) DEFAULT NULL,
        tracking_code VARCHAR(50) DEFAULT NULL,
        courier_status VARCHAR(50) DEFAULT NULL,
        booked_by VARCHAR(100) DEFAULT NULL,
        booked_at DATETIME DEFAULT NULL,
        note TEXT,
        updated_by VARCHAR(100) DEFAULT NULL,
        updated_at DATETIME DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS media_files (
        id INT AUTO_INCREMENT PRIMARY KEY,
        filename VARCHAR(255) NOT NULL,
        filepath VARCHAR(500) NOT NULL,
        url VARCHAR(500) NOT NULL,
        filesize INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS blocked_customers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        phone VARCHAR(20) DEFAULT NULL,
        ip VARCHAR(64) DEFAULT NULL,
        reason VARCHAR(255) DEFAULT NULL,
        blocked_by VARCHAR(100) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS incomplete_orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        token VARCHAR(64) DEFAULT NULL,
        customer_name VARCHAR(150) DEFAULT NULL,
        phone VARCHAR(20) DEFAULT NULL,
        address TEXT,
        product_id INT DEFAULT NULL,
        page_slug VARCHAR(255) DEFAULT NULL,
        customer_ip VARCHAR(64) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT NULL,
        UNIQUE KEY uniq_token (token)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS categories (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(150) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS messaging_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        platform ENUM('whatsapp', 'facebook') NOT NULL,
        name VARCHAR(150) NOT NULL,
        account_id VARCHAR(100) NOT NULL,
        access_token TEXT,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS short_links (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(60) NOT NULL UNIQUE,
        target_url TEXT NOT NULL,
        title VARCHAR(150) DEFAULT NULL,
        clicks INT DEFAULT 0,
        active TINYINT(1) DEFAULT 1,
        created_by VARCHAR(100) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS ad_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        platform ENUM('facebook', 'tiktok', 'google', 'other') DEFAULT 'facebook',
        label VARCHAR(120) NOT NULL,
        fb_account_id VARCHAR(100) DEFAULT NULL,
        fb_access_token TEXT DEFAULT NULL,
        auto_sync TINYINT(1) DEFAULT 0,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS ad_spends (
        id INT AUTO_INCREMENT PRIMARY KEY,
        account_id INT NOT NULL,
        spend_date DATE NOT NULL,
        amount_usd DECIMAL(10,2) DEFAULT 0,
        amount_bdt DECIMAL(12,2) DEFAULT 0,
        note VARCHAR(255) DEFAULT NULL,
        source ENUM('manual', 'api') DEFAULT 'manual',
        created_by VARCHAR(100) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uniq_acct_date (account_id, spend_date),
        INDEX idx_date (spend_date)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS courier_zone_entries (
        id INT AUTO_INCREMENT PRIMARY KEY,
        courier_id VARCHAR(100) NOT NULL,
        courier_link VARCHAR(500) DEFAULT NULL,
        product_id INT DEFAULT NULL,
        color VARCHAR(80) DEFAULT NULL,
        zone VARCHAR(50) NOT NULL,
        created_by VARCHAR(100) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS msg_accounts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        channel ENUM('whatsapp', 'facebook') NOT NULL,
        label VARCHAR(100) NOT NULL,
        ext_id VARCHAR(100) NOT NULL,
        access_token TEXT,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS inbox_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        account_id INT NOT NULL,
        contact_ext_id VARCHAR(150) NOT NULL,
        contact_name VARCHAR(150) DEFAULT NULL,
        direction ENUM('in', 'out') DEFAULT 'in',
        body TEXT,
        ext_msg_id VARCHAR(190) DEFAULT NULL UNIQUE,
        is_read TINYINT(1) DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_acct_contact (account_id, contact_ext_id),
        INDEX idx_created (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS promo_codes (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(50) UNIQUE NOT NULL,
        discount_type ENUM('percent', 'flat') DEFAULT 'flat',
        discount_value DECIMAL(10,2) DEFAULT 0,
        valid_until DATE DEFAULT NULL,
        max_uses INT DEFAULT 0,
        used_count INT DEFAULT 0,
        active TINYINT(1) DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    CREATE TABLE IF NOT EXISTS call_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        caller_id INT DEFAULT NULL,
        caller_name VARCHAR(100) DEFAULT NULL,
        caller_role VARCHAR(30) DEFAULT NULL,
        phone VARCHAR(30) DEFAULT NULL,
        customer_name VARCHAR(150) DEFAULT NULL,
        order_id INT DEFAULT NULL,
        direction VARCHAR(10) DEFAULT 'outgoing',
        started_at DATETIME DEFAULT NULL,
        duration_seconds INT DEFAULT 0,
        call_status VARCHAR(30) DEFAULT 'completed',
        recording_path VARCHAR(500) DEFAULT NULL,
        recording_url VARCHAR(500) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
");

try { $db->exec("ALTER TABLE pages ADD COLUMN product_ids TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN checkout_fields TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN bottom_content LONGTEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN variant_config TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN og_image VARCHAR(500) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN builder_json LONGTEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN og_image VARCHAR(500) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN courier_note TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN courier_synced_at DATETIME DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE call_logs ADD COLUMN direction VARCHAR(10) DEFAULT 'outgoing';"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN advance_trx VARCHAR(100) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN advance_proof_url VARCHAR(500) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN custom_field_value TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN custom_field_label VARCHAR(255) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN delivery_zone VARCHAR(30) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN delivery_charge DECIMAL(10,2) DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN promo_code VARCHAR(50) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN discount_amount DECIMAL(10,2) DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN cost_price DECIMAL(10,2) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN courier_name VARCHAR(30) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE courier_zone_entries ADD COLUMN color VARCHAR(80) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE courier_zone_entries MODIFY zone VARCHAR(50) NOT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN booking_lock VARCHAR(40) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN zone_change_flag TINYINT(1) DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN order_items TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE pages ADD COLUMN multi_product TINYINT(1) DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN cost_price DECIMAL(10,2) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN category_id INT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN checkout_fields TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN stock INT DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE products ADD COLUMN variant_options TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN fraud_score INT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN fraud_summary TEXT DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN is_deleted TINYINT DEFAULT 0;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN updated_by VARCHAR(100) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN updated_at DATETIME DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN customer_ip VARCHAR(64) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN size_selected VARCHAR(50) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE orders ADD COLUMN weight_selected VARCHAR(50) DEFAULT NULL;"); } catch (Exception $e) {}
try { $db->exec("ALTER TABLE users MODIFY COLUMN role ENUM('admin', 'agent', 'office_team') DEFAULT 'agent';"); } catch (Exception $e) {}

try {
    $db->exec("ALTER TABLE users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
    $db->exec("ALTER TABLE system_settings CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
    $db->exec("ALTER TABLE products CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
    $db->exec("ALTER TABLE pages CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
    $db->exec("ALTER TABLE orders CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
} catch (Exception $e) {}

// Insert default administrator if none exists
$stmt = $db->prepare("SELECT COUNT(*) FROM users");
$stmt->execute();
if ($stmt->fetchColumn() == 0) {
    $hashed_pass = password_hash('Admin@SunnahTi2026', PASSWORD_BCRYPT);
    $db->prepare("INSERT INTO users (username, password, role) VALUES ('admin', ?, 'admin')")->execute([$hashed_pass]);
}

// Global Agent and Admin Status Mapping Array
$status_map = [
    'pending'          => 'Call Pending',
    'confirmed'        => 'Confirmed',
    'no_answer'        => 'No Answer',
    'cancelled'        => 'Cancelled',
    'interested_later' => 'Interested Later',
    'did_not_order'    => 'Did Not Order',
    'phone_off'        => 'Phone Off',
    'booked'           => 'Booked (Courier)',
    'delivered'        => 'Delivered'
];

// English versions of statuses (for Bn/EN toggle)
$status_map_en = [
    'pending'          => 'Call Pending',
    'confirmed'        => 'Confirmed',
    'no_answer'        => 'No Answer',
    'cancelled'        => 'Cancelled',
    'interested_later' => 'Interested Later',
    'did_not_order'    => 'Did Not Order',
    'phone_off'        => 'Phone Off',
    'booked'           => 'Booked',
    'delivered'        => 'Delivered'
];

// Set up Default Settings if empty
$default_settings = [
    'fraud_api_key' => '',
    'fraud_api_url' => 'https://fraudshield.bd/api/customer/check',
    'steadfast_api_key' => '',
    'steadfast_secret_key' => '',
    'steadfast_base_url' => 'https://portal.packzy.com/api/v1',
    'facebook_pixel' => '',
    'facebook_access_token' => '',
    'facebook_test_code' => '',
    'tiktok_pixel' => '',
    'tiktok_access_token' => '',
    'tiktok_test_code' => '',
    'google_tag' => '',
    'checkout_fields' => '',
    'product_colors' => '',
    // ---- Google Sheet Integration ----
    'gsheet_enabled' => '0',
    'gsheet_webapp_url' => '',
    'gsheet_sheet_name' => 'Orders',
    // ---- SIP Dialer Configuration ----
    'dialer_mode' => 'tel',
    'sip_wss_url' => '',
    'sip_username' => '',
    'sip_password' => '',
    'sip_domain' => '',
    'sip_port' => '5060',
    'sip_transport' => 'UDP',
    'sip_proxy' => '',
    'sip_dtmf' => 'RFC2833',
    'sip_stun' => 'stun.l.google.com:19302',
    'sip_reg_interval' => '60',
    'sip_portal_url' => 'https://webvoice.net',
    'sip_balance_code' => '123',
    // ---- Branding ----
    'site_name' => 'SunnahTi',
    'contact_whatsapp' => '',
    'fraud_block_threshold' => '0',
    'custom_field_enabled' => '0',
    'home_page_slug' => '',
    'courier_charge_dhaka' => '60',
    'sms_api_key' => '',
    'sms_sender_id' => '',
    'sms_on_confirm' => '0',
    'sms_on_courier' => '0',
    'sms_tpl_confirm' => 'প্রিয় {name}, আপনার অর্ডার #{order_id} কনফার্ম হয়েছে। মোট: {cod} টাকা (ক্যাশ অন ডেলিভারি)। ধন্যবাদ!',
    'sms_tpl_courier' => 'প্রিয় {name}, আপনার অর্ডার #{order_id} কুরিয়ারে পাঠানো হয়েছে। ট্র্যাকিং: {tracking}। মোট: {cod} টাকা রেডি রাখুন।',
    'telegram_bot_token' => '',
    'telegram_chat_id' => '',
    'cron_secret' => '',
    'courier_charge_sub_dhaka' => '100',
    'courier_charge_outside' => '130',
    'sms_api_key' => '',
    'sms_sender_id' => '',
    'sms_on_confirm' => '0',
    'sms_on_courier' => '0',
    'sms_tpl_confirm' => 'প্রিয় {name}, আপনার অর্ডার #{order_id} কনফার্ম হয়েছে। মোট: {cod} টাকা (ক্যাশ অন ডেলিভারি)। ধন্যবাদ!',
    'sms_tpl_courier' => 'প্রিয় {name}, আপনার অর্ডার #{order_id} কুরিয়ারে পাঠানো হয়েছে। ট্র্যাকিং: {tracking}। ডেলিভারিতে {cod} টাকা রাখুন।',
    'telegram_bot_token' => '',
    'telegram_chat_id' => '',
    'report_cron_key' => '',
    'meta_verify_token' => '',
    'custom_field_label' => '',
    'advance_amount' => '150',
    'advance_bkash' => '',
    'advance_nagad' => '',
    'support_whatsapp' => '',
    'block_repeat_hours' => '24',
    'usd_to_bdt' => '122',
    'invoice_prefix' => 'ST-',
    'contact_phone' => '',
    'og_default_image' => '',
    'site_title' => 'SunnahTi Premium Store',
    'home_url' => '',
    'favicon_url' => '',
    'logo_url' => '',
    // ---- Variant option lists ----
    'size_teen_options' => json_encode(['XXS','XS','S','M','L','XL','XXL','3XL','4XL','5XL','6XL','7XL','8XL']),
    'size_kids_options' => json_encode(['0-6 Months','6-12 Months','12-18 Months','18-24 Months','24-36 Months','0-1 Years','1-2 Years','2-4 Years','4-6 Years','8-10 Years','10-12 Years','12-14 Years']),
    'weight_options' => json_encode(['200g','250g','300g','400g','450g','500g','550g','750g','800g','900g','950g','1kg','1.2kg','1.5kg','1.8kg','2kg','2.5kg','3kg','4kg','5kg','6kg','10kg','20kg'])
];

// Non-empty JSON defaults (kept separate so INSERT IGNORE stays clean)
$default_settings['checkout_fields'] = json_encode(['name' => true, 'phone' => true, 'alt_phone' => true, 'address' => true, 'color' => true, 'note' => true]);
$default_settings['product_colors'] = json_encode([
    ['en' => 'Black', 'bn' => 'কালো'], ['en' => 'White', 'bn' => 'সাদা'], ['en' => 'Red', 'bn' => 'লাল'],
    ['en' => 'Green', 'bn' => 'সবুজ'], ['en' => 'Blue', 'bn' => 'নীল'], ['en' => 'Yellow', 'bn' => 'হলুদ'],
    ['en' => 'Brown', 'bn' => 'বাদামী'], ['en' => 'Orange', 'bn' => 'কমলা'], ['en' => 'Pink', 'bn' => 'গোলাপি'],
    ['en' => 'Purple', 'bn' => 'বেগুনি'], ['en' => 'Grey', 'bn' => 'ধূসর'], ['en' => 'Navy Blue', 'bn' => 'নেভি ব্লু'],
    ['en' => 'Maroon', 'bn' => 'মেরুন'], ['en' => 'Olive', 'bn' => 'অলিভ'], ['en' => 'Gold', 'bn' => 'গোল্ডেন'],
    ['en' => 'Silver', 'bn' => 'রুপালি'], ['en' => 'Teal', 'bn' => 'টিল'], ['en' => 'Beige', 'bn' => 'বেজ'],
    ['en' => 'Magenta', 'bn' => 'ম্যাজেন্টা'], ['en' => 'Cream', 'bn' => 'ক্রিম']
]);

foreach ($default_settings as $key => $val) {
    $st = $db->prepare("INSERT IGNORE INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
    $st->execute([$key, $val]);
}

function get_setting($key) {
    global $db;
    $st = $db->prepare("SELECT setting_value FROM system_settings WHERE setting_key = ?");
    $st->execute([$key]);
    return $st->fetchColumn();
}

function update_setting($key, $val) {
    global $db;
    $st = $db->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
    $st->execute([$key, $val, $val]);
}

function bnToEnNumber($string) {
    $bn = ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'];
    $en = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    return str_replace($bn, $en, $string);
}

function enToBnNumber($string) {
    $en = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    $bn = ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'];
    return str_replace($en, $bn, (string)$string);
}

// Bengali ordinal for loyal customer badge: 2 => "২য়", 3 => "৩য়" ...
function bnOrdinal($n) {
    $map = [1 => '১ম', 2 => '২য়', 3 => '৩য়', 4 => '৪র্থ', 5 => '৫ম', 6 => '৬ষ্ঠ', 7 => '৭ম', 8 => '৮ম', 9 => '৯ম', 10 => '১০ম'];
    if (isset($map[$n])) return $map[$n];
    return enToBnNumber($n) . 'তম';
}

// Build the site base URL (used for auto media link generation)
function base_url() {
    $scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/')), '/');
    return $scheme . '://' . $host . $dir;
}

// Get real client IP (handles common proxies / Cloudflare)
function wa_number($phone) {
    // যেকোনো ফরম্যাট (01711..., +8801711..., 8801711..., বাংলা সংখ্যা) → 8801711... (wa.me সঠিক ফরম্যাট)
    $p = preg_replace('/\D/', '', bnToEnNumber((string)$phone));
    if ($p === '') return '';
    if (strpos($p, '880') === 0) return $p;           // ইতিমধ্যে 880 দিয়ে শুরু
    if (strlen($p) === 11 && $p[0] === '0') return '88' . $p; // 01711... → 8801711...
    if (strlen($p) === 10 && $p[0] === '1') return '880' . $p; // 1711... → 8801711...
    return $p;
}

function get_client_ip() {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = trim(explode(',', $_SERVER[$key])[0]);
            if (filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
        }
    }
    return '';
}

// Fraud Detection: is this phone or IP blocked?
function is_blocked($phone, $ip) {
    global $db;
    $phone = trim((string)$phone);
    $ip = trim((string)$ip);
    if ($phone === '' && $ip === '') return false;
    $st = $db->prepare("SELECT COUNT(*) FROM blocked_customers WHERE (phone IS NOT NULL AND phone != '' AND phone = ?) OR (ip IS NOT NULL AND ip != '' AND ip = ?)");
    $st->execute([$phone, $ip]);
    return $st->fetchColumn() > 0;
}

// 64 Bangladeshi District/Zone Mapping Dictionary (spelling corrected)
$zone_to_bangla = [
    'Dhaka' => 'ঢাকা',
    'Gazipur' => 'গাজীপুর',
    'Manikganj' => 'মানিকগঞ্জ',
    'Munshiganj' => 'মুন্সিগঞ্জ',
    'Narayanganj' => 'নারায়ণগঞ্জ',
    'Narsingdi' => 'নরসিংদী',
    'Faridpur' => 'ফরিদপুর',
    'Gopalganj' => 'গোপালগঞ্জ',
    'Madaripur' => 'মাদারীপুর',
    'Rajbari' => 'রাজবাড়ী',
    'Shariatpur' => 'শরীয়তপুর',
    'Kishoreganj' => 'কিশোরগঞ্জ',
    'Tangail' => 'টাঙ্গাইল',
    'Chattogram' => 'চট্টগ্রাম',
    'Cox\'s Bazar' => 'কক্সবাজার',
    'Brahmanbaria' => 'ব্রাহ্মণবাড়িয়া',
    'Chandpur' => 'চাঁদপুর',
    'Cumilla' => 'কুমিল্লা',
    'Feni' => 'ফেনী',
    'Lakshmipur' => 'লক্ষ্মীপুর',
    'Noakhali' => 'নোয়াখালী',
    'Bandarban' => 'বান্দরবান',
    'Khagrachhari' => 'খাগড়াছড়ি',
    'Rangamati' => 'রাঙ্গামাটি',
    'Rajshahi' => 'রাজশাহী',
    'Bogura' => 'বগুড়া',
    'Chapainawabganj' => 'চাঁপাইনবাবগঞ্জ',
    'Joypurhat' => 'জয়পুরহাট',
    'Naogaon' => 'নওগাঁ',
    'Natore' => 'নাটোর',
    'Pabna' => 'পাবনা',
    'Sirajganj' => 'সিরাজগঞ্জ',
    'Khulna' => 'খুলনা',
    'Bagerhat' => 'বাগেরহাট',
    'Chuadanga' => 'চুয়াডাঙ্গা',
    'Jashore' => 'যশোর',
    'Jhenaidah' => 'ঝিনাইদহ',
    'Kushtia' => 'কুষ্টিয়া',
    'Magura' => 'মাগুরা',
    'Meherpur' => 'মেহেরপুর',
    'Narail' => 'নড়াইল',
    'Satkhira' => 'সাতক্ষীরা',
    'Rangpur' => 'রংপুর',
    'Dinajpur' => 'দিনাজপুর',
    'Gaibandha' => 'গাইবান্ধা',
    'Kurigram' => 'কুড়িগ্রাম',
    'Lalmonirhat' => 'লালমনিরহাট',
    'Nilphamari' => 'নীলফামারী',
    'Panchagarh' => 'পঞ্চগড়',
    'Thakurgaon' => 'ঠাকুরগাঁও',
    'Sylhet' => 'সিলেট',
    'Habiganj' => 'হবিগঞ্জ',
    'Moulvibazar' => 'মৌলভীবাজার',
    'Sunamganj' => 'সুনামগঞ্জ',
    'Barishal' => 'বরিশাল',
    'Barguna' => 'বরগুনা',
    'Bhola' => 'ভোলা',
    'Jhalokathi' => 'ঝালকাঠি',
    'Patuakhali' => 'পটুয়াখালী',
    'Pirojpur' => 'পিরোজপুর',
    'Mymensingh' => 'ময়মনসিংহ',
    'Jamalpur' => 'জামালপুর',
    'Netrokona' => 'নেত্রকোণা',
    'Sherpur' => 'শেরপুর'
];

function detectBanglaDistrict($address) {
    global $zone_to_bangla;
    foreach ($zone_to_bangla as $en => $bn) {
        if (mb_strpos($address, $bn) !== false || mb_strpos(mb_strtolower($address), mb_strtolower($en)) !== false) {
            return $en;
        }
    }
    return null;
}

// Authentication Middleware Helpers
function is_logged_in() {
    return isset($_SESSION['user_id']);
}
function get_user_role() {
    return $_SESSION['user_role'] ?? 'guest';
}
function require_login() {
    if (!is_logged_in()) {
        header("Location: ?action=login");
        exit;
    }
}
function require_admin() {
    require_login();
    if (get_user_role() !== 'admin') {
        die("Forbidden: Access restricted to Administrators only.");
    }
}
function require_admin_or_office() {
    require_login();
    if (!in_array(get_user_role(), ['admin', 'office_team'])) {
        die("Forbidden: Access restricted.");
    }
}

function get_status_style($status) {
    switch ($status) {
        case 'pending':
            return 'bg-amber-500/10 text-amber-500 border-amber-500/30';
        case 'confirmed':
            return 'bg-emerald-500/10 text-emerald-500 border-emerald-500/30';
        case 'no_answer':
            return 'bg-purple-500/10 text-purple-500 border-purple-500/30';
        case 'cancelled':
            return 'bg-rose-500/10 text-rose-500 border-rose-500/30';
        case 'interested_later':
            return 'bg-blue-500/10 text-blue-500 border-blue-500/30';
        case 'did_not_order':
            return 'bg-slate-500/10 text-slate-400 border-slate-500/30';
        case 'phone_off':
            return 'bg-orange-500/10 text-orange-500 border-orange-500/30';
        case 'booked':
            return 'bg-teal-500/10 text-teal-500 border-teal-500/30';
        case 'delivered':
            return 'bg-green-500/10 text-green-400 border-green-500/30';
        default:
            return 'bg-slate-500/10 text-slate-300 border-slate-600';
    }
}

// Color name => Hex map for the on/off style color buttons
$color_hex_map = [
    'Black' => '#000000', 'White' => '#ffffff', 'Red' => '#dc2626', 'Green' => '#16a34a',
    'Blue' => '#2563eb', 'Yellow' => '#eab308', 'Brown' => '#92400e', 'Orange' => '#ea580c',
    'Pink' => '#ec4899', 'Purple' => '#9333ea', 'Grey' => '#6b7280', 'Navy Blue' => '#1e3a8a',
    'Maroon' => '#7f1d1d', 'Olive' => '#65a30d', 'Gold' => '#d4af37', 'Silver' => '#c0c0c0',
    'Teal' => '#0d9488', 'Beige' => '#d6c7a1', 'Magenta' => '#d946ef', 'Cream' => '#f5f0e1'
];
// ডেলিভারি জোন → বাংলা
function delivery_zone_bn($z) {
    $m = ['dhaka' => 'ঢাকার মধ্যে', 'sub_dhaka' => 'সাব ঢাকা', 'outside' => 'সারা বাংলাদেশ'];
    return $m[$z] ?? $z;
}

// SMS পাঠানো (BulkSMSBD API — বাংলাদেশি গেটওয়ে)
function send_sms($phone, $message) {
    $api_key = trim(get_setting('sms_api_key'));
    $sender = trim(get_setting('sms_sender_id'));
    $phone = preg_replace('/\D/', '', bnToEnNumber($phone));
    if ($api_key === '' || $phone === '') return ['status' => 'error', 'message' => 'SMS API কনফিগ নেই'];
    if (!function_exists('curl_init')) return ['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন নেই'];
    if (strlen($phone) === 11 && $phone[0] === '0') $phone = '88' . $phone;
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => 'http://bulksmsbd.net/api/smsapi',
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'api_key' => $api_key, 'type' => 'text', 'number' => $phone,
            'senderid' => $sender, 'message' => $message
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) return ['status' => 'error', 'message' => $err];
    $data = json_decode($res, true);
    $ok = is_array($data) && (int)($data['response_code'] ?? 0) === 202;
    return ['status' => $ok ? 'success' : 'error', 'message' => is_array($data) ? ($data['error_message'] ?? ($data['success_message'] ?? '')) : substr((string)$res, 0, 100)];
}

// SMS টেমপ্লেট রেন্ডার
function sms_render($tpl, $order) {
    return str_replace(
        ['{name}', '{order_id}', '{cod}', '{tracking}'],
        [$order['customer_name'] ?? '', $order['id'] ?? '', number_format((float)($order['cod_amount'] ?? 0)), $order['tracking_code'] ?? ''],
        $tpl
    );
}

// স্টিডফাস্ট কুরিয়ার স্ট্যাটাস → বাংলা লেবেল + রঙ
function courier_status_info($st) {
    $st = strtolower(trim((string)$st));
    $map = [
        'in_review'         => ['In Review — পারসেল বুক হয়েছে', 'bg-sky-500/20 text-sky-400'],
        'pending'           => ['Pending — এখনো ডেলিভারি বাকি', 'bg-amber-500/20 text-amber-400'],
        'hold'              => ['Hold — সাময়িকভাবে আটকে আছে', 'bg-orange-500/20 text-orange-400'],
        'delivered'         => ['Delivered — ডেলিভারি সম্পন্ন ✓', 'bg-emerald-500/20 text-emerald-400'],
        'delivered_approval_pending' => ['Approval Pending — ডেলিভারি অনুমোদনের অপেক্ষায়', 'bg-teal-500/20 text-teal-400'],
        'partial_delivered' => ['Partly — আংশিক ডেলিভারি / পণ্য ফেরত', 'bg-violet-500/20 text-violet-400'],
        'partial_delivered_approval_pending' => ['Partly + Approval Pending', 'bg-violet-500/20 text-violet-400'],
        'cancelled'         => ['Cancelled — পারসেল ক্যান্সেল হয়েছে', 'bg-rose-500/20 text-rose-400'],
        'cancelled_approval_pending' => ['Cancel Approval Pending', 'bg-rose-500/20 text-rose-400'],
        'unknown'           => ['Unknown — স্ট্যাটাস পাওয়া যায়নি', 'bg-slate-500/20 text-slate-400'],
    ];
    if (isset($map[$st])) return $map[$st];
    if (strpos($st, 'approval') !== false) return ['Approval Pending — অনুমোদনের অপেক্ষায়', 'bg-teal-500/20 text-teal-400'];
    return [$st !== '' ? ucfirst($st) : '—', 'bg-slate-500/20 text-slate-400'];
}

function color_hex($en) {
    global $color_hex_map;
    return $color_hex_map[$en] ?? '#475569';
}

// Branding helpers
function branding($key, $fallback = '') {
    $v = trim((string)get_setting($key));
    return $v !== '' ? $v : $fallback;
}
function render_favicon_tag() {
    $fav = branding('favicon_url');
    if ($fav) {
        echo '<link rel="icon" href="' . htmlspecialchars($fav) . '">' . "\n";
    }
}

class IntegrationEngine {

    public static function checkFraud($phone) {
        $phone = bnToEnNumber($phone);
        $apiKey = get_setting('fraud_api_key');
        $apiUrl = get_setting('fraud_api_url') ?: 'https://fraudshield.bd/api/customer/check';
        if (empty($apiKey)) return ['status' => 'error', 'message' => 'API Key কনফিগার করা হয়নি। সেটিংস থেকে FraudShield API Key দিন।'];
        if (!function_exists('curl_init')) return ['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন নেই'];

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $apiKey,
                'Content-Type: application/json',
                'Accept: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode(['phone' => $phone]),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($err) return ['status' => 'error', 'message' => 'কানেকশন এরর: ' . $err];

        // FIX (Feature 17): API sometimes returns empty/invalid body causing
        // "Unexpected end of JSON input" on the client. Always return valid JSON-safe array.
        if ($res === false || trim((string)$res) === '') {
            return ['status' => 'error', 'message' => 'FraudShield API থেকে খালি রেসপন্স এসেছে (HTTP ' . $http_code . ')। API Key/URL সঠিক আছে কিনা যাচাই করুন।'];
        }
        $decoded = json_decode($res, true);
        if (!is_array($decoded)) {
            return ['status' => 'error', 'message' => 'FraudShield API থেকে সঠিক JSON ডাটা পাওয়া যায়নি (HTTP ' . $http_code . ')। রেসপন্স: ' . mb_substr(strip_tags((string)$res), 0, 120)];
        }
        return $decoded;
    }

    // স্টিডফাস্ট পাবলিক ট্র্যাকিং পেজ থেকে ডেলিভারিম্যানের লেটেস্ট নোট (best-effort)
    public static function fetchSteadfastPublicNote($tracking_code) {
        if (empty($tracking_code)) return '';
        if (!function_exists('curl_init')) return '';
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://steadfast.com.bd/t/' . urlencode($tracking_code),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT => 8,
            CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
        ]);
        $html = curl_exec($ch);
        curl_close($ch);
        if (!$html || !is_string($html)) return '';

        $notes = [];
        // ১) পেজে এমবেড করা JSON-এ "note"/"instruction" ফিল্ড খোঁজা
        if (preg_match_all('/"(?:note|notes|instruction|status_note|comment)"\s*:\s*"((?:[^"\\]|\\.)*)"/iu', $html, $m)) {
            foreach ($m[1] as $raw) {
                $t = trim(json_decode('"' . $raw . '"') ?? '');
                if ($t !== '' && strtolower($t) !== 'null') $notes[] = $t;
            }
        }
        // ২) টাইমলাইন লিস্ট আইটেম থেকে টেক্সট (JSON না পেলে) — মেনু/বিজ্ঞাপন/ফুটার আবর্জনা বাদ
        // পেজে অনেক <li> থাকে (নেভিগেশন, ফুটার, বিজ্ঞাপন) — এগুলো নোট নয়, তাই ফিল্টার করা হয়।
        $junk_words = ['বিজ্ঞাপন', 'বিজ্গাপন', 'menu', 'home', 'login', 'register', 'contact', 'about',
                       'privacy', 'terms', 'facebook', 'copyright', 'download', 'app store', 'google play',
                       'হোম', 'লগইন', 'যোগাযোগ', 'সম্পর্কে', 'ডাউনলোড', 'অ্যাপ', 'সকল অধিকার'];
        if (empty($notes) && preg_match_all('/<li[^>]*>(.*?)<\/li>/is', $html, $m2)) {
            foreach ($m2[1] as $li) {
                $t = trim(preg_replace('/\s+/', ' ', strip_tags($li)));
                if (mb_strlen($t) <= 6 || mb_strlen($t) >= 220) continue;
                if (preg_match('~https?://|www\.~i', $t)) continue; // লিংক = মেনু/ফুটার
                $low = mb_strtolower($t);
                $is_junk = false;
                foreach ($junk_words as $jw) { if (mb_stripos($low, mb_strtolower($jw)) !== false) { $is_junk = true; break; } }
                if ($is_junk) continue;
                $notes[] = $t;
            }
        }
        if (empty($notes)) return '';
        $last = end($notes); // সর্বশেষটাই লেটেস্ট আপডেট
        return mb_substr($last, 0, 250);
    }

    // স্টিডফাস্ট delivery status চেক (status_by_cid API)
    public static function checkSteadfastStatus($consignment_id) {
        $apiKey = get_setting('steadfast_api_key');
        $secretKey = get_setting('steadfast_secret_key');
        $baseUrl = get_setting('steadfast_base_url') ?: 'https://portal.packzy.com/api/v1';
        if (empty($apiKey) || empty($secretKey) || empty($consignment_id)) {
            return ['status' => 'error', 'message' => 'API কনফিগ বা Consignment ID নেই'];
        }
        if (!function_exists('curl_init')) return ['status' => 'error', 'message' => 'সার্ভারে PHP cURL নেই'];
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $baseUrl . '/status_by_cid/' . urlencode($consignment_id),
            CURLOPT_HTTPHEADER => [
                'Api-Key: ' . $apiKey,
                'Secret-Key: ' . $secretKey,
                'Content-Type: application/json'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if ($err) return ['status' => 'error', 'message' => $err];
        $data = json_decode($res, true);
        if (!is_array($data)) return ['status' => 'error', 'message' => 'Invalid API response'];
        return $data; // {"status":200, "delivery_status":"pending|delivered|cancelled|partial_delivered|in_review|hold|..."}
    }

    public static function createSteadfastOrder($order) {
        $apiKey = get_setting('steadfast_api_key');
        $secretKey = get_setting('steadfast_secret_key');
        $baseUrl = get_setting('steadfast_base_url') ?: 'https://portal.packzy.com/api/v1';

        if (empty($apiKey) || empty($secretKey)) {
            return ['status' => 'error', 'message' => 'Steadfast API Key/Secret কনফিগার করা হয়নি।'];
        }

        // কুরিয়ার নোট: পণ্যের নাম + কালার + সাইজ/ওজন + কাস্টমারের নোট — সব একসাথে
        $note_bits = [];
        // মাল্টি-প্রোডাক্ট থাকলে সব পণ্য+কোয়ান্টিটি; নাহলে একক পণ্য
        $mp_items = !empty($order['order_items']) ? json_decode($order['order_items'], true) : null;
        if (is_array($mp_items) && count($mp_items) > 0) {
            $mp_bits = [];
            foreach ($mp_items as $mi) {
                $mp_bits[] = ($mi['title'] ?? '') . ' x' . (int)($mi['qty'] ?? 1);
            }
            $note_bits[] = implode(', ', $mp_bits);
        } elseif (!empty($order['product_title'])) {
            $note_bits[] = $order['product_title'];
        }
        if (!empty($order['color_selected'])) $note_bits[] = 'Color: ' . $order['color_selected'];
        if (!empty($order['size_selected'])) $note_bits[] = 'Size: ' . $order['size_selected'];
        if (!empty($order['weight_selected'])) $note_bits[] = 'Weight: ' . $order['weight_selected'];
        $cust_note = trim((string)($order['note'] ?: ''));
        if ($cust_note !== '') $note_bits[] = $cust_note;
        $extra_note = implode(' | ', $note_bits);

        $inv_prefix = get_setting('invoice_prefix');
        if ($inv_prefix === '' || $inv_prefix === false) $inv_prefix = 'ST-';

        $payload = [
            'invoice' => $inv_prefix . $order['id'],
            'recipient_name' => $order['customer_name'],
            'recipient_phone' => bnToEnNumber($order['phone']),
            'recipient_address' => $order['address'],
            'cod_amount' => (int)$order['cod_amount'],
            'note' => $extra_note ?: 'Auto booking from SunnahTi Platform',
            'alternative_phone' => $order['alternative_phone'] ? bnToEnNumber($order['alternative_phone']) : '',
            'delivery_type' => 0
        ];

        if (!function_exists('curl_init')) return ['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন নেই — cPanel থেকে চালু করুন'];
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $baseUrl . '/create_order',
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Api-Key: ' . $apiKey,
                'Secret-Key: ' . $secretKey,
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15
        ]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        if ($err) return ['status' => 'error', 'message' => $err];
        $decoded = json_decode($res, true);
        if (!is_array($decoded)) {
            return ['status' => 'error', 'message' => 'Steadfast API থেকে সঠিক রেসপন্স পাওয়া যায়নি।'];
        }
        return $decoded;
    }

    public static function checkSteadfastBalance() {
        $apiKey = get_setting('steadfast_api_key');
        $secretKey = get_setting('steadfast_secret_key');
        $baseUrl = get_setting('steadfast_base_url') ?: 'https://portal.packzy.com/api/v1';

        if (empty($apiKey) || empty($secretKey)) return 'N/A (Missing Key)';
        if (!function_exists('curl_init')) return 'N/A (No cURL)';

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $baseUrl . '/get_balance',
            CURLOPT_HTTPHEADER => [
                'Api-Key: ' . $apiKey,
                'Secret-Key: ' . $secretKey,
                'Content-Type: application/json'
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $res = curl_exec($ch);
        $curl_err = curl_error($ch);
        curl_close($ch);
        if ($curl_err) return 'Connection Error';
        $data = json_decode($res, true);
        return isset($data['current_balance']) ? $data['current_balance'] . ' BDT' : 'Error / Unauthorized';
    }

    public static function sendFacebookCAPIEvent($orderId, $name, $phone, $value, $productName) {
        $pixelId = get_setting('facebook_pixel');
        $accessToken = get_setting('facebook_access_token');
        $testCode = get_setting('facebook_test_code');

        if (empty($pixelId) || empty($accessToken)) {
            return false;
        }

        $cleanPhone = preg_replace('/[^0-9]/', '', bnToEnNumber($phone));
        if (strlen($cleanPhone) === 11 && strpos($cleanPhone, '01') === 0) {
            $cleanPhone = '88' . $cleanPhone;
        }
        $hashPhone = hash('sha256', $cleanPhone);

        $cleanName = str_replace(' ', '', strtolower(trim($name)));
        $hashName = hash('sha256', $cleanName);

        $clientIp = get_client_ip();
        $clientUa = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $eventSourceUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? '');

        $eventData = [
            'event_name' => 'Purchase',
            'event_time' => time(),
            'event_id' => 'order_' . $orderId,
            'action_source' => 'website',
            'event_source_url' => $eventSourceUrl,
            'user_data' => array_filter([
                'ph' => [$hashPhone],
                'fn' => [$hashName],
                'client_ip_address' => $clientIp,
                'client_user_agent' => $clientUa
            ]),
            'custom_data' => [
                'currency' => 'BDT',
                'value' => (float)$value,
                'content_name' => $productName,
                'content_type' => 'product'
            ]
        ];

        if (!empty($testCode)) {
            $eventData['test_event_code'] = $testCode;
        }

        $payload = [
            'data' => [$eventData]
        ];

        if (!function_exists('curl_init')) return;
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => "https://graph.facebook.com/v17.0/{$pixelId}/events?access_token={$accessToken}",
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $res = curl_exec($ch);
        curl_close($ch);

        return json_decode($res, true);
    }

    public static function sendTiktokCAPIEvent($orderId, $phone, $value, $productName) {
        $pixelId = get_setting('tiktok_pixel');
        $accessToken = get_setting('tiktok_access_token');
        $testCode = get_setting('tiktok_test_code');

        if (empty($pixelId) || empty($accessToken)) {
            return false;
        }

        $cleanPhone = preg_replace('/[^0-9]/', '', bnToEnNumber($phone));
        if (strlen($cleanPhone) === 11 && strpos($cleanPhone, '01') === 0) {
            $cleanPhone = '88' . $cleanPhone;
        }
        $hashPhone = hash('sha256', '+' . $cleanPhone);

        $clientIp = get_client_ip();
        $clientUa = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $eventSourceUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . ($_SERVER['HTTP_HOST'] ?? '') . ($_SERVER['REQUEST_URI'] ?? '');

        $payload = [
            'pixel_code' => $pixelId,
            'event' => 'CompletePayment',
            'event_id' => 'order_' . $orderId,
            'timestamp' => date('c'),
            'context' => [
                'page' => [
                    'url' => $eventSourceUrl
                ],
                'user' => [
                    'phone_number' => $hashPhone
                ],
                'ip' => $clientIp,
                'user_agent' => $clientUa
            ],
            'properties' => [
                'currency' => 'BDT',
                'value' => (float)$value,
                'contents' => [
                    [
                        'content_name' => $productName,
                        'quantity' => 1,
                        'price' => (float)$value
                    ]
                ]
            ]
        ];

        if (!empty($testCode)) {
            $payload['test_event_code'] = $testCode;
        }

        if (!function_exists('curl_init')) return;
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => "https://business-api.tiktok.com/open_api/v1.3/event/track/",
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Access-Token: ' . $accessToken,
                'Content-Type: application/json'
            ],
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10
        ]);
        $res = curl_exec($ch);
        curl_close($ch);

        return json_decode($res, true);
    }

    // Feature 3: Push a new order row to Google Sheet via Apps Script Web App URL
    public static function sendToGoogleSheet($order_id, $order_data) {
        if (get_setting('gsheet_enabled') !== '1') return false;
        $url = trim((string)get_setting('gsheet_webapp_url'));
        if (empty($url)) return false;

        $payload = [
            'sheet'    => get_setting('gsheet_sheet_name') ?: 'Orders',
            'order_id' => $order_id,
            'date'     => date('Y-m-d H:i:s'),
            'name'     => $order_data['customer_name'] ?? '',
            'phone'    => $order_data['phone'] ?? '',
            'address'  => $order_data['address'] ?? '',
            'product'  => $order_data['product_title'] ?? '',
            'color'    => $order_data['color_selected'] ?? '',
            'size'     => $order_data['size_selected'] ?? '',
            'weight'   => $order_data['weight_selected'] ?? '',
            'amount'   => $order_data['cod_amount'] ?? 0,
            'status'   => $order_data['status'] ?? 'pending',
            'ip'       => $order_data['customer_ip'] ?? ''
        ];

        if (!function_exists('curl_init')) return;
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 5,
            CURLOPT_TIMEOUT => 8
        ]);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }
}

if (get_setting('cron_secret') === '' || get_setting('cron_secret') === false) {
    try { update_setting('cron_secret', bin2hex(random_bytes(12))); } catch (Exception $e) {}
}

$action = $_GET['action'] ?? 'dashboard';

// --- রুট ডোমেইন হোম পেজ: action ছাড়া সরাসরি ডোমেইনে ঢুকলে নির্বাচিত ল্যান্ডিং পেজ দেখাবে ---
if (!isset($_GET['action']) && !isset($_GET['slug'])) {
    $home_slug = trim((string)get_setting('home_page_slug'));
    if ($home_slug !== '') {
        $action = 'view';
        $_GET['slug'] = $home_slug;
    }
    // খালি থাকলে আগের মতোই লগইন/ড্যাশবোর্ডে যাবে
}

// --- FRONTEND LANDING PAGE DISPATCHER ---
// পাবলিক শর্ট-লিংক রিডাইরেক্ট: ?action=go&code=xxx → target_url (কোনো লগইন লাগে না)
if ($action === 'go' && isset($_GET['code'])) {
    $code = trim($_GET['code']);
    $stmt = $db->prepare("SELECT * FROM short_links WHERE code = ? AND active = 1");
    $stmt->execute([$code]);
    $link = $stmt->fetch();
    if ($link) {
        try { $db->prepare("UPDATE short_links SET clicks = clicks + 1 WHERE id = ?")->execute([(int)$link['id']]); } catch (Exception $e) {}
        $url = $link['target_url'];
        if (!preg_match('~^https?://~i', $url)) $url = 'https://' . $url;
        header('Location: ' . $url, true, 302);
        exit;
    }
    http_response_code(404);
    echo '<!DOCTYPE html><html lang="bn"><head><meta charset="UTF-8"><title>লিংক পাওয়া যায়নি</title><style>body{font-family:Arial;background:#0f172a;color:#fff;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;text-align:center}</style></head><body><div><h1>😕 ৪০৪</h1><p>এই শর্ট লিংকটি খুঁজে পাওয়া যায়নি বা নিষ্ক্রিয় করা হয়েছে।</p></div></body></html>';
    exit;
}

if ($action === 'view' && isset($_GET['slug'])) {
    $slug = $_GET['slug'];
    $stmt = $db->prepare("SELECT * FROM pages WHERE slug = ?");
    $stmt->execute([$slug]);
    $page = $stmt->fetch();

    if (!$page) {
        // Fallback: Check if it's a product slug
        $stmt = $db->prepare("SELECT * FROM products WHERE slug = ?");
        $stmt->execute([$slug]);
        $product = $stmt->fetch();
        if ($product) {
            render_dynamic_product_landing($product);
            exit;
        }
        die("<h3>404 Page/Product Not Found</h3>");
    }
    render_dynamic_landing_page($page);
    exit;
}

// Feature 13: Incomplete Order Capture (Public endpoint, called silently from landing page JS)
if ($action === 'save_incomplete') {
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error']);
        exit;
    }
    $token = substr(trim($_POST['token'] ?? ''), 0, 64);
    $name = mb_substr(trim($_POST['customer_name'] ?? ''), 0, 150);
    $phone = mb_substr(bnToEnNumber(trim($_POST['phone'] ?? '')), 0, 20);
    $address = mb_substr(trim($_POST['address'] ?? ''), 0, 1000);
    $product_id = (int)($_POST['product_id'] ?? 0);
    $page_slug = mb_substr(trim($_POST['page_slug'] ?? ''), 0, 255);
    $ip = get_client_ip();

    // Save partial or full info but only if there is something meaningful
    if ($token === '' || (mb_strlen($name) < 2 && strlen($phone) < 6 && mb_strlen($address) < 5)) {
        echo json_encode(['status' => 'skipped']);
        exit;
    }

    try {
        $st = $db->prepare("INSERT INTO incomplete_orders (token, customer_name, phone, address, product_id, page_slug, customer_ip, updated_at)
                            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
                            ON DUPLICATE KEY UPDATE customer_name = VALUES(customer_name), phone = VALUES(phone), address = VALUES(address),
                            product_id = VALUES(product_id), page_slug = VALUES(page_slug), customer_ip = VALUES(customer_ip), updated_at = NOW()");
        $st->execute([$token, $name, $phone, $address, $product_id ?: null, $page_slug, $ip]);
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error']);
    }
    exit;
}

// Handle Order Form Submission (AJAX/Post)
if ($action === 'submit_order') {
    header('Content-Type: application/json');
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Request Method']);
        exit;
    }

    $name = trim($_POST['customer_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $alt_phone = trim($_POST['alternative_phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $product_id = (int)($_POST['product_id'] ?? 0);
    $color = trim($_POST['color_selected'] ?? '');
    $size = trim($_POST['size_selected'] ?? '');
    $weight = trim($_POST['weight_selected'] ?? '');
    $note = trim($_POST['note'] ?? '');
    $incomplete_token = substr(trim($_POST['incomplete_token'] ?? ''), 0, 64);

    // Custom weight (kg) support
    if ($weight === 'custom') {
        $custom_kg = trim(bnToEnNumber($_POST['weight_custom'] ?? ''));
        $custom_kg = preg_replace('/[^0-9.]/', '', $custom_kg);
        $weight = $custom_kg !== '' ? $custom_kg . 'kg' : '';
    }

    // Cleanup phone - convert Bangla digits to English
    $phone = bnToEnNumber($phone);
    $alt_phone = bnToEnNumber($alt_phone);

    // Validate 11-digit phone
    if (!preg_match('/^(01)[3-9][0-9]{8}$/', $phone)) {
        echo json_encode(['status' => 'error', 'message' => 'দয়া করে একটি সঠিক ১১ ডিজিটের সচল মোবাইল নম্বর দিন (যেমন: 017XXXXXXXX)']);
        exit;
    }

    if (empty($name) || empty($address)) {
        echo json_encode(['status' => 'error', 'message' => 'অনুগ্রহ করে নাম এবং সম্পূর্ণ ডেলিভারি ঠিকানা প্রদান করুন।']);
        exit;
    }

    if (empty($product_id)) {
        echo json_encode(['status' => 'error', 'message' => 'অনুগ্রহ করে একটি প্রোডাক্ট সিলেক্ট করুন।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // ==== মাল্টি-প্রোডাক্ট: order_items JSON এলে সার্ভার-সাইডে দাম যাচাই করে সেভ ====
    $order_items_save = null;
    if (!empty($_POST['order_items'])) {
        $decoded_items = json_decode($_POST['order_items'], true);
        if (is_array($decoded_items) && count($decoded_items) > 0) {
            $verified_items = [];
            foreach ($decoded_items as $it) {
                $ipid = (int)($it['product_id'] ?? 0);
                $iqty = max(1, (int)($it['qty'] ?? 1));
                if ($ipid <= 0) continue;
                // দাম DB থেকে নেওয়া হয় (কাস্টমার টেম্পার করলেও আসল দাম বসবে)
                $pst = $db->prepare("SELECT title, price, sale_price FROM products WHERE id = ?");
                $pst->execute([$ipid]);
                $prow = $pst->fetch();
                if (!$prow) continue;
                $iprice = ($prow['sale_price'] !== null && $prow['sale_price'] > 0) ? (float)$prow['sale_price'] : (float)$prow['price'];
                $verified_items[] = ['product_id' => $ipid, 'title' => $prow['title'], 'qty' => $iqty, 'price' => $iprice];
            }
            if (count($verified_items) > 0) {
                $order_items_save = json_encode($verified_items, JSON_UNESCAPED_UNICODE);
                // প্রধান product_id = প্রথম আইটেম
                $product_id = $verified_items[0]['product_id'];
            }
        }
    }

    // এক্সট্রা কাস্টম ফিল্ড (পেজ/প্রোডাক্ট-লেভেল কনফিগ — লেবেল ফর্ম থেকেই আসে)
    $custom_field_value = trim($_POST['custom_field_value'] ?? '');
    $custom_field_label = trim($_POST['custom_field_label'] ?? '');
    if ($custom_field_label !== '' && $custom_field_value === '') {
        echo json_encode(['status' => 'error', 'message' => '"' . $custom_field_label . '" — এই ঘরটি পূরণ করা আবশ্যক।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    // Feature 9/10: Auto capture customer IP + Blocked customer check
    $customer_ip = get_client_ip();
    if (is_blocked($phone, $customer_ip)) {
        echo json_encode(['status' => 'error', 'message' => 'দুঃখিত, এই মুহূর্তে আপনার অর্ডারটি গ্রহণ করা সম্ভব হচ্ছে না। প্রয়োজনে আমাদের হেল্পলাইনে যোগাযোগ করুন।']);
        exit;
    }

    // ==== রিপিট-অর্ডার গার্ড: ১ দিনে ১ কাস্টমার (ফোন বা IP) একবারই অর্ডার করতে পারবে ====
    // এটি Facebook Purchase ডাবল/ট্রিপল কাউন্টও ঠেকায় — একই কাস্টমার বারবার সাবমিট করলে নতুন অর্ডার তৈরি হয় না,
    // তাই একটি অর্ডার একবারই Purchase ইভেন্ট ফায়ার করে।
    // শুধু পাবলিক ল্যান্ডিং পেজের কাস্টমারের জন্য গার্ড — প্যানেলে লগইন করা admin/office/agent
    // একই কাস্টমারের একাধিক অর্ডার তৈরি করতে পারবে (তাদের ক্ষেত্রে গার্ড স্কিপ)।
    $brh_setting = get_setting('block_repeat_hours');
    $block_hours = ($brh_setting === '' || $brh_setting === false) ? 24 : (int)$brh_setting;
    if ($block_hours > 0 && !is_logged_in()) {
        $dup = $db->prepare("SELECT id, created_at FROM orders
                             WHERE is_deleted = 0
                               AND (phone = ? OR (customer_ip <> '' AND customer_ip = ?))
                               AND created_at >= (NOW() - INTERVAL ? HOUR)
                             ORDER BY id DESC LIMIT 1");
        $dup->execute([$phone, $customer_ip, $block_hours]);
        $prev = $dup->fetch();
        if ($prev) {
            $wa_support = preg_replace('/\D/', '', bnToEnNumber(get_setting('support_whatsapp')));
            $wa_link = '';
            if ($wa_support !== '') {
                if (strlen($wa_support) === 11 && $wa_support[0] === '0') $wa_support = '88' . $wa_support;
                $wa_msg = rawurlencode('আসসালামু আলাইকুম, আমি একটি অর্ডার করেছি (#' . $prev['id'] . ') কিন্তু আবার অর্ডার করতে গিয়ে সমস্যা হচ্ছে। সাহায্য করুন।');
                $wa_link = 'https://wa.me/' . $wa_support . '?text=' . $wa_msg;
            }
            echo json_encode([
                'status' => 'repeat_blocked',
                'wa_link' => $wa_link,
                'message' => 'আপনি ইতিমধ্যে একটি অর্ডার করেছেন (অর্ডার #' . $prev['id'] . ')। একই দিনে আবার অর্ডার করা যাবে না। কোনো সমস্যা থাকলে অনুগ্রহ করে আমাদের WhatsApp-এ মেসেজ দিন।'
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }

    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    $cod_amount = $product ? ($product['sale_price'] ?: $product['price']) : 0;

    // ---- ডেলিভারি এলাকা ও কুরিয়ার চার্জ (সেটিংস থেকে — ক্লায়েন্টের পাঠানো মান বিশ্বাস করা হয় না) ----
    $delivery_zone = trim($_POST['delivery_zone'] ?? '');
    $delivery_charge = 0;
    if (($_POST['courier_charge_on'] ?? '') === '1') {
        $zone_charges = [
            'dhaka' => (int)(get_setting('courier_charge_dhaka') ?: 60),
            'sub_dhaka' => (int)(get_setting('courier_charge_sub_dhaka') ?: 100),
            'outside' => (int)(get_setting('courier_charge_outside') ?: 130),
        ];
        if (!isset($zone_charges[$delivery_zone])) {
            echo json_encode(['status' => 'error', 'message' => 'অনুগ্রহ করে আপনার ডেলিভারি এলাকা সিলেক্ট করুন।'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $delivery_charge = $zone_charges[$delivery_zone];
    } else {
        $delivery_zone = '';
    }

    // ---- প্রোমো কোড রি-ভ্যালিডেশন (সাবমিটের মুহূর্তেও বৈধ কিনা) ----
    $promo_code_in = strtoupper(trim($_POST['promo_code'] ?? ''));
    $discount_amount = 0;
    $promo_row = null;
    if ($promo_code_in !== '') {
        $pvs = $db->prepare("SELECT * FROM promo_codes WHERE code = ? LIMIT 1");
        $pvs->execute([$promo_code_in]);
        $promo_row = $pvs->fetch();
        $promo_valid = $promo_row && $promo_row['active']
            && (empty($promo_row['valid_until']) || strtotime($promo_row['valid_until'] . ' 23:59:59') >= time())
            && ((int)$promo_row['max_uses'] <= 0 || (int)$promo_row['used_count'] < (int)$promo_row['max_uses']);
        if (!$promo_valid) {
            echo json_encode(['status' => 'error', 'message' => 'দুঃখিত, প্রোমো কোডটি এখন আর প্রযোজ্য নয়। কোডটি মুছে আবার অর্ডার করুন।'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $discount_amount = $promo_row['discount_type'] === 'percent'
            ? round((float)$cod_amount * (float)$promo_row['discount_value'] / 100, 2)
            : (float)$promo_row['discount_value'];
        if ($discount_amount > (float)$cod_amount) $discount_amount = (float)$cod_amount;
    }

    // চূড়ান্ত COD = মূল্য − ছাড় + ডেলিভারি চার্জ
    $cod_amount = max(0, (float)$cod_amount - $discount_amount + $delivery_charge);
    $product_title = $product ? $product['title'] : 'Dynamic Premium Item';

    // Run Fraud Check immediately for automated flag
    $fraud_score = null;
    $fraud_summary = null;
    $fraud_res = IntegrationEngine::checkFraud($phone);

    // Parse numerical score and build nested summary payload cleanly
    if ($fraud_res && !isset($fraud_res['status']) && isset($fraud_res['fraudRiskScore'])) {
        $fraud_score = (int)($fraud_res['fraudRiskScore']['score'] ?? 0);
        $fraud_summary = json_encode([
            'summary' => $fraud_res['courierData']['summary'] ?? [],
            'courierData' => $fraud_res['courierData'] ?? [],
            'fraudRiskScore' => $fraud_res['fraudRiskScore'] ?? [],
            'reviews' => $fraud_res['reviews'] ?? []
        ], JSON_UNESCAPED_UNICODE);
    }

    // ফ্রড রিস্ক লিমিট গেট: রিস্ক লিমিটের বেশি হলে এডভান্স ছাড়া অর্ডার হবে না
    $fb_threshold = (int)get_setting('fraud_block_threshold');
    $advance_trx = trim($_POST['advance_trx'] ?? '');
    $advance_proof_url = null;
    $adv_amt = (int)(get_setting('advance_amount') ?: '150');
    $high_risk = ($fb_threshold > 0 && $fraud_score !== null && $fraud_score >= $fb_threshold);
    if ($high_risk) {
        $has_ss = !empty($_FILES['advance_screenshot']) && $_FILES['advance_screenshot']['error'] === UPLOAD_ERR_OK && $_FILES['advance_screenshot']['size'] > 0;
        if ($advance_trx === '' && !$has_ss) {
            echo json_encode([
                'status' => 'advance_required',
                'risk' => $fraud_score,
                'amount' => $adv_amt,
                'bkash' => get_setting('advance_bkash'),
                'nagad' => get_setting('advance_nagad'),
                'message' => 'দুঃখিত! আপনার নাম্বারে পূর্বের কুরিয়ার রেকর্ডে ঝুঁকি ' . $fraud_score . '% পাওয়া গেছে। অর্ডার কনফার্ম করতে ' . $adv_amt . ' টাকা এডভান্স (বিকাশ/নগদ সেন্ড মানি) পাঠিয়ে ট্রানজেকশন আইডি অথবা পেমেন্টের স্ক্রিনশট দিন — বাকি টাকা ডেলিভারির সময় দিবেন।'
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        // স্ক্রিনশট প্রুফ সেভ
        if ($has_ss && $_FILES['advance_screenshot']['size'] <= 10 * 1024 * 1024) {
            $imginfo = @getimagesize($_FILES['advance_screenshot']['tmp_name']);
            if ($imginfo !== false) {
                if (!is_dir(ADV_DIR)) @mkdir(ADV_DIR, 0755, true);
                if (is_dir(ADV_DIR) && is_writable(ADV_DIR)) {
                    $ext_map = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp'];
                    $aext = $ext_map[$imginfo[2]] ?? 'jpg';
                    $aname = 'adv_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $aext;
                    if (@move_uploaded_file($_FILES['advance_screenshot']['tmp_name'], ADV_DIR . '/' . $aname)) {
                        $advance_proof_url = rtrim(base_url(), '/') . '/uploads/advance/' . $aname;
                    }
                }
            }
        }
        $note = trim(($note !== '' ? $note . "\n" : '') . '⚠️ হাই রিস্ক (' . $fraud_score . '%) — ' . $adv_amt . '৳ এডভান্স প্রুফ দিয়েছে।' . ($advance_trx !== '' ? ' TrxID: ' . $advance_trx : ''));
    }

    try {
        $ins = $db->prepare("INSERT INTO orders (customer_name, phone, alternative_phone, address, product_id, color_selected, size_selected, weight_selected, cod_amount, fraud_score, fraud_summary, customer_ip, note, advance_trx, advance_proof_url, custom_field_value, custom_field_label, delivery_zone, delivery_charge, promo_code, discount_amount, order_items, status, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0)");
        $ins->execute([$name, $phone, $alt_phone, $address, $product_id, $color, $size, $weight, $cod_amount, $fraud_score, $fraud_summary, $customer_ip, $note, $advance_trx !== '' ? $advance_trx : null, $advance_proof_url, $custom_field_value !== '' ? $custom_field_value : null, $custom_field_label !== '' ? $custom_field_label : null, $delivery_zone !== '' ? $delivery_zone : null, $delivery_charge, $promo_code_in !== '' ? $promo_code_in : null, $discount_amount, $order_items_save]);
        $order_id = $db->lastInsertId();

        // প্রোমো কোডের ব্যবহার গণনা
        if ($promo_row) {
            try { $db->prepare("UPDATE promo_codes SET used_count = used_count + 1 WHERE id = ?")->execute([(int)$promo_row['id']]); } catch (Exception $e) {}
        }
        // স্টক অটো কমা (স্টক ট্র্যাক করা প্রোডাক্টে) — প্রতি অর্ডারে ঠিক ১ কমবে
        if ($product_id) {
            try { $db->prepare("UPDATE products SET stock = stock - 1 WHERE id = ? AND stock IS NOT NULL AND stock > 0")->execute([$product_id]); } catch (Exception $e) {}
        }

        // Feature 13: Remove matching incomplete order records (order completed)
        try {
            if ($incomplete_token !== '') {
                $db->prepare("DELETE FROM incomplete_orders WHERE token = ?")->execute([$incomplete_token]);
            }
            $db->prepare("DELETE FROM incomplete_orders WHERE phone = ?")->execute([$phone]);
        } catch (Exception $e) {}

        // Server-Side Facebook & TikTok Conversion API (CAPI) Event Fire
        IntegrationEngine::sendFacebookCAPIEvent($order_id, $name, $phone, $cod_amount, $product_title);
        IntegrationEngine::sendTiktokCAPIEvent($order_id, $phone, $cod_amount, $product_title);

        // Feature 3: Push to Google Sheet (if enabled)
        IntegrationEngine::sendToGoogleSheet($order_id, [
            'customer_name' => $name, 'phone' => $phone, 'address' => $address,
            'product_title' => $product_title, 'color_selected' => $color,
            'size_selected' => $size, 'weight_selected' => $weight,
            'cod_amount' => $cod_amount, 'status' => 'pending', 'customer_ip' => $customer_ip
        ]);

        echo json_encode(['status' => 'success', 'message' => 'আপনার অর্ডারটি সফলভাবে সম্পন্ন হয়েছে!', 'order_id' => $order_id]);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'Error saving order: ' . $e->getMessage()]);
    }
    exit;
}

// 5. Backend Logic Handlers (Requires Login)
if (in_array($action, ['login', 'do_login'])) {
    if ($action === 'do_login') {
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');
        $stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['user_role'] = $user['role'];
            header("Location: ?action=dashboard");
            exit;
        } else {
            $error = "ভুল ইউজারনেম অথবা পাসওয়ার্ড!";
        }
    }
    // Render Login Interface
    render_login_view($error ?? null);
    exit;
}

if ($action === 'logout') {
    session_destroy();
    header("Location: ?action=login");
    exit;
}

// Ensure logged in for all remaining dashboard/API endpoints
// WhatsApp Cloud API ওয়েবহুক (পাবলিক — Meta এখানে ইনকামিং মেসেজ পাঠাবে)
if ($action === 'wa_webhook') {
    // ভেরিফিকেশন (Meta ড্যাশবোর্ডে ওয়েবহুক সেট করার সময়)
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (($_GET['hub_mode'] ?? $_GET['hub.mode'] ?? '') === 'subscribe'
            && hash_equals((string)get_setting('cron_secret'), (string)($_GET['hub_verify_token'] ?? $_GET['hub.verify_token'] ?? ''))) {
            echo $_GET['hub_challenge'] ?? $_GET['hub.challenge'] ?? '';
        } else {
            http_response_code(403);
            echo 'verify failed';
        }
        exit;
    }
    // ইনকামিং মেসেজ রিসিভ
    $raw = file_get_contents('php://input');
    $payload = json_decode($raw, true);
    if (is_array($payload)) {
        foreach (($payload['entry'] ?? []) as $entry) {
            foreach (($entry['changes'] ?? []) as $chg) {
                $val = $chg['value'] ?? [];
                $pnid = $val['metadata']['phone_number_id'] ?? '';
                if ($pnid === '') continue;
                $ast = $db->prepare("SELECT id FROM msg_accounts WHERE channel = 'whatsapp' AND ext_id = ? AND active = 1 LIMIT 1");
                $ast->execute([$pnid]);
                $acct = $ast->fetch();
                if (!$acct) continue;
                // কন্টাক্ট নাম ম্যাপ
                $names = [];
                foreach (($val['contacts'] ?? []) as $ct) {
                    $names[$ct['wa_id'] ?? ''] = $ct['profile']['name'] ?? '';
                }
                foreach (($val['messages'] ?? []) as $wm) {
                    $from = $wm['from'] ?? '';
                    $body = $wm['text']['body'] ?? ($wm['button']['text'] ?? ($wm['interactive']['button_reply']['title'] ?? '[মিডিয়া/অন্য টাইপ মেসেজ]'));
                    $mid = $wm['id'] ?? null;
                    if ($from === '') continue;
                    try {
                        $db->prepare("INSERT IGNORE INTO inbox_messages (account_id, contact_ext_id, contact_name, direction, body, ext_msg_id, created_at) VALUES (?, ?, ?, 'in', ?, ?, ?)")
                           ->execute([(int)$acct['id'], $from, $names[$from] ?? null, $body, $mid, isset($wm['timestamp']) ? date('Y-m-d H:i:s', (int)$wm['timestamp']) : date('Y-m-d H:i:s')]);
                    } catch (Exception $e) {}
                }
            }
        }
    }
    echo 'OK';
    exit;
}

// প্রোমো কোড যাচাই (পাবলিক — ল্যান্ডিং পেজ থেকে AJAX)
if ($action === 'apply_promo') {
    header('Content-Type: application/json; charset=utf-8');
    $p_code = strtoupper(trim($_POST['code'] ?? $_GET['code'] ?? ''));
    $p_pid  = (int)($_POST['product_id'] ?? $_GET['product_id'] ?? 0);
    if ($p_code === '') { echo json_encode(['status' => 'error', 'message' => 'প্রোমো কোড লিখুন']); exit; }
    $pst = $db->prepare("SELECT * FROM promo_codes WHERE code = ? LIMIT 1");
    $pst->execute([$p_code]);
    $promo = $pst->fetch();
    if (!$promo || !$promo['active']) { echo json_encode(['status' => 'error', 'message' => 'প্রোমো কোডটি সঠিক নয়!'], JSON_UNESCAPED_UNICODE); exit; }
    if (!empty($promo['valid_until']) && strtotime($promo['valid_until'] . ' 23:59:59') < time()) {
        echo json_encode(['status' => 'error', 'message' => 'দুঃখিত, প্রোমো কোডটির মেয়াদ শেষ হয়ে গেছে!'], JSON_UNESCAPED_UNICODE); exit;
    }
    if ((int)$promo['max_uses'] > 0 && (int)$promo['used_count'] >= (int)$promo['max_uses']) {
        echo json_encode(['status' => 'error', 'message' => 'দুঃখিত, প্রোমো কোডটির ব্যবহারের সীমা শেষ!'], JSON_UNESCAPED_UNICODE); exit;
    }
    $price = 0;
    if ($p_pid) {
        $prs = $db->prepare("SELECT price, sale_price FROM products WHERE id = ?");
        $prs->execute([$p_pid]);
        if ($pr = $prs->fetch()) $price = (float)(($pr['sale_price'] !== null && $pr['sale_price'] > 0) ? $pr['sale_price'] : $pr['price']);
    }
    $discount = $promo['discount_type'] === 'percent' ? round($price * (float)$promo['discount_value'] / 100, 2) : (float)$promo['discount_value'];
    if ($price > 0 && $discount > $price) $discount = $price;
    echo json_encode([
        'status' => 'success',
        'code' => $promo['code'],
        'discount' => $discount,
        'label' => $promo['discount_type'] === 'percent' ? ((float)$promo['discount_value'] . '% ছাড়') : ('৳' . (float)$promo['discount_value'] . ' ছাড়'),
        'message' => 'প্রোমো কোড প্রয়োগ হয়েছে! ছাড়: ৳' . $discount
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

require_login();

// Real-Time Fraud Intel Endpoints (Feature 17: always emit valid JSON)
if ($action === 'ajax_fraud_check' && isset($_GET['phone'])) {
    header('Content-Type: application/json');
    $phone = trim($_GET['phone']);
    $res = IntegrationEngine::checkFraud($phone);
    if (!is_array($res)) {
        $res = ['status' => 'error', 'message' => 'ডাটা রিট্রিভ করা সম্ভব হয়নি। কিছুক্ষণ পর আবার চেষ্টা করুন।'];
    }
    echo json_encode($res, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'ajax_get_fraud_details' && isset($_GET['phone'])) {
    header('Content-Type: application/json');
    $phone = trim($_GET['phone']);
    $res = IntegrationEngine::checkFraud($phone);
    if (!is_array($res)) {
        $res = ['status' => 'error', 'message' => 'ডাটা রিট্রিভ করা সম্ভব হয়নি। কিছুক্ষণ পর আবার চেষ্টা করুন।'];
    }
    echo json_encode($res, JSON_UNESCAPED_UNICODE);
    exit;
}

// Feature 14: Save order note via AJAX (all logged in users can update)
if ($action === 'ajax_save_note' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $id = (int)($_POST['id'] ?? 0);
    $note = trim($_POST['note'] ?? '');
    if ($id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'অর্ডার আইডি সঠিক নয়।']);
        exit;
    }
    $stmt = $db->prepare("UPDATE orders SET note = ?, updated_by = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$note, $_SESSION['username'], $id]);
    echo json_encode(['status' => 'success', 'message' => 'নোট সফলভাবে সেভ করা হয়েছে!'], JSON_UNESCAPED_UNICODE);
    exit;
}

// Feature 12: Loyal Customer - full order history for one phone number
if ($action === 'ajax_customer_history' && isset($_GET['phone'])) {
    header('Content-Type: application/json');
    global $status_map;
    $phone = trim($_GET['phone']);
    $stmt = $db->prepare("SELECT o.id, o.status, o.cod_amount, o.is_deleted, o.created_at, o.color_selected, o.size_selected, o.weight_selected, p.title AS product_title
                          FROM orders o LEFT JOIN products p ON o.product_id = p.id
                          WHERE o.phone = ? ORDER BY o.id DESC");
    $stmt->execute([$phone]);
    $rows = $stmt->fetchAll();
    $out = [];
    foreach ($rows as $r) {
        $out[] = [
            'id' => $r['id'],
            'status' => $r['status'],
            'status_label' => $r['is_deleted'] ? 'Deleted' : ($status_map[$r['status']] ?? $r['status']),
            'is_deleted' => (int)$r['is_deleted'],
            'cod' => number_format((float)$r['cod_amount'], 2),
            'created_at' => $r['created_at'],
            'product' => $r['product_title'] ?: 'Dynamic Item',
            'color' => $r['color_selected'] ?: '',
            'size' => $r['size_selected'] ?: '',
            'weight' => $r['weight_selected'] ?: ''
        ];
    }
    $active_total = 0;
    foreach ($out as $o_row) { if (!$o_row['is_deleted']) $active_total++; }
    echo json_encode(['status' => 'success', 'phone' => $phone, 'total' => $active_total, 'total_all' => count($out), 'orders' => $out], JSON_UNESCAPED_UNICODE);
    exit;
}

// A4 ইনভয়েস প্রিন্ট
if ($action === 'invoice' && isset($_GET['id'])) {
    require_login();
    $iid = (int)$_GET['id'];
    $st = $db->prepare("SELECT o.*, p.title AS product_title FROM orders o LEFT JOIN products p ON p.id = o.product_id WHERE o.id = ?");
    $st->execute([$iid]);
    $inv = $st->fetch();
    if (!$inv) die('অর্ডার পাওয়া যায়নি');
    $inv_brand = branding('site_name') ?: get_setting('site_name');
    $inv_logo = branding('logo_url');
    $inv_base = (float)$inv['cod_amount'] + (float)$inv['discount_amount'] - (float)$inv['delivery_charge'];
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <title>ইনভয়েস #<?= $inv['id'] ?></title>
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Hind Siliguri', sans-serif; color: #1e293b; padding: 40px; max-width: 800px; margin: 0 auto; }
            .head { display: flex; justify-content: space-between; align-items: center; border-bottom: 3px solid #059669; padding-bottom: 16px; margin-bottom: 24px; }
            .brand { font-size: 26px; font-weight: 700; color: #059669; }
            .inv-no { text-align: right; font-size: 13px; color: #64748b; }
            .inv-no b { font-size: 20px; color: #1e293b; display: block; }
            .grid { display: flex; gap: 24px; margin-bottom: 24px; }
            .box { flex: 1; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 14px 16px; font-size: 13px; line-height: 1.9; }
            .box h4 { font-size: 11px; text-transform: uppercase; color: #64748b; margin-bottom: 6px; letter-spacing: 1px; }
            table { width: 100%; border-collapse: collapse; font-size: 14px; margin-bottom: 24px; }
            th { background: #059669; color: #fff; text-align: left; padding: 10px 14px; font-size: 12px; }
            td { padding: 10px 14px; border-bottom: 1px solid #e2e8f0; }
            .totals { margin-left: auto; width: 280px; font-size: 14px; }
            .totals div { display: flex; justify-content: space-between; padding: 6px 0; }
            .totals .grand { border-top: 2px solid #1e293b; font-weight: 700; font-size: 17px; padding-top: 10px; }
            .foot { margin-top: 40px; text-align: center; font-size: 12px; color: #94a3b8; border-top: 1px dashed #cbd5e1; padding-top: 14px; }
            .badge { display: inline-block; background: #ecfdf5; color: #059669; font-size: 11px; font-weight: 700; padding: 3px 10px; border-radius: 99px; border: 1px solid #a7f3d0; }
            @media print { body { padding: 10px; } .no-print { display: none; } }
        </style>
    </head>
    <body>
        <div class="no-print" style="text-align:right; margin-bottom:14px;">
            <button onclick="window.print()" style="background:#059669; color:#fff; border:0; padding:10px 24px; border-radius:8px; font-family:inherit; font-weight:700; cursor:pointer;">🖨️ প্রিন্ট করুন</button>
        </div>
        <div class="head">
            <div>
                <?php if ($inv_logo): ?><img src="<?= htmlspecialchars($inv_logo) ?>" style="height:44px; margin-bottom:6px;"><?php endif; ?>
                <div class="brand"><?= htmlspecialchars($inv_brand) ?></div>
            </div>
            <div class="inv-no">ইনভয়েস<b>#<?= $inv['id'] ?></b><?= date('d M Y, h:i A', strtotime($inv['created_at'])) ?></div>
        </div>
        <div class="grid">
            <div class="box">
                <h4>কাস্টমার</h4>
                <b><?= htmlspecialchars($inv['customer_name']) ?></b><br>
                📞 <?= htmlspecialchars($inv['phone']) ?><?= $inv['alternative_phone'] ? ' / ' . htmlspecialchars($inv['alternative_phone']) : '' ?><br>
                📍 <?= nl2br(htmlspecialchars($inv['address'])) ?>
            </div>
            <div class="box">
                <h4>অর্ডার তথ্য</h4>
                স্ট্যাটাস: <span class="badge"><?= htmlspecialchars($inv['status']) ?></span><br>
                <?= $inv['courier_name'] ? 'কুরিয়ার: ' . htmlspecialchars($inv['courier_name']) . '<br>' : '' ?>
                <?= $inv['tracking_code'] ? 'ট্র্যাকিং: <b>' . htmlspecialchars($inv['tracking_code']) . '</b><br>' : '' ?>
                <?= $inv['delivery_zone'] ? 'এলাকা: ' . htmlspecialchars(delivery_zone_bn($inv['delivery_zone'])) : '' ?>
            </div>
        </div>
        <table>
            <tr><th>পণ্য</th><th>ভ্যারিয়েন্ট</th><th style="text-align:right">মূল্য</th></tr>
            <tr>
                <td><b><?= htmlspecialchars($inv['product_title'] ?: 'পণ্য') ?></b></td>
                <td><?= htmlspecialchars(implode(' | ', array_filter([$inv['color_selected'], $inv['size_selected'], $inv['weight_selected']]))) ?: '—' ?></td>
                <td style="text-align:right">৳<?= number_format($inv_base, 2) ?></td>
            </tr>
        </table>
        <div class="totals">
            <div><span>পণ্যের মূল্য</span><span>৳<?= number_format($inv_base, 2) ?></span></div>
            <?php if ((float)$inv['discount_amount'] > 0): ?><div style="color:#be185d"><span>ছাড় (<?= htmlspecialchars($inv['promo_code'] ?? '') ?>)</span><span>−৳<?= number_format($inv['discount_amount'], 2) ?></span></div><?php endif; ?>
            <?php if ((float)$inv['delivery_charge'] > 0): ?><div><span>ডেলিভারি চার্জ</span><span>+৳<?= number_format($inv['delivery_charge'], 2) ?></span></div><?php endif; ?>
            <div class="grand"><span>মোট (ক্যাশ অন ডেলিভারি)</span><span>৳<?= number_format($inv['cod_amount'], 2) ?></span></div>
        </div>
        <div class="foot"><?= htmlspecialchars($inv_brand) ?> — ধন্যবাদ আমাদের সাথে কেনাকাটার জন্য! <?= get_setting('contact_phone') ? '| হটলাইন: ' . htmlspecialchars(get_setting('contact_phone')) : '' ?></div>
    </body>
    </html>
    <?php
    exit;
}


// ডাটাবেজ ব্যাকআপ ডাউনলোড (.sql) — শুধু অ্যাডমিন
if ($action === 'db_backup') {
    require_admin();
    @set_time_limit(300);
    header('Content-Type: application/sql; charset=utf-8');
    header('Content-Disposition: attachment; filename="backup_' . DB_NAME . '_' . date('Ymd_His') . '.sql"');
    echo "-- SunnahTi ERP ব্যাকআপ — " . date('Y-m-d H:i:s') . "\nSET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\n\n";
    $tables = $db->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    foreach ($tables as $tbl) {
        $create = $db->query("SHOW CREATE TABLE `$tbl`")->fetch();
        echo "DROP TABLE IF EXISTS `$tbl`;\n" . $create['Create Table'] . ";\n\n";
        $rows = $db->query("SELECT * FROM `$tbl`");
        while ($r = $rows->fetch(PDO::FETCH_ASSOC)) {
            $vals = array_map(function ($v) use ($db) { return $v === null ? 'NULL' : $db->quote($v); }, array_values($r));
            echo "INSERT INTO `$tbl` (`" . implode('`,`', array_keys($r)) . "`) VALUES (" . implode(',', $vals) . ");\n";
        }
        echo "\n";
    }
    echo "SET FOREIGN_KEY_CHECKS=1;\n";
    exit;
}

// Telegram দৈনিক রিপোর্ট (cron URL অথবা টেস্ট বাটন থেকে)
if ($action === 'telegram_report') {
    $is_cron = isset($_GET['key']) && hash_equals((string)get_setting('cron_secret'), (string)$_GET['key']);
    if (!$is_cron) { require_admin_or_office(); }
    header('Content-Type: application/json; charset=utf-8');
    $bot = trim(get_setting('telegram_bot_token'));
    $chat = trim(get_setting('telegram_chat_id'));
    if ($bot === '' || $chat === '') { echo json_encode(['status' => 'error', 'message' => 'Telegram বট টোকেন/চ্যাট আইডি সেট করুন']); exit; }
    if (!function_exists('curl_init')) { echo json_encode(['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন চালু করুন'], JSON_UNESCAPED_UNICODE); exit; }
    $d = $db->query("SELECT COUNT(*) c, COALESCE(SUM(cod_amount),0) s FROM orders WHERE is_deleted = 0 AND DATE(created_at) = CURDATE()")->fetch();
    $pend = $db->query("SELECT COUNT(*) FROM orders WHERE is_deleted = 0 AND status = 'pending'")->fetchColumn();
    $dlv = $db->query("SELECT COUNT(*) FROM orders WHERE is_deleted = 0 AND status = 'delivered' AND DATE(updated_at) = CURDATE()")->fetchColumn();
    $inc = $db->query("SELECT COUNT(*) FROM incomplete_orders WHERE DATE(updated_at) = CURDATE()")->fetchColumn();
    $msg = "📊 " . (get_setting('site_name') ?: 'SunnahTi') . " — দৈনিক রিপোর্ট (" . date('d M Y') . ")\n\n"
         . "🛒 আজকের অর্ডার: {$d['c']} টি\n💰 আজকের সেলস: ৳" . number_format((float)$d['s']) . "\n"
         . "✅ আজ ডেলিভারড: {$dlv} টি\n📞 কল বাকি (মোট পেন্ডিং): {$pend} টি\n⏳ আজকের ইনকমপ্লিট: {$inc} টি";
    $ch = curl_init("https://api.telegram.org/bot" . $bot . "/sendMessage");
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(['chat_id' => $chat, 'text' => $msg]), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    $ok = !$err && ($j = json_decode($res, true)) && !empty($j['ok']);
    echo json_encode(['status' => $ok ? 'success' : 'error', 'message' => $ok ? 'রিপোর্ট Telegram-এ পাঠানো হয়েছে!' : ('পাঠানো যায়নি: ' . ($err ?: substr((string)$res, 0, 120)))], JSON_UNESCAPED_UNICODE);
    exit;
}


// ইনবক্স: থ্রেড লোড (JSON) + পড়া হয়েছে মার্ক
if ($action === 'inbox_thread') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    $aid = (int)($_GET['account_id'] ?? 0);
    $cid = trim($_GET['contact'] ?? '');
    $tst = $db->prepare("SELECT * FROM inbox_messages WHERE account_id = ? AND contact_ext_id = ? ORDER BY created_at ASC, id ASC LIMIT 200");
    $tst->execute([$aid, $cid]);
    $msgs = $tst->fetchAll();
    $db->prepare("UPDATE inbox_messages SET is_read = 1 WHERE account_id = ? AND contact_ext_id = ? AND direction = 'in'")->execute([$aid, $cid]);
    echo json_encode(['status' => 'success', 'messages' => $msgs], JSON_UNESCAPED_UNICODE);
    exit;
}

// ইনবক্স: রিপ্লাই পাঠানো (WhatsApp Cloud API / Facebook Page)
if ($action === 'inbox_send' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    $aid = (int)($_POST['account_id'] ?? 0);
    $cid = trim($_POST['contact'] ?? '');
    $msg = trim($_POST['message'] ?? '');
    if (!$aid || $cid === '' || $msg === '') { echo json_encode(['status' => 'error', 'message' => 'মেসেজ লিখুন']); exit; }
    $ast = $db->prepare("SELECT * FROM msg_accounts WHERE id = ? AND active = 1");
    $ast->execute([$aid]);
    $acct = $ast->fetch();
    if (!$acct) { echo json_encode(['status' => 'error', 'message' => 'অ্যাকাউন্ট পাওয়া যায়নি']); exit; }
    if (!function_exists('curl_init')) { echo json_encode(['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন চালু করুন (cPanel → Select PHP Version → curl)'], JSON_UNESCAPED_UNICODE); exit; }
    if ($acct['channel'] === 'whatsapp') {
        $url = "https://graph.facebook.com/v19.0/" . rawurlencode($acct['ext_id']) . "/messages";
        $body = ['messaging_product' => 'whatsapp', 'to' => $cid, 'type' => 'text', 'text' => ['body' => $msg]];
    } else {
        $url = "https://graph.facebook.com/v19.0/" . rawurlencode($acct['ext_id']) . "/messages?access_token=" . rawurlencode($acct['access_token']);
        $body = ['recipient' => ['id' => $cid], 'message' => ['text' => $msg], 'messaging_type' => 'RESPONSE'];
    }
    $ch = curl_init($url);
    $headers = ['Content-Type: application/json'];
    if ($acct['channel'] === 'whatsapp') $headers[] = 'Authorization: Bearer ' . $acct['access_token'];
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($body, JSON_UNESCAPED_UNICODE), CURLOPT_HTTPHEADER => $headers, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    $j = json_decode((string)$res, true);
    $ok = !$err && is_array($j) && (isset($j['messages'][0]['id']) || isset($j['message_id']) || isset($j['recipient_id']));
    if ($ok) {
        $ext_id = $j['messages'][0]['id'] ?? ($j['message_id'] ?? null);
        try {
            $db->prepare("INSERT INTO inbox_messages (account_id, contact_ext_id, direction, body, ext_msg_id, is_read) VALUES (?, ?, 'out', ?, ?, 1)")
               ->execute([$aid, $cid, $msg, $ext_id]);
        } catch (Exception $e) {}
        echo json_encode(['status' => 'success', 'message' => 'মেসেজ পাঠানো হয়েছে!'], JSON_UNESCAPED_UNICODE);
    } else {
        $emsg = $err ?: (is_array($j) ? ($j['error']['message'] ?? 'API এরর') : 'API এরর');
        echo json_encode(['status' => 'error', 'message' => 'পাঠানো যায়নি: ' . mb_substr($emsg, 0, 150)], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

// ইনবক্স: ফেসবুক পেজের নতুন মেসেজ টেনে আনা (পোলিং)
if ($action === 'inbox_sync') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    if (!function_exists('curl_init')) { echo json_encode(['status' => 'error', 'message' => 'সার্ভারে PHP cURL এক্সটেনশন চালু করুন'], JSON_UNESCAPED_UNICODE); exit; }
    $fbs = $db->query("SELECT * FROM msg_accounts WHERE channel = 'facebook' AND active = 1")->fetchAll();
    $pulled = 0;
    $errors = [];
    foreach ($fbs as $acct) {
        $url = "https://graph.facebook.com/v19.0/" . rawurlencode($acct['ext_id'])
             . "/conversations?fields=participants,messages.limit(10){message,from,created_time,id}&limit=20&access_token=" . rawurlencode($acct['access_token']);
        $ch = curl_init($url);
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20]);
        $res = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);
        if ($err) { $errors[] = $acct['label'] . ': ' . $err; continue; }
        $j = json_decode((string)$res, true);
        if (!is_array($j) || isset($j['error'])) { $errors[] = $acct['label'] . ': ' . ($j['error']['message'] ?? 'API এরর'); continue; }
        foreach (($j['data'] ?? []) as $conv) {
            // পেজ বাদে অপর পক্ষের নাম
            $others = [];
            foreach (($conv['participants']['data'] ?? []) as $pp) {
                if ((string)($pp['id'] ?? '') !== (string)$acct['ext_id']) $others[$pp['id']] = $pp['name'] ?? '';
            }
            foreach (($conv['messages']['data'] ?? []) as $fm) {
                $from_id = (string)($fm['from']['id'] ?? '');
                $is_out = ($from_id === (string)$acct['ext_id']);
                $contact = $is_out ? (array_key_first($others) ?: '') : $from_id;
                if ($contact === '') continue;
                try {
                    $ins = $db->prepare("INSERT IGNORE INTO inbox_messages (account_id, contact_ext_id, contact_name, direction, body, ext_msg_id, is_read, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $ins->execute([(int)$acct['id'], $contact, $others[$contact] ?? ($fm['from']['name'] ?? null), $is_out ? 'out' : 'in', $fm['message'] ?? '', $fm['id'] ?? null, $is_out ? 1 : 0, isset($fm['created_time']) ? date('Y-m-d H:i:s', strtotime($fm['created_time'])) : date('Y-m-d H:i:s')]);
                    if ($ins->rowCount() > 0) $pulled++;
                } catch (Exception $e) {}
            }
        }
    }
    echo json_encode(['status' => 'success', 'pulled' => $pulled, 'errors' => $errors, 'message' => $pulled . ' টি নতুন মেসেজ আনা হয়েছে' . (empty($errors) ? '' : ' (কিছু এরর: ' . implode('; ', array_slice($errors, 0, 2)) . ')')], JSON_UNESCAPED_UNICODE);
    exit;
}

// কাস্টমার হিস্টোরি থেকে অর্ডার ডিলিট / রিস্টোর
if ($action === 'ajax_toggle_order_delete') {
    require_admin_or_office();
    header('Content-Type: application/json; charset=utf-8');
    $oid = (int)($_POST['id'] ?? 0);
    $mode = $_POST['mode'] ?? '';
    if (!$oid || !in_array($mode, ['delete', 'restore'])) {
        echo json_encode(['status' => 'error', 'message' => 'ভুল রিকোয়েস্ট']); exit;
    }
    try {
        $db->prepare("UPDATE orders SET is_deleted = ?, updated_by = ?, updated_at = NOW() WHERE id = ?")
           ->execute([$mode === 'delete' ? 1 : 0, $_SESSION['username'] ?? '', $oid]);
        echo json_encode(['status' => 'success', 'message' => $mode === 'delete' ? 'অর্ডারটি ডিলিট (রিসাইকেল বিনে) করা হয়েছে' : 'অর্ডারটি রিস্টোর করা হয়েছে'], JSON_UNESCAPED_UNICODE);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'কাজটি সম্পন্ন করা যায়নি']);
    }
    exit;
}

// কুরিয়ার স্ট্যাটাস অটো-সিঙ্ক (১ মিনিট পর পর AJAX থেকে কল হয়)
if ($action === 'courier_sync') {
    require_login();
    header('Content-Type: application/json');
    if (get_user_role() === 'agent') {
        // কলিং এজেন্টের জন্য কুরিয়ার অটো সিঙ্ক বন্ধ — API কলও হবে না
        echo json_encode(['status' => 'success', 'updated' => [], 'skipped' => 'agent']);
        exit;
    }
    // বুক হওয়া, এখনো ফাইনাল না হওয়া অর্ডারগুলো — সবচেয়ে পুরোনো সিঙ্কেরগুলো আগে (প্রতি রানে সর্বোচ্চ ১৫টা, API চাপ কমাতে)
    $st = $db->query("SELECT id, consignment_id, tracking_code FROM orders
                      WHERE is_deleted = 0 AND consignment_id IS NOT NULL AND consignment_id != ''
                        AND (courier_status IS NULL OR courier_status NOT IN ('delivered', 'cancelled'))
                      ORDER BY courier_synced_at IS NULL DESC, courier_synced_at ASC
                      LIMIT 15");
    $rows = $st->fetchAll();
    $updated = [];
    foreach ($rows as $r) {
        $res = IntegrationEngine::checkSteadfastStatus($r['consignment_id']);
        $up = $db->prepare("UPDATE orders SET courier_status = ?, courier_note = ?, courier_synced_at = NOW() WHERE id = ?");
        if (isset($res['status']) && (int)$res['status'] === 200) {
            $ds = trim((string)($res['delivery_status'] ?? 'unknown'));
            // কুরিয়ারের লাস্ট নোট/মেসেজ — API যা দেয় তা সংরক্ষণ
            $note_bits = [];
            foreach (['note', 'last_note', 'message', 'comment', 'remarks'] as $nk) {
                if (!empty($res[$nk]) && is_string($res[$nk]) && strtolower($res[$nk]) !== 'ok') $note_bits[] = trim($res[$nk]);
            }
            if (isset($res['tracking']) && is_array($res['tracking'])) {
                $last_t = end($res['tracking']);
                if (is_array($last_t) && !empty($last_t['note'])) $note_bits[] = trim($last_t['note']);
            }
            $cnote = trim(implode(' | ', array_unique($note_bits)));
            // API-তে নোট না এলে পাবলিক ট্র্যাকিং পেজ থেকে ডেলিভারিম্যানের লেটেস্ট নোট আনার চেষ্টা
            if ($cnote === '' && !empty($r['tracking_code'])) {
                try { $cnote = IntegrationEngine::fetchSteadfastPublicNote($r['tracking_code']); } catch (Exception $e) {}
            }
            $up->execute([$ds, $cnote !== '' ? $cnote : null, (int)$r['id']]);
            $info = courier_status_info($ds);
            $updated[] = ['id' => (int)$r['id'], 'courier_status' => $ds, 'label' => $info[0], 'note' => $cnote];
        } else {
            // এরর হলেও synced_at আপডেট, যেন একই অর্ডারে বারবার আটকে না থাকে
            $db->prepare("UPDATE orders SET courier_synced_at = NOW() WHERE id = ?")->execute([(int)$r['id']]);
        }
    }
    echo json_encode(['status' => 'success', 'checked' => count($rows), 'updated' => $updated], JSON_UNESCAPED_UNICODE);
    exit;
}

// Courier Booking Action Handler
// ম্যানুয়াল কুরিয়ার বুকিং সেভ (Pathao / RedX — তাদের প্যানেলে বুক করে ট্র্যাকিং আইডি পেস্ট)
if ($action === 'manual_courier' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    $oid = (int)($_POST['id'] ?? 0);
    $cname = trim($_POST['courier_name'] ?? '');
    $trk = trim($_POST['tracking'] ?? '');
    if (!$oid || !in_array($cname, ['Pathao', 'RedX', 'Other']) || $trk === '') {
        echo json_encode(['status' => 'error', 'message' => 'কুরিয়ার ও ট্র্যাকিং আইডি দিন']); exit;
    }
    $stc = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stc->execute([$oid]);
    $mo = $stc->fetch();
    if (!$mo) { echo json_encode(['status' => 'error', 'message' => 'অর্ডার পাওয়া যায়নি']); exit; }
    $db->prepare("UPDATE orders SET status = 'booked', courier_name = ?, tracking_code = ?, consignment_id = NULL, booked_by = ?, booked_at = NOW(), updated_by = ?, updated_at = NOW() WHERE id = ?")
       ->execute([$cname, $trk, $_SESSION['username'], $_SESSION['username'], $oid]);
    if (get_setting('sms_on_courier') === '1') {
        try { send_sms($mo['phone'], sms_render(get_setting('sms_tpl_courier'), ['customer_name' => $mo['customer_name'], 'id' => $oid, 'cod_amount' => $mo['cod_amount'], 'tracking_code' => $trk])); } catch (Exception $e) {}
    }
    echo json_encode(['status' => 'success', 'message' => $cname . '-এ বুকড হিসেবে সেভ হয়েছে!'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'book_courier' && isset($_GET['id'])) {
    header('Content-Type: application/json');
    $id = (int)$_GET['id'];

    // ==== ডাবল-বুকিং গার্ড: অ্যাটমিকভাবে অর্ডার "দাবি" করা ====
    // শুধু তখনই বুক করা যাবে যখন এটি এখনো বুক হয়নি (tracking_code খালি ও booking_lock খালি)।
    // এই একটি UPDATE-ই রেস কন্ডিশন ঠেকায় — দুটি রিকোয়েস্ট একসাথে এলেও মাত্র একটি লক পাবে।
    $lock_token = bin2hex(random_bytes(8));
    $claim = $db->prepare("UPDATE orders SET booking_lock = ? WHERE id = ? AND (tracking_code IS NULL OR tracking_code = '') AND (booking_lock IS NULL OR booking_lock = '')");
    $claim->execute([$lock_token, $id]);
    if ($claim->rowCount() === 0) {
        // হয় ইতিমধ্যে বুকড, নয়তো আরেকটি রিকোয়েস্ট এইমাত্র লক নিয়েছে
        $chk = $db->prepare("SELECT tracking_code, consignment_id FROM orders WHERE id = ?");
        $chk->execute([$id]);
        $ex = $chk->fetch();
        if ($ex && !empty($ex['tracking_code'])) {
            echo json_encode(['status' => 'already', 'message' => 'এই অর্ডারটি ইতিমধ্যে কুরিয়ারে বুক করা হয়েছে।', 'consignment_id' => $ex['consignment_id'] ?? '', 'tracking_code' => $ex['tracking_code']]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'অর্ডারটি এই মুহূর্তে বুক হচ্ছে — অনুগ্রহ করে অপেক্ষা করুন।']);
        }
        exit;
    }

    $stmt = $db->prepare("SELECT o.*, p.title as product_title FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.id = ?");
    $stmt->execute([$id]);
    $order = $stmt->fetch();
    if (!$order) {
        $db->prepare("UPDATE orders SET booking_lock = NULL WHERE id = ?")->execute([$id]);
        echo json_encode(['status' => 'error', 'message' => 'Order not found']);
        exit;
    }
    $res = IntegrationEngine::createSteadfastOrder($order);
    if (isset($res['status']) && $res['status'] === 200) {
        $c = $res['consignment'] ?? $res['order'] ?? [];
        $tracking = $c['tracking_code'] ?? '';
        $consignment = $c['consignment_id'] ?? '';
        // লক ছেড়ে দিয়ে (booking_lock = NULL) বুকিং ফাইনাল করা
        $up = $db->prepare("UPDATE orders SET status = 'booked', courier_name = 'Steadfast', tracking_code = ?, consignment_id = ?, booked_by = ?, booked_at = NOW(), updated_by = ?, updated_at = NOW(), booking_lock = NULL WHERE id = ?");
        $up->execute([$tracking, $consignment, $_SESSION['username'], $_SESSION['username'], $id]);
        if (get_setting('sms_on_courier') === '1') {
            try { send_sms($order['phone'], sms_render(get_setting('sms_tpl_courier'), ['customer_name' => $order['customer_name'], 'id' => $order['id'], 'cod_amount' => $order['cod_amount'], 'tracking_code' => $tracking])); } catch (Exception $e) {}
        }
        echo json_encode(['status' => 'success', 'message' => 'Courier Booking Successful', 'consignment_id' => $consignment, 'tracking_code' => $tracking]);
    } else {
        // বুকিং ব্যর্থ — লক ছেড়ে দাও যাতে পরে আবার চেষ্টা করা যায়
        $db->prepare("UPDATE orders SET booking_lock = NULL WHERE id = ?")->execute([$id]);
        echo json_encode(['status' => 'error', 'message' => $res['message'] ?? 'Booking Failed']);
    }
    exit;
}

// Thermal Printer Multi-Invoice Dispatcher
if ($action === 'invoice' && isset($_GET['ids'])) {
    $ids = array_filter(array_map('intval', explode(',', $_GET['ids'])));
    if (empty($ids)) die('No orders selected');
    $type = $_GET['type'] ?? '80mm';
    $placeholders = implode(',', array_fill(0, count($ids), '?'));
    $stmt = $db->prepare("SELECT o.*, p.title as product_title FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.id IN ($placeholders)");
    $stmt->execute($ids);
    $orders = $stmt->fetchAll();
    render_invoice_thermal($orders, $type);
    exit;
}

// Bulk Actions Handler
if ($action === 'bulk_action' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $bulk_op = $_POST['bulk_op'] ?? '';
    $order_ids = $_POST['order_ids'] ?? [];
    if (!empty($order_ids)) {
        $order_ids = array_filter(array_map('intval', $order_ids));
        $placeholders = implode(',', array_fill(0, count($order_ids), '?'));
        if ($bulk_op === 'delete') {
            $stmt = $db->prepare("UPDATE orders SET is_deleted = 1, updated_by = ?, updated_at = NOW() WHERE id IN ($placeholders)");
            $stmt->execute(array_merge([$_SESSION['username']], $order_ids));
        } elseif ($bulk_op === 'restore') {
            $stmt = $db->prepare("UPDATE orders SET is_deleted = 0, updated_by = ?, updated_at = NOW() WHERE id IN ($placeholders)");
            $stmt->execute(array_merge([$_SESSION['username']], $order_ids));
        } elseif ($bulk_op === 'force_delete') {
            $stmt = $db->prepare("DELETE FROM orders WHERE id IN ($placeholders)");
            $stmt->execute($order_ids);
        } elseif ($bulk_op === 'book_steadfast') {
            // ==== বাল্ক ডাবল-বুকিং গার্ড ====
            // প্রতিটি অর্ডার প্রসেসের আগে অ্যাটমিকভাবে "দাবি" করা হয়। ইতিমধ্যে বুকড বা
            // অন্য প্রসেস লক করে রাখা অর্ডার এই লুপে বাদ পড়ে যায় — তাই একই পার্সেল দুবার যায় না।
            $bulk_booked = 0; $bulk_skipped = 0; $bulk_failed = 0;
            foreach ($order_ids as $oid) {
                $lock_token = bin2hex(random_bytes(8));
                $claim = $db->prepare("UPDATE orders SET booking_lock = ? WHERE id = ? AND (tracking_code IS NULL OR tracking_code = '') AND (booking_lock IS NULL OR booking_lock = '')");
                $claim->execute([$lock_token, $oid]);
                if ($claim->rowCount() === 0) { $bulk_skipped++; continue; } // ইতিমধ্যে বুকড/লকড — বাদ

                $stmt = $db->prepare("SELECT o.*, p.title as product_title FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.id = ?");
                $stmt->execute([$oid]);
                $order = $stmt->fetch();
                if (!$order) { $db->prepare("UPDATE orders SET booking_lock = NULL WHERE id = ?")->execute([$oid]); continue; }

                $res = IntegrationEngine::createSteadfastOrder($order);
                if (isset($res['status']) && $res['status'] === 200) {
                    $c = $res['consignment'] ?? $res['order'] ?? [];
                    $tracking = $c['tracking_code'] ?? '';
                    $consignment = $c['consignment_id'] ?? '';
                    $up = $db->prepare("UPDATE orders SET status = 'booked', courier_name = 'Steadfast', tracking_code = ?, consignment_id = ?, booked_by = ?, booked_at = NOW(), updated_by = ?, updated_at = NOW(), booking_lock = NULL WHERE id = ?");
                    $up->execute([$tracking, $consignment, $_SESSION['username'], $_SESSION['username'], $oid]);
                    $bulk_booked++;
                    if (get_setting('sms_on_courier') === '1') {
                        try { send_sms($order['phone'], sms_render(get_setting('sms_tpl_courier'), ['customer_name' => $order['customer_name'], 'id' => $order['id'], 'cod_amount' => $order['cod_amount'], 'tracking_code' => $tracking])); } catch (Exception $e) {}
                    }
                } else {
                    // ব্যর্থ হলে লক ছেড়ে দাও — পরে আবার চেষ্টা করা যাবে
                    $db->prepare("UPDATE orders SET booking_lock = NULL WHERE id = ?")->execute([$oid]);
                    $bulk_failed++;
                }
            }
            $_SESSION['bulk_book_result'] = ['booked' => $bulk_booked, 'skipped' => $bulk_skipped, 'failed' => $bulk_failed];
            header("Location: ?action=dashboard&bulk_booked={$bulk_booked}&bulk_skipped={$bulk_skipped}&bulk_failed={$bulk_failed}");
            exit;
        }
    }
    header("Location: ?action=dashboard");
    exit;
}

// জোন চেঞ্জ লিস্টে অর্ডার যোগ/বাদ (মূল অর্ডার লিস্টের বাটন থেকে) — এজেন্ট নয়
if ($action === 'toggle_zone_flag' && isset($_GET['id'])) {
    header('Content-Type: application/json; charset=utf-8');
    if (get_user_role() === 'agent') {
        echo json_encode(['status' => 'error', 'message' => 'কলিং এজেন্ট এই সুবিধা ব্যবহার করতে পারবেন না।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $id = (int)$_GET['id'];
    $cur = $db->prepare("SELECT zone_change_flag FROM orders WHERE id = ?");
    $cur->execute([$id]);
    $row = $cur->fetch();
    if (!$row) { echo json_encode(['status' => 'error', 'message' => 'অর্ডার পাওয়া যায়নি']); exit; }
    $new = $row['zone_change_flag'] ? 0 : 1;
    $db->prepare("UPDATE orders SET zone_change_flag = ? WHERE id = ?")->execute([$new, $id]);
    echo json_encode([
        'status' => 'success',
        'flagged' => $new,
        'message' => $new ? 'অর্ডারটি জোন চেঞ্জ লিস্টে যোগ হয়েছে!' : 'অর্ডারটি জোন চেঞ্জ লিস্ট থেকে সরানো হয়েছে।'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'ajax_update_status' && isset($_GET['id']) && isset($_GET['status'])) {
    header('Content-Type: application/json');
    $id = (int)$_GET['id'];
    $status = trim($_GET['status']);

    if (!array_key_exists($status, $status_map)) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid Status']);
        exit;
    }

    if (get_user_role() === 'agent' && $status === 'booked') {
        echo json_encode(['status' => 'error', 'message' => 'কলিং এজেন্ট কুরিয়ার বুকিং সুবিধা পরিবর্তন করতে পারবেন না।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $stmt_old = $db->prepare("SELECT status, product_id FROM orders WHERE id = ?");
    $stmt_old->execute([$id]);
    $old_order = $stmt_old->fetch();

    if ($old_order) {
        if (($status === 'cancelled' || $status === 'did_not_order') && ($old_order['status'] !== 'cancelled' && $old_order['status'] !== 'did_not_order')) {
            $up_stock = $db->prepare("UPDATE products SET stock = stock + 1 WHERE id = ?");
            $up_stock->execute([$old_order['product_id']]);
        }
        elseif (($old_order['status'] === 'cancelled' || $old_order['status'] === 'did_not_order') && ($status !== 'cancelled' && $status !== 'did_not_order')) {
            $up_stock = $db->prepare("UPDATE products SET stock = GREATEST(0, stock - 1) WHERE id = ?");
            $up_stock->execute([$old_order['product_id']]);
        }
    }

    $stmt = $db->prepare("UPDATE orders SET status = ?, updated_by = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$status, $_SESSION['username'], $id]);

    echo json_encode(['status' => 'success', 'message' => 'স্ট্যাটাস রিয়েল-টাইমে আপডেট করা হয়েছে!'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'restore_order' && isset($_GET['id'])) {
    require_admin();
    $order_id = (int)$_GET['id'];
    $stmt = $db->prepare("UPDATE orders SET is_deleted = 0, updated_by = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$_SESSION['username'], $order_id]);
    header("Location: ?action=dashboard&status_filter=deleted&msg=restored");
    exit;
}

if ($action === 'delete_order' && isset($_GET['id'])) {
    require_admin();
    $order_id = (int)$_GET['id'];
    $stmt = $db->prepare("UPDATE orders SET is_deleted = 1, updated_by = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$_SESSION['username'], $order_id]);
    header("Location: ?action=dashboard&msg=deleted");
    exit;
}

if ($action === 'force_delete_order' && isset($_GET['id'])) {
    require_admin();
    $order_id = (int)$_GET['id'];
    $stmt = $db->prepare("DELETE FROM orders WHERE id = ?");
    $stmt->execute([$order_id]);
    header("Location: ?action=dashboard&status_filter=deleted&msg=force_deleted");
    exit;
}

if ($action === 'restock_product') {
    require_admin();
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $p_id = (int)$_POST['product_id'];
        $qty = (int)$_POST['qty'];
        if ($p_id > 0 && $qty > 0) {
            $stmt = $db->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
            $stmt->execute([$qty, $p_id]);
            header("Location: ?action=products&msg=restocked");
            exit;
        }
    }
    header("Location: ?action=products");
    exit;
}

// স্টক অডিট: সঠিক স্টক সংখ্যা সরাসরি সেট করা (পুরোনো ডাবল-কমা বাগ ঠিক করতে)
if ($action === 'set_stock') {
    require_admin();
    header('Content-Type: application/json; charset=utf-8');
    $p_id = (int)($_POST['product_id'] ?? 0);
    $new_stock = (int)bnToEnNumber($_POST['new_stock'] ?? '');
    if ($p_id > 0 && $new_stock >= 0) {
        $db->prepare("UPDATE products SET stock = ? WHERE id = ?")->execute([$new_stock, $p_id]);
        echo json_encode(['status' => 'success', 'message' => 'স্টক আপডেট হয়েছে!', 'stock' => $new_stock]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'সঠিক সংখ্যা দিন']);
    }
    exit;
}

// -------------------------------------------------------------
// Feature 2: MEDIA FILE MANAGER (Upload, Crop, Delete, Auto Link)
// -------------------------------------------------------------

if ($action === 'media') {
    require_admin_or_office();
    render_dashboard_header("মিডিয়া ফাইল ম্যানেজার");
    render_media_panel();
    render_dashboard_footer();
    exit;
}

if ($action === 'media_upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_admin_or_office();
    header('Content-Type: application/json');

    if (!is_dir(MEDIA_DIR)) {
        @mkdir(MEDIA_DIR, 0755, true);
    }
    if (is_dir(MEDIA_DIR) && !is_writable(MEDIA_DIR)) {
        @chmod(MEDIA_DIR, 0755);
        if (!is_writable(MEDIA_DIR)) @chmod(MEDIA_DIR, 0775);
    }
    if (!is_dir(MEDIA_DIR) || !is_writable(MEDIA_DIR)) {
        echo json_encode(['status' => 'error', 'message' => 'uploads/media ফোল্ডার তৈরি বা লেখা যাচ্ছে না। cPanel থেকে ফোল্ডার পারমিশন (755) চেক করুন।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (empty($_FILES['media_file'])) {
        // ফাইল POST-ই হয়নি — সাধারণত post_max_size ছাড়িয়ে গেলে এমন হয়
        $pm = ini_get('post_max_size');
        echo json_encode(['status' => 'error', 'message' => "ফাইলটি সার্ভারে পৌঁছায়নি। সম্ভবত ফাইল সাইজ সার্ভারের post_max_size ($pm) লিমিটের চেয়ে বড়। cPanel → MultiPHP INI Editor থেকে লিমিট বাড়ান।"], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($_FILES['media_file']['error'] !== UPLOAD_ERR_OK) {
        $um = ini_get('upload_max_filesize');
        $err_map = [
            UPLOAD_ERR_INI_SIZE   => "ফাইলটি সার্ভারের upload_max_filesize ($um) লিমিটের চেয়ে বড়! cPanel → MultiPHP INI Editor → upload_max_filesize বাড়িয়ে 20M করুন।",
            UPLOAD_ERR_FORM_SIZE  => 'ফাইলটি ফর্মের সর্বোচ্চ সাইজ লিমিট ছাড়িয়ে গেছে।',
            UPLOAD_ERR_PARTIAL    => 'ফাইলটি আংশিক আপলোড হয়েছে — ইন্টারনেট সংযোগ চেক করে আবার চেষ্টা করুন।',
            UPLOAD_ERR_NO_FILE    => 'কোনো ফাইল সিলেক্ট করা হয়নি।',
            UPLOAD_ERR_NO_TMP_DIR => 'সার্ভারে টেম্প ফোল্ডার নেই — হোস্টিং প্রোভাইডারকে জানান।',
            UPLOAD_ERR_CANT_WRITE => 'সার্ভার ডিস্কে লেখা যাচ্ছে না — ডিস্ক স্পেস/পারমিশন চেক করুন।',
            UPLOAD_ERR_EXTENSION  => 'একটি PHP এক্সটেনশন আপলোড আটকে দিয়েছে (ModSecurity হতে পারে)।',
        ];
        $ec = $_FILES['media_file']['error'];
        echo json_encode(['status' => 'error', 'message' => $err_map[$ec] ?? ('ফাইল আপলোড ব্যর্থ হয়েছে (কোড: ' . $ec . ')।')], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $file = $_FILES['media_file'];
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if ($ext === '' && strpos($file['type'], 'image/') === 0) {
        $ext = str_replace('image/', '', $file['type']);
        if ($ext === 'jpeg') $ext = 'jpg';
    }
    if (!in_array($ext, $allowed)) {
        echo json_encode(['status' => 'error', 'message' => 'শুধুমাত্র ছবি আপলোড করা যাবে (jpg, png, gif, webp)।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    // Verify it is a real image
    if (@getimagesize($file['tmp_name']) === false) {
        echo json_encode(['status' => 'error', 'message' => 'ফাইলটি সঠিক ইমেজ ফাইল নয়।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($file['size'] > 10 * 1024 * 1024) {
        echo json_encode(['status' => 'error', 'message' => 'সর্বোচ্চ ১০ MB সাইজের ইমেজ আপলোড করা যাবে।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $prefix = isset($_POST['cropped']) && $_POST['cropped'] === '1' ? 'crop_' : 'img_';
    $newname = $prefix . date('Ymd_His') . '_' . substr(md5(uniqid('', true)), 0, 8) . '.' . $ext;
    $target = MEDIA_DIR . '/' . $newname;

    if (!move_uploaded_file($file['tmp_name'], $target)) {
        echo json_encode(['status' => 'error', 'message' => 'ফাইল সেভ করা যায়নি। ফোল্ডার পারমিশন চেক করুন।'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $url = base_url() . '/' . MEDIA_URL_PATH . '/' . $newname;
    $ins = $db->prepare("INSERT INTO media_files (filename, filepath, url, filesize) VALUES (?, ?, ?, ?)");
    $ins->execute([$newname, MEDIA_URL_PATH . '/' . $newname, $url, (int)$file['size']]);

    echo json_encode(['status' => 'success', 'message' => 'ইমেজ সফলভাবে আপলোড হয়েছে!', 'id' => $db->lastInsertId(), 'url' => $url], JSON_UNESCAPED_UNICODE);
    exit;
}

// Load 20 images per page (Load More)
if ($action === 'media_list') {
    require_admin_or_office();
    header('Content-Type: application/json');
    $offset = max(0, (int)($_GET['offset'] ?? 0));
    $limit = 20;
    $total = (int)$db->query("SELECT COUNT(*) FROM media_files")->fetchColumn();
    $stmt = $db->prepare("SELECT * FROM media_files ORDER BY id DESC LIMIT $limit OFFSET $offset");
    $stmt->execute();
    $rows = $stmt->fetchAll();
    // প্রিভিউর জন্য রিলেটিভ পাথ (মিক্সড-কনটেন্ট/পুরোনো হোস্ট সমস্যা এড়াতে) + কপির জন্য ফ্রেশ ফুল URL
    $bu = rtrim(base_url(), '/');
    foreach ($rows as &$mr) {
        $mr['file_name'] = $mr['filename'];
        $mr['rel_url'] = $mr['filepath']; // যেমন uploads/media/img_x.png (ড্যাশবোর্ডের সাপেক্ষে)
        $mr['file_url'] = $bu . '/' . ltrim($mr['filepath'], '/');
    }
    unset($mr);
    echo json_encode(['status' => 'success', 'total' => $total, 'offset' => $offset, 'files' => $rows], JSON_UNESCAPED_UNICODE);
    exit;
}

// Permanent delete of a media file
if ($action === 'media_delete' && isset($_GET['id'])) {
    require_admin_or_office();
    header('Content-Type: application/json');
    $id = (int)$_GET['id'];
    $stmt = $db->prepare("SELECT * FROM media_files WHERE id = ?");
    $stmt->execute([$id]);
    $file = $stmt->fetch();
    if (!$file) {
        echo json_encode(['status' => 'error', 'message' => 'ফাইলটি খুঁজে পাওয়া যায়নি।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $full = __DIR__ . '/' . $file['filepath'];
    if (is_file($full)) {
        @unlink($full);
    }
    $db->prepare("DELETE FROM media_files WHERE id = ?")->execute([$id]);
    echo json_encode(['status' => 'success', 'message' => 'ইমেজটি স্থায়ীভাবে ডিলিট করা হয়েছে!'], JSON_UNESCAPED_UNICODE);
    exit;
}

// -------------------------------------------------------------
// Feature 9: FRAUD DETECTION TAB (Block by Phone / IP)
// -------------------------------------------------------------




// ইউনিফাইড ইনবক্স: একাধিক WhatsApp Business + Facebook Page — সব মেসেজ এক জায়গায়
if ($action === 'inbox') {
    require_login();

    // অ্যাকাউন্ট CRUD (PRG)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_msg_account'])) {
        $ma_ch = ($_POST['ma_channel'] ?? '') === 'facebook' ? 'facebook' : 'whatsapp';
        $ma_label = trim($_POST['ma_label'] ?? '');
        $ma_ext = trim($_POST['ma_ext_id'] ?? '');
        $ma_token = trim($_POST['ma_token'] ?? '');
        if ($ma_label !== '' && $ma_ext !== '' && $ma_token !== '') {
            $db->prepare("INSERT INTO msg_accounts (channel, label, ext_id, access_token) VALUES (?, ?, ?, ?)")
               ->execute([$ma_ch, $ma_label, $ma_ext, $ma_token]);
            header("Location: ?action=inbox&imsg=added");
        } else {
            header("Location: ?action=inbox&imsg=invalid");
        }
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_msg_account'])) {
        $db->prepare("UPDATE msg_accounts SET active = 1 - active WHERE id = ?")->execute([(int)$_POST['ma_id']]);
        header("Location: ?action=inbox&imsg=toggled"); exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_msg_account'])) {
        $mid = (int)$_POST['ma_id'];
        $db->prepare("DELETE FROM msg_accounts WHERE id = ?")->execute([$mid]);
        $db->prepare("DELETE FROM inbox_messages WHERE account_id = ?")->execute([$mid]);
        header("Location: ?action=inbox&imsg=deleted"); exit;
    }

    $msg_accounts = $db->query("SELECT * FROM msg_accounts ORDER BY id")->fetchAll();
    // কনভার্সেশন লিস্ট: অ্যাকাউন্ট+কন্টাক্ট গ্রুপে, সর্বশেষ মেসেজ + আনরিড কাউন্ট
    $convs = $db->query("
        SELECT m.account_id, m.contact_ext_id,
               MAX(m.created_at) AS last_at,
               SUM(CASE WHEN m.direction = 'in' AND m.is_read = 0 THEN 1 ELSE 0 END) AS unread,
               (SELECT body FROM inbox_messages x WHERE x.account_id = m.account_id AND x.contact_ext_id = m.contact_ext_id ORDER BY x.created_at DESC, x.id DESC LIMIT 1) AS last_body,
               (SELECT contact_name FROM inbox_messages x2 WHERE x2.account_id = m.account_id AND x2.contact_ext_id = m.contact_ext_id AND x2.contact_name IS NOT NULL ORDER BY x2.id DESC LIMIT 1) AS cname
        FROM inbox_messages m
        GROUP BY m.account_id, m.contact_ext_id
        ORDER BY last_at DESC
        LIMIT 100
    ")->fetchAll();
    $acct_map = [];
    foreach ($msg_accounts as $ma) $acct_map[$ma['id']] = $ma;
    $wa_webhook_url = rtrim(base_url(), '/') . '/?action=wa_webhook';

    render_dashboard_header('ইনবক্স');
    ?>
    <div class="space-y-6 font-semibold">
        <?php if (isset($_GET['imsg'])): $im = ['added' => ['s', 'অ্যাকাউন্ট যোগ হয়েছে!'], 'deleted' => ['s', 'অ্যাকাউন্ট ও তার মেসেজ ডিলিট হয়েছে!'], 'toggled' => ['s', 'অ্যাকাউন্ট চালু/বন্ধ করা হয়েছে!'], 'invalid' => ['e', 'সব ঘর পূরণ করুন!']][$_GET['imsg']] ?? null; if ($im): ?>
            <div class="<?= $im[0] === 'e' ? 'bg-rose-500/10 border-rose-500 text-rose-400' : 'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= $im[1] ?></div>
        <?php endif; endif; ?>

        <!-- অ্যাকাউন্ট ম্যানেজার -->
        <details class="bg-slate-800 rounded-2xl border border-slate-700 shadow-md" <?= empty($msg_accounts) ? 'open' : '' ?>>
            <summary class="p-5 cursor-pointer text-white font-bold flex items-center gap-2 select-none">
                <i class="fa-solid fa-gears text-amber-400"></i> মেসেজ অ্যাকাউন্ট ম্যানেজার (<?= count($msg_accounts) ?> টি) — WhatsApp Business / Facebook Page যোগ করুন
            </summary>
            <div class="px-5 pb-5 space-y-4">
                <form action="?action=inbox" method="POST" class="grid grid-cols-1 md:grid-cols-5 gap-3 items-end">
                    <input type="hidden" name="add_msg_account" value="1">
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">চ্যানেল</label>
                        <select name="ma_channel" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                            <option value="whatsapp">WhatsApp Business (Cloud API)</option>
                            <option value="facebook">Facebook Page</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">নাম / লেবেল</label>
                        <input type="text" name="ma_label" required placeholder="যেমন: মেইন WhatsApp" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">Phone Number ID / Page ID</label>
                        <input type="text" name="ma_ext_id" required placeholder="1234567890" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">Access Token</label>
                        <input type="text" name="ma_token" required placeholder="EAAG..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    </div>
                    <button type="submit" class="bg-sky-600 hover:bg-sky-500 text-white text-sm font-bold px-4 py-2.5 rounded-xl"><i class="fa-solid fa-plus"></i> যোগ করুন</button>
                </form>
                <?php if (!empty($msg_accounts)): ?>
                <div class="flex flex-wrap gap-2">
                    <?php foreach ($msg_accounts as $ma): ?>
                    <div class="flex items-center gap-2 bg-slate-900/60 border border-slate-700 rounded-xl px-3 py-2 text-xs">
                        <i class="fa-brands fa-<?= $ma['channel'] === 'whatsapp' ? 'whatsapp text-emerald-400' : 'facebook text-blue-400' ?>"></i>
                        <span class="font-bold text-white"><?= htmlspecialchars($ma['label']) ?></span>
                        <span class="font-mono text-slate-500"><?= htmlspecialchars($ma['ext_id']) ?></span>
                        <form action="?action=inbox" method="POST" class="inline"><input type="hidden" name="toggle_msg_account" value="1"><input type="hidden" name="ma_id" value="<?= (int)$ma['id'] ?>"><button class="<?= $ma['active'] ? 'text-emerald-400' : 'text-slate-500' ?> font-bold" title="চালু/বন্ধ"><?= $ma['active'] ? 'চালু ✓' : 'বন্ধ' ?></button></form>
                        <form action="?action=inbox" method="POST" class="inline" onsubmit="return confirm('অ্যাকাউন্ট ও তার সব মেসেজ ডিলিট হবে?');"><input type="hidden" name="delete_msg_account" value="1"><input type="hidden" name="ma_id" value="<?= (int)$ma['id'] ?>"><button class="text-rose-400 hover:text-rose-300"><i class="fa-solid fa-trash"></i></button></form>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
                <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 text-[11px] text-slate-400 space-y-1.5">
                    <p class="text-amber-400 font-bold">⚙️ সেটআপ গাইড:</p>
                    <p><b class="text-emerald-400">WhatsApp:</b> Meta for Developers → আপনার অ্যাপ → WhatsApp → Phone Number ID + Permanent Token নিন। Webhook Callback URL: <code class="text-cyan-400 select-all"><?= htmlspecialchars($wa_webhook_url) ?></code> | Verify Token: <code class="text-cyan-400 select-all"><?= htmlspecialchars(get_setting('cron_secret')) ?></code> — messages ফিল্ড সাবস্ক্রাইব করুন। এটা শুধু <b>WhatsApp Cloud API</b>-তে কাজ করে (সাধারণ WhatsApp অ্যাপে নয়)।</p>
                    <p><b class="text-blue-400">Facebook Page:</b> Page ID + Page Access Token (pages_messaging পারমিশনসহ) দিন — "সিঙ্ক" বাটনে নতুন মেসেজ আসবে।</p>
                </div>
            </div>
        </details>

        <!-- দুই-প্যান ইনবক্স -->
        <div class="bg-slate-800 rounded-2xl border border-slate-700 shadow-md overflow-hidden">
            <div class="p-4 border-b border-slate-700 flex items-center justify-between flex-wrap gap-2">
                <h3 class="text-lg font-bold text-white flex items-center gap-2"><i class="fa-solid fa-comments text-sky-400"></i> সব মেসেজ এক জায়গায়</h3>
                <button type="button" onclick="inboxSync(this)" class="bg-blue-600 hover:bg-blue-500 text-white text-xs font-bold px-4 py-2 rounded-lg"><i class="fa-brands fa-facebook"></i> ফেসবুক পেজ সিঙ্ক করুন</button>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-3" style="min-height: 480px;">
                <!-- বাম: কনভার্সেশন লিস্ট -->
                <div class="border-r border-slate-700 max-h-[70vh] overflow-y-auto">
                    <?php if (empty($convs)): ?>
                        <p class="p-6 text-center text-slate-500 text-sm">কোনো মেসেজ নেই।<br><span class="text-[10px]">WhatsApp ওয়েবহুক সেট করলে বা ফেসবুক সিঙ্ক করলে মেসেজ আসবে।</span></p>
                    <?php else: foreach ($convs as $cv): $cacct = $acct_map[$cv['account_id']] ?? null; ?>
                    <button type="button" onclick="openThread(<?= (int)$cv['account_id'] ?>, '<?= htmlspecialchars($cv['contact_ext_id'], ENT_QUOTES) ?>', '<?= htmlspecialchars($cv['cname'] ?: $cv['contact_ext_id'], ENT_QUOTES) ?>', '<?= $cacct ? $cacct['channel'] : '' ?>')"
                        class="w-full text-left p-3.5 border-b border-slate-700/50 hover:bg-slate-700/40 transition flex items-start gap-2.5">
                        <i class="fa-brands fa-<?= ($cacct['channel'] ?? '') === 'whatsapp' ? 'whatsapp text-emerald-400' : 'facebook text-blue-400' ?> mt-1"></i>
                        <span class="flex-1 min-w-0">
                            <span class="flex items-center justify-between gap-2">
                                <b class="text-white text-sm truncate"><?= htmlspecialchars($cv['cname'] ?: $cv['contact_ext_id']) ?></b>
                                <span class="text-[9px] text-slate-500 whitespace-nowrap"><?= date('d M, h:i A', strtotime($cv['last_at'])) ?></span>
                            </span>
                            <span class="flex items-center justify-between gap-2">
                                <span class="text-[11px] text-slate-400 truncate"><?= htmlspecialchars(mb_substr((string)$cv['last_body'], 0, 40)) ?></span>
                                <?php if ($cv['unread'] > 0): ?><span class="bg-emerald-500 text-white text-[9px] font-bold rounded-full px-1.5 py-0.5"><?= (int)$cv['unread'] ?></span><?php endif; ?>
                            </span>
                            <span class="text-[9px] text-slate-600"><?= htmlspecialchars($cacct['label'] ?? '') ?></span>
                        </span>
                    </button>
                    <?php endforeach; endif; ?>
                </div>
                <!-- ডান: থ্রেড -->
                <div class="md:col-span-2 flex flex-col">
                    <div id="threadHeader" class="p-3.5 border-b border-slate-700 text-sm text-slate-400">← বাম দিক থেকে একটা কনভার্সেশন বাছুন</div>
                    <div id="threadBox" class="flex-1 overflow-y-auto p-4 space-y-2 max-h-[52vh]"></div>
                    <div id="replyBar" class="hidden p-3 border-t border-slate-700 flex gap-2">
                        <input type="text" id="replyInput" placeholder="রিপ্লাই লিখুন..." class="flex-1 bg-slate-700 text-white rounded-xl px-4 py-2.5 border border-slate-600 outline-none text-sm" onkeydown="if(event.key==='Enter') sendReply()">
                        <button type="button" onclick="sendReply()" class="bg-emerald-600 hover:bg-emerald-500 text-white font-bold px-5 py-2.5 rounded-xl text-sm"><i class="fa-solid fa-paper-plane"></i></button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        let curAcct = 0, curContact = '', threadTimer = null;
        function openThread(aid, contact, name, channel) {
            curAcct = aid; curContact = contact;
            document.getElementById('threadHeader').innerHTML = '<i class="fa-brands fa-' + (channel === 'whatsapp' ? 'whatsapp text-emerald-400' : 'facebook text-blue-400') + '"></i> <b class="text-white">' + name + '</b> <span class="text-[10px] text-slate-500 font-mono">' + contact + '</span>';
            document.getElementById('replyBar').classList.remove('hidden');
            document.getElementById('replyBar').classList.add('flex');
            loadThread(true);
            if (threadTimer) clearInterval(threadTimer);
            threadTimer = setInterval(() => loadThread(false), 15000); // ১৫ সেকেন্ড পর পর অটো রিফ্রেশ
        }
        function loadThread(scroll) {
            if (!curAcct) return;
            fetch('?action=inbox_thread&account_id=' + curAcct + '&contact=' + encodeURIComponent(curContact))
                .then(r => r.json())
                .then(d => {
                    const box = document.getElementById('threadBox');
                    box.innerHTML = (d.messages || []).map(m =>
                        '<div class="flex ' + (m.direction === 'out' ? 'justify-end' : 'justify-start') + '">'
                        + '<div class="max-w-[75%] rounded-2xl px-4 py-2 text-sm ' + (m.direction === 'out' ? 'bg-emerald-600 text-white rounded-br-sm' : 'bg-slate-700 text-slate-100 rounded-bl-sm') + '">'
                        + '<div style="word-break: break-word; white-space: pre-wrap;">' + escHtml(m.body || '') + '</div>'
                        + '<div class="text-[9px] opacity-60 mt-1 text-right">' + (m.created_at || '') + '</div>'
                        + '</div></div>'
                    ).join('');
                    if (scroll) box.scrollTop = box.scrollHeight;
                });
        }
        function escHtml(t) { const d = document.createElement('div'); d.innerText = t; return d.innerHTML; }
        function sendReply() {
            const inp = document.getElementById('replyInput');
            const msg = inp.value.trim();
            if (!msg || !curAcct) return;
            const fd = new FormData();
            fd.append('account_id', curAcct);
            fd.append('contact', curContact);
            fd.append('message', msg);
            fetch('?action=inbox_send', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(d => {
                    showToast(d.message, d.status === 'success' ? 'success' : 'error');
                    if (d.status === 'success') { inp.value = ''; loadThread(true); }
                });
        }
        function inboxSync(btn) {
            btn.disabled = true;
            btn.innerHTML = 'সিঙ্ক হচ্ছে...';
            fetch('?action=inbox_sync')
                .then(r => r.json())
                .then(d => { showToast(d.message, 'success'); setTimeout(() => location.reload(), 900); })
                .catch(() => { showToast('সিঙ্ক ব্যর্থ', 'error'); btn.disabled = false; btn.innerHTML = 'ফেসবুক পেজ সিঙ্ক করুন'; });
        }
    </script>
    <?php
    render_dashboard_footer();
    exit;
}

// কুরিয়ার জোন চেঞ্জ ট্যাব: ম্যানুয়াল এন্ট্রি (৪ দিন পর অটো রিমুভ) + কনফার্মড অর্ডারের জোন ম্যাচিং
if ($action === 'zone_change') {
    require_login();
    // ৪ দিনের পুরোনো এন্ট্রি অটো ডিলিট
    try { $db->exec("DELETE FROM courier_zone_entries WHERE created_at < NOW() - INTERVAL 4 DAY"); } catch (Exception $e) {}

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_zone_entry'])) {
        global $zone_to_bangla;
        $z_cid = trim($_POST['z_courier_id'] ?? '');
        $z_link = trim($_POST['z_courier_link'] ?? '');
        $z_pid = (int)($_POST['z_product_id'] ?? 0);
        $z_color = trim($_POST['z_color'] ?? '');
        $z_zone_raw = $_POST['z_zone'] ?? '';
        $z_zone = (isset($zone_to_bangla[$z_zone_raw]) || in_array($z_zone_raw, ['dhaka', 'sub_dhaka', 'outside'])) ? $z_zone_raw : '';
        if ($z_cid !== '' && $z_zone !== '') {
            $db->prepare("INSERT INTO courier_zone_entries (courier_id, courier_link, product_id, color, zone, created_by) VALUES (?, ?, ?, ?, ?, ?)")
               ->execute([$z_cid, $z_link !== '' ? $z_link : null, $z_pid ?: null, $z_color !== '' ? $z_color : null, $z_zone, $_SESSION['username'] ?? '']);
            header("Location: ?action=zone_change&zmsg=added");
        } else {
            header("Location: ?action=zone_change&zmsg=invalid");
        }
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_zone_entry'])) {
        $db->prepare("DELETE FROM courier_zone_entries WHERE id = ?")->execute([(int)$_POST['entry_id']]);
        header("Location: ?action=zone_change&zmsg=deleted");
        exit;
    }

    global $zone_to_bangla;
    $zone_entries = $db->query("SELECT z.*, p.title AS product_title FROM courier_zone_entries z LEFT JOIN products p ON p.id = z.product_id ORDER BY z.id DESC")->fetchAll();
    $zc_products = $db->query("SELECT id, title FROM products ORDER BY id DESC")->fetchAll();

    // ==== অটো-লিস্ট: কুরিয়ারে বুকড, ৫+ দিন পার হয়েছে কিন্তু এখনো পেন্ডিং (ডেলিভার/ক্যান্সেল হয়নি) ====
    // শুধু কনফার্ম অর্ডার, in_review অর্ডার, অথবা ম্যানুয়ালি জোন চেঞ্জ লিস্টে যোগ করা অর্ডার — পুরোনো booked নয়
    $stuck_orders = $db->query("
        SELECT o.id, o.customer_name, o.phone, o.address, o.cod_amount, o.tracking_code, o.consignment_id,
               o.courier_name, o.courier_status, o.status, o.booked_at, o.zone_change_flag, p.title AS ptitle,
               CASE WHEN o.booked_at IS NOT NULL THEN DATEDIFF(NOW(), o.booked_at) ELSE NULL END AS days_pending
        FROM orders o LEFT JOIN products p ON p.id = o.product_id
        WHERE o.is_deleted = 0
          AND (
                o.status = 'confirmed'
             OR o.courier_status = 'in_review'
             OR o.zone_change_flag = 1
          )
        ORDER BY o.zone_change_flag DESC, o.id DESC
        LIMIT 150
    ")->fetchAll();
    $zone_bn = array_merge(['dhaka' => 'ঢাকার মধ্যে', 'sub_dhaka' => 'সাব ঢাকা', 'outside' => 'সারা বাংলাদেশ'], $zone_to_bangla);
    $zone_clr = ['dhaka' => 'emerald', 'sub_dhaka' => 'amber', 'outside' => 'sky'];

    render_dashboard_header('কুরিয়ার জোন চেঞ্জ');
    ?>
    <div class="space-y-6 font-semibold">
        <?php if (isset($_GET['zmsg'])): $zm = ['added' => ['s', 'এন্ট্রি যোগ হয়েছে!'], 'deleted' => ['s', 'এন্ট্রি ডিলিট হয়েছে!'], 'invalid' => ['e', 'কুরিয়ার আইডি ও জোন অবশ্যই দিতে হবে!']][$_GET['zmsg']] ?? null; if ($zm): ?>
            <div class="<?= $zm[0] === 'e' ? 'bg-rose-500/10 border-rose-500 text-rose-400' : 'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= $zm[1] ?></div>
        <?php endif; endif; ?>

        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
            <h3 class="text-lg font-bold text-white mb-1 flex items-center gap-2 border-b border-slate-700 pb-3">
                <i class="fa-solid fa-map-location-dot text-orange-400"></i> কুরিয়ার জোন চেঞ্জ — ম্যানুয়াল এন্ট্রি
            </h3>
            <p class="text-[10px] text-slate-500 my-3">এন্ট্রি <b class="text-amber-400">৪ দিন পর অটো রিমুভ</b> হয়ে যাবে; চাইলে ম্যানুয়ালিও ডিলিট করতে পারবেন। প্রতিটি এন্ট্রির নিচে সেই জোনের সাথে ম্যাচ করা আপনার কনফার্মড/সফল অর্ডারগুলো দেখাবে।</p>
            <form action="?action=zone_change" method="POST" class="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-6 gap-3 items-end">
                <input type="hidden" name="add_zone_entry" value="1">
                <div>
                    <label class="block text-slate-300 text-xs mb-1">কুরিয়ার আইডি *</label>
                    <input type="text" name="z_courier_id" required placeholder="যেমন: SF123456" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">কুরিয়ার লিংক</label>
                    <input type="url" name="z_courier_link" placeholder="https://..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">প্রোডাক্ট সিলেক্ট</label>
                    <select name="z_product_id" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="0">— সব প্রোডাক্ট —</option>
                        <?php foreach ($zc_products as $zp): ?>
                        <option value="<?= (int)$zp['id'] ?>"><?= htmlspecialchars($zp['title']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">কালার ফিল্টার <span class="text-slate-500">(অপশনাল)</span></label>
                    <?php $zc_colors = json_decode(get_setting('product_colors'), true) ?: []; ?>
                    <select name="z_color" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="">— সব কালার —</option>
                        <?php foreach ($zc_colors as $zcc): if (empty($zcc['en'])) continue; ?>
                        <option value="<?= htmlspecialchars($zcc['en']) ?>"><?= htmlspecialchars(($zcc['bn'] ?? '') !== '' ? $zcc['bn'] : $zcc['en']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">জোন / জেলা সিলেক্ট *</label>
                    <select name="z_zone" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="">— জেলা বাছুন —</option>
                        <?php global $zone_to_bangla; foreach ($zone_to_bangla as $en_d => $bn_d): ?>
                        <option value="<?= htmlspecialchars($en_d) ?>"><?= htmlspecialchars($bn_d) ?> (<?= htmlspecialchars($en_d) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="bg-orange-600 hover:bg-orange-500 text-white text-sm font-bold px-4 py-2.5 rounded-xl"><i class="fa-solid fa-plus"></i> এন্ট্রি করুন</button>
            </form>
        </div>

        <!-- জোন চেঞ্জ তালিকা: কনফার্ম + in_review + ম্যানুয়ালি যোগ করা অর্ডার -->
        <div class="bg-slate-800 rounded-2xl border border-orange-800/40 shadow-md overflow-hidden">
            <div class="p-5 border-b border-slate-700 bg-orange-950/20 flex items-center gap-3 flex-wrap">
                <h3 class="text-lg font-bold text-white flex items-center gap-2">
                    <i class="fa-solid fa-map-location-dot text-orange-400"></i> জোন চেঞ্জ তালিকা
                </h3>
                <span class="text-xs bg-orange-500/20 text-orange-400 px-2.5 py-1 rounded-full font-mono"><?= count($stuck_orders) ?> টি</span>
                <p class="text-[10px] text-slate-400 w-full mt-1">শুধু <b class="text-emerald-400">কনফার্ম</b> অর্ডার, কুরিয়ারে <b class="text-amber-400">in_review</b> অর্ডার, এবং মূল অর্ডার লিস্ট থেকে <b class="text-orange-400">ম্যানুয়ালি যোগ করা</b> অর্ডার এখানে দেখায়। পুরোনো অর্ডার দেখায় না।</p>
            </div>
            <div class="p-4">
                <?php if (empty($stuck_orders)): ?>
                    <p class="text-sm text-slate-500 text-center py-4"><i class="fa-solid fa-circle-info text-slate-500"></i> এই মুহূর্তে কোনো কনফার্ম/in_review/যোগ করা অর্ডার নেই।</p>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left text-xs">
                            <thead><tr class="text-slate-400 border-b border-slate-700">
                                <th class="py-2 px-2">অর্ডার</th><th class="py-2 px-2">গ্রাহক</th><th class="py-2 px-2">জেলা (ঠিকানা)</th><th class="py-2 px-2 text-center">ধরন</th><th class="py-2 px-2 text-center">কুরিয়ার স্ট্যাটাস</th><th class="py-2 px-2 text-right">COD</th><th class="py-2 px-2 text-center"></th>
                            </tr></thead>
                            <tbody>
                            <?php foreach ($stuck_orders as $so):
                                $ci = courier_status_info($so['courier_status'] ?: 'pending');
                                // ঠিকানা থেকে জেলা অনুমান
                                $matched_dist = '';
                                foreach ($zone_to_bangla as $en_d => $bn_d) {
                                    if (mb_stripos($so['address'], $bn_d) !== false || stripos($so['address'], $en_d) !== false) { $matched_dist = $bn_d; break; }
                                }
                            ?>
                            <tr class="border-b border-slate-700/50 hover:bg-slate-700/20">
                                <td class="py-2.5 px-2">
                                    <a href="?action=order_detail&id=<?= (int)$so['id'] ?>" class="font-mono font-bold text-white hover:text-orange-400">#<?= (int)$so['id'] ?></a>
                                    <?php if ($so['tracking_code']): ?><div class="text-[9px] text-slate-500 font-mono"><?= htmlspecialchars($so['tracking_code']) ?></div><?php endif; ?>
                                </td>
                                <td class="py-2.5 px-2"><span class="text-white font-semibold"><?= htmlspecialchars($so['customer_name']) ?></span><div class="text-[9px] text-slate-500 font-mono"><?= htmlspecialchars($so['phone']) ?></div></td>
                                <td class="py-2.5 px-2"><?php if ($matched_dist): ?><span class="text-[10px] font-bold bg-slate-700 text-slate-200 px-2 py-0.5 rounded-full"><?= $matched_dist ?></span><?php endif; ?><div class="text-[9px] text-slate-500 truncate max-w-[160px]"><?= htmlspecialchars(mb_substr($so['address'], 0, 40)) ?></div></td>
                                <td class="py-2.5 px-2 text-center">
                                    <?php if (!empty($so['zone_change_flag'])): ?><span class="text-[9px] px-2 py-0.5 rounded-full font-bold bg-orange-500/20 text-orange-400">ম্যানুয়াল</span>
                                    <?php elseif ($so['status'] === 'confirmed'): ?><span class="text-[9px] px-2 py-0.5 rounded-full font-bold bg-emerald-500/20 text-emerald-400">কনফার্ম</span>
                                    <?php elseif ($so['courier_status'] === 'in_review'): ?><span class="text-[9px] px-2 py-0.5 rounded-full font-bold bg-amber-500/20 text-amber-400">in_review</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-2.5 px-2 text-center"><span class="text-[9px] px-2 py-0.5 rounded-full font-bold <?= $ci[1] ?>"><?= $ci[0] ?></span></td>
                                <td class="py-2.5 px-2 text-right font-mono text-emerald-400"><?= number_format((float)$so['cod_amount']) ?>৳</td>
                                <td class="py-2.5 px-2 text-center">
                                    <?php if (!empty($so['zone_change_flag'])): ?>
                                    <button type="button" onclick="toggleZoneFlag(<?= (int)$so['id'] ?>, this)" class="text-rose-400 hover:text-rose-300" title="তালিকা থেকে সরান"><i class="fa-solid fa-xmark"></i></button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <h3 class="text-lg font-bold text-white flex items-center gap-2 pt-2"><i class="fa-solid fa-list-check text-orange-400"></i> ম্যানুয়াল জোন এন্ট্রি সমূহ</h3>
        <?php if (empty($zone_entries)): ?>
            <div class="bg-slate-800 border border-slate-700 rounded-2xl p-8 text-center text-slate-400 text-sm">কোনো এন্ট্রি নেই — ওপরের ফর্ম থেকে এন্ট্রি করুন।</div>
        <?php else: foreach ($zone_entries as $ze):
            $days_left = max(0, 4 - (int)floor((time() - strtotime($ze['created_at'])) / 86400));
            $clr = $zone_clr[$ze['zone']] ?? 'orange';
            // এই জোন/জেলার সাথে ম্যাচ করা কনফার্মড/সফল অর্ডার (জেলা হলে ঠিকানায় খোঁজে; প্রোডাক্ট/কালার দিলে সেটাও ম্যাচ)
            $mq = "SELECT o.id, o.status, o.cod_amount, o.tracking_code, o.created_at, p.title AS ptitle FROM orders o LEFT JOIN products p ON p.id = o.product_id
                   WHERE o.is_deleted = 0 AND o.status IN ('confirmed', 'booked', 'delivered')";
            $mp = [];
            if (isset($zone_to_bangla[$ze['zone']])) {
                $mq .= " AND (o.address LIKE ? OR o.address LIKE ?)";
                $mp[] = '%' . $ze['zone'] . '%';
                $mp[] = '%' . $zone_to_bangla[$ze['zone']] . '%';
            } else {
                $mq .= " AND o.delivery_zone = ?";
                $mp[] = $ze['zone'];
            }
            if (!empty($ze['product_id'])) { $mq .= " AND o.product_id = ?"; $mp[] = (int)$ze['product_id']; }
            if (!empty($ze['color'])) { $mq .= " AND o.color_selected LIKE ?"; $mp[] = '%' . $ze['color'] . '%'; }
            $mq .= " ORDER BY o.id DESC LIMIT 12";
            $mst3 = $db->prepare($mq);
            $mst3->execute($mp);
            $zmatches = $mst3->fetchAll();
        ?>
        <div class="bg-slate-800 rounded-2xl border border-slate-700 shadow-md overflow-hidden">
            <div class="p-4 flex flex-wrap items-center gap-3 border-b border-slate-700 bg-slate-900/40">
                <span class="font-mono font-bold text-white text-sm"><i class="fa-solid fa-barcode text-orange-400"></i> <?= htmlspecialchars($ze['courier_id']) ?></span>
                <span class="text-[10px] font-bold bg-<?= $clr ?>-500/20 text-<?= $clr ?>-400 px-2.5 py-1 rounded-full"><?= $zone_bn[$ze['zone']] ?? $ze['zone'] ?></span>
                <?php if ($ze['product_title']): ?><span class="text-[10px] bg-slate-700 text-slate-300 px-2.5 py-1 rounded-full">📦 <?= htmlspecialchars($ze['product_title']) ?></span><?php endif; ?>
                <?php if (!empty($ze['color'])): ?><span class="text-[10px] font-bold bg-fuchsia-500/20 text-fuchsia-300 px-2.5 py-1 rounded-full">🎨 <?= htmlspecialchars($ze['color']) ?></span><?php endif; ?>
                <?php if ($ze['courier_link']): ?><a href="<?= htmlspecialchars($ze['courier_link']) ?>" target="_blank" class="text-[10px] text-cyan-400 hover:underline"><i class="fa-solid fa-link"></i> কুরিয়ার লিংক ↗</a><?php endif; ?>
                <span class="text-[10px] text-slate-500 ml-auto">⏳ <?= $days_left ?> দিন পর অটো রিমুভ | <?= date('d M, h:i A', strtotime($ze['created_at'])) ?></span>
                <form action="?action=zone_change" method="POST" onsubmit="return confirm('এন্ট্রিটি ডিলিট করবেন?');" class="inline">
                    <input type="hidden" name="delete_zone_entry" value="1">
                    <input type="hidden" name="entry_id" value="<?= (int)$ze['id'] ?>">
                    <button type="submit" class="text-rose-400 hover:text-rose-300 p-1"><i class="fa-solid fa-trash"></i></button>
                </form>
            </div>
            <div class="p-4">
                <p class="text-[10px] text-slate-400 font-bold uppercase mb-2">🎯 এই জোনের সাথে ম্যাচ করা কনফার্মড অর্ডার (<?= count($zmatches) ?> টি):</p>
                <?php if (empty($zmatches)): ?>
                    <p class="text-xs text-slate-500">এই জোনে কোনো কনফার্মড/সফল অর্ডার পাওয়া যায়নি।</p>
                <?php else: ?>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
                        <?php foreach ($zmatches as $zm2): global $status_map; ?>
                        <a href="?action=order_detail&id=<?= (int)$zm2['id'] ?>" class="flex items-center justify-between gap-2 bg-slate-900/60 border border-slate-700 hover:border-orange-500 rounded-lg px-3 py-2 transition">
                            <span class="font-mono font-bold text-white text-xs">#<?= (int)$zm2['id'] ?></span>
                            <span class="text-[10px] text-slate-400 truncate flex-1"><?= htmlspecialchars(mb_substr($zm2['ptitle'] ?? '—', 0, 20)) ?></span>
                            <span class="text-[9px] font-bold px-2 py-0.5 rounded-full <?= $zm2['status'] === 'delivered' ? 'bg-sky-500/20 text-sky-400' : ($zm2['status'] === 'booked' ? 'bg-indigo-500/20 text-indigo-300' : 'bg-emerald-500/20 text-emerald-400') ?>"><?= $status_map[$zm2['status']] ?? $zm2['status'] ?></span>
                            <span class="font-mono text-emerald-400 text-[10px]"><?= number_format((float)$zm2['cod_amount']) ?>৳</span>
                        </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>
    <script>
        function toggleZoneFlag(id, btn) {
            fetch('?action=toggle_zone_flag&id=' + id)
                .then(r => r.json())
                .then(d => {
                    showToast(d.message, d.status === 'success' ? 'success' : 'error');
                    if (d.status === 'success' && d.flagged === 0) {
                        // তালিকা থেকে সরানো হলে সারি মুছে দাও
                        const row = btn.closest('tr'); if (row) row.remove();
                    }
                }).catch(() => showToast('আপডেট ব্যর্থ', 'error'));
        }
    </script>
    <?php
    render_dashboard_footer();
    exit;
}

// লিংক শর্টনার ট্যাব (কাস্টম শর্ট লিংক তৈরি/এডিট/ডিলিট)
if ($action === 'short_links') {
    require_admin_or_office();

    // ---- তৈরি ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_link'])) {
        $code = trim($_POST['link_code'] ?? '');
        $code = preg_replace('/[^A-Za-z0-9_-]/', '', $code); // নিরাপদ কোড
        $url = trim($_POST['target_url'] ?? '');
        $title = trim($_POST['link_title'] ?? '');
        if ($code === '') $code = substr(bin2hex(random_bytes(4)), 0, 6); // খালি হলে অটো কোড
        if ($url !== '') {
            try {
                $db->prepare("INSERT INTO short_links (code, target_url, title, created_by) VALUES (?, ?, ?, ?)")
                   ->execute([$code, $url, $title ?: null, $_SESSION['username'] ?? '']);
                header("Location: ?action=short_links&lmsg=added");
            } catch (Exception $e) {
                header("Location: ?action=short_links&lmsg=dup"); // কোড ডুপ্লিকেট
            }
        } else { header("Location: ?action=short_links&lmsg=invalid"); }
        exit;
    }
    // ---- এডিট ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_link'])) {
        $lid = (int)$_POST['link_id'];
        $code = preg_replace('/[^A-Za-z0-9_-]/', '', trim($_POST['link_code'] ?? ''));
        $url = trim($_POST['target_url'] ?? '');
        $title = trim($_POST['link_title'] ?? '');
        if ($lid && $code !== '' && $url !== '') {
            try {
                $db->prepare("UPDATE short_links SET code = ?, target_url = ?, title = ? WHERE id = ?")
                   ->execute([$code, $url, $title ?: null, $lid]);
                header("Location: ?action=short_links&lmsg=updated");
            } catch (Exception $e) { header("Location: ?action=short_links&lmsg=dup"); }
        } else { header("Location: ?action=short_links&lmsg=invalid"); }
        exit;
    }
    // ---- ডিলিট / টগল ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_link'])) {
        $db->prepare("DELETE FROM short_links WHERE id = ?")->execute([(int)$_POST['link_id']]);
        header("Location: ?action=short_links&lmsg=deleted"); exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_link'])) {
        $db->prepare("UPDATE short_links SET active = 1 - active WHERE id = ?")->execute([(int)$_POST['link_id']]);
        header("Location: ?action=short_links&lmsg=toggled"); exit;
    }

    $links = $db->query("SELECT * FROM short_links ORDER BY id DESC")->fetchAll();
    $short_base = base_url() . '/?action=go&code=';

    render_dashboard_header('লিংক শর্টনার');
    ?>
    <div class="space-y-6 font-semibold">
        <?php if (isset($_GET['lmsg'])): $lm = ['added'=>['s','শর্ট লিংক তৈরি হয়েছে!'],'updated'=>['s','লিংক আপডেট হয়েছে!'],'deleted'=>['s','লিংক ডিলিট হয়েছে!'],'toggled'=>['s','লিংকের অবস্থা পরিবর্তন হয়েছে!'],'dup'=>['e','এই কোড আগে থেকেই আছে — অন্য কোড দিন।'],'invalid'=>['e','টার্গেট URL দিন।']][$_GET['lmsg']] ?? null; if ($lm): ?>
            <div class="<?= $lm[0]==='e'?'bg-rose-500/10 border-rose-500 text-rose-400':'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= $lm[1] ?></div>
        <?php endif; endif; ?>

        <!-- নতুন লিংক তৈরি -->
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-link text-cyan-400"></i> নতুন শর্ট লিংক তৈরি করুন</h3>
            <form action="?action=short_links" method="POST" class="grid grid-cols-1 md:grid-cols-4 gap-3 items-end">
                <input type="hidden" name="add_link" value="1">
                <div class="md:col-span-2">
                    <label class="block text-slate-300 text-xs mb-1">টার্গেট URL <span class="text-rose-400">*</span></label>
                    <input type="text" name="target_url" required placeholder="https://facebook.com/... বা যেকোনো লম্বা লিংক" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">কাস্টম কোড <span class="text-slate-500">(ঐচ্ছিক)</span></label>
                    <input type="text" name="link_code" placeholder="যেমন: eid-offer" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">টাইটেল <span class="text-slate-500">(ঐচ্ছিক)</span></label>
                    <input type="text" name="link_title" placeholder="যেমন: ঈদ ক্যাম্পেইন" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                </div>
                <div class="md:col-span-4">
                    <button type="submit" class="bg-cyan-600 hover:bg-cyan-500 text-white text-sm font-bold px-6 py-2.5 rounded-xl"><i class="fa-solid fa-plus"></i> লিংক তৈরি করুন</button>
                    <span class="text-[11px] text-slate-500 ml-2">কোড খালি রাখলে অটো তৈরি হবে। কোডে শুধু অক্ষর/সংখ্যা/hyphen চলবে।</span>
                </div>
            </form>
        </div>

        <!-- লিংক তালিকা -->
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md overflow-x-auto">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2"><i class="fa-solid fa-list text-slate-400"></i> আপনার শর্ট লিংকসমূহ (<?= count($links) ?>)</h3>
            <?php if (empty($links)): ?>
                <p class="text-sm text-slate-500 text-center py-6">এখনো কোনো শর্ট লিংক নেই — ওপরের ফর্ম থেকে তৈরি করুন।</p>
            <?php else: ?>
            <table class="w-full text-left text-xs">
                <thead><tr class="text-slate-400 border-b border-slate-700">
                    <th class="py-2 px-2">টাইটেল / শর্ট লিংক</th><th class="py-2 px-2">টার্গেট</th><th class="py-2 px-2 text-center">ক্লিক</th><th class="py-2 px-2 text-center">অবস্থা</th><th class="py-2 px-2 text-right">অ্যাকশন</th>
                </tr></thead>
                <tbody>
                <?php foreach ($links as $lk): $full = $short_base . $lk['code']; ?>
                <tr class="border-b border-slate-700/50" id="linkrow-<?= (int)$lk['id'] ?>">
                    <td class="py-2.5 px-2">
                        <?php if ($lk['title']): ?><span class="text-white font-bold block"><?= htmlspecialchars($lk['title']) ?></span><?php endif; ?>
                        <div class="flex items-center gap-1.5 mt-0.5">
                            <span class="font-mono text-cyan-400 text-[11px]" id="short-<?= (int)$lk['id'] ?>"><?= htmlspecialchars($full) ?></span>
                            <button type="button" onclick="copyShort('<?= htmlspecialchars($full, ENT_QUOTES) ?>', this)" class="text-slate-500 hover:text-white" title="কপি করুন"><i class="fa-solid fa-copy text-[10px]"></i></button>
                        </div>
                    </td>
                    <td class="py-2.5 px-2 max-w-[220px] truncate text-slate-400" title="<?= htmlspecialchars($lk['target_url']) ?>"><?= htmlspecialchars($lk['target_url']) ?></td>
                    <td class="py-2.5 px-2 text-center"><span class="bg-slate-700 text-white px-2 py-0.5 rounded-full font-mono"><?= (int)$lk['clicks'] ?></span></td>
                    <td class="py-2.5 px-2 text-center">
                        <form action="?action=short_links" method="POST" class="inline">
                            <input type="hidden" name="toggle_link" value="1"><input type="hidden" name="link_id" value="<?= (int)$lk['id'] ?>">
                            <button class="text-[10px] px-2 py-0.5 rounded-full font-bold <?= $lk['active'] ? 'bg-emerald-500/20 text-emerald-400' : 'bg-slate-600/40 text-slate-400' ?>"><?= $lk['active'] ? 'সক্রিয়' : 'নিষ্ক্রিয়' ?></button>
                        </form>
                    </td>
                    <td class="py-2.5 px-2 text-right whitespace-nowrap">
                        <button type="button" onclick='editLink(<?= json_encode(["id"=>(int)$lk["id"],"code"=>$lk["code"],"url"=>$lk["target_url"],"title"=>$lk["title"] ?? ""], JSON_UNESCAPED_UNICODE|JSON_HEX_APOS|JSON_HEX_QUOT) ?>)' class="text-indigo-400 hover:text-indigo-300 mr-2" title="এডিট"><i class="fa-solid fa-pen"></i></button>
                        <a href="<?= htmlspecialchars($full) ?>" target="_blank" class="text-emerald-400 hover:text-emerald-300 mr-2" title="খুলুন"><i class="fa-solid fa-up-right-from-square"></i></a>
                        <form action="?action=short_links" method="POST" class="inline" onsubmit="return confirm('এই লিংকটি ডিলিট করবেন?');">
                            <input type="hidden" name="del_link" value="1"><input type="hidden" name="link_id" value="<?= (int)$lk['id'] ?>">
                            <button class="text-rose-400 hover:text-rose-300" title="ডিলিট"><i class="fa-solid fa-trash"></i></button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>

    <!-- এডিট মোডাল -->
    <div id="editLinkModal" class="hidden fixed inset-0 z-[170] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
        <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-md w-full p-6 shadow-2xl relative">
            <button onclick="document.getElementById('editLinkModal').classList.add('hidden')" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold">&times;</button>
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2"><i class="fa-solid fa-pen text-indigo-400"></i> লিংক এডিট করুন</h3>
            <form action="?action=short_links" method="POST" class="space-y-3">
                <input type="hidden" name="edit_link" value="1"><input type="hidden" name="link_id" id="edit_link_id">
                <div><label class="block text-slate-300 text-xs mb-1">টার্গেট URL</label><input type="text" name="target_url" id="edit_target_url" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm"></div>
                <div><label class="block text-slate-300 text-xs mb-1">কোড</label><input type="text" name="link_code" id="edit_link_code" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono"></div>
                <div><label class="block text-slate-300 text-xs mb-1">টাইটেল</label><input type="text" name="link_title" id="edit_link_title" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm"></div>
                <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-2.5 rounded-xl text-sm"><i class="fa-solid fa-floppy-disk"></i> সেভ করুন</button>
            </form>
        </div>
    </div>
    <script>
        function copyShort(url, btn) {
            navigator.clipboard.writeText(url).then(() => { showToast('লিংক কপি হয়েছে!', 'success'); }).catch(()=>{});
        }
        function editLink(d) {
            document.getElementById('edit_link_id').value = d.id;
            document.getElementById('edit_target_url').value = d.url;
            document.getElementById('edit_link_code').value = d.code;
            document.getElementById('edit_link_title').value = d.title || '';
            document.getElementById('editLinkModal').classList.remove('hidden');
        }
    </script>
    <?php
    render_dashboard_footer();
    exit;
}

// অ্যাড খরচ ট্র্যাকিং ট্যাব (ম্যানুয়াল এন্ট্রি + FB API সিঙ্ক + ROAS/প্রতি-অর্ডার হিসাব)
if ($action === 'ad_costs') {
    require_admin_or_office();
    $usd_rate = (float)(get_setting('usd_to_bdt') ?: 122);

    // ---- অ্যাকাউন্ট যোগ/টগল/ডিলিট ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_ad_account'])) {
        $plat = in_array($_POST['ad_platform'] ?? '', ['facebook','tiktok','google','other']) ? $_POST['ad_platform'] : 'facebook';
        $lbl = trim($_POST['ad_label'] ?? '');
        $fbid = trim($_POST['fb_account_id'] ?? '');
        $fbtok = trim($_POST['fb_access_token'] ?? '');
        if ($lbl !== '') {
            $db->prepare("INSERT INTO ad_accounts (platform, label, fb_account_id, fb_access_token, auto_sync) VALUES (?, ?, ?, ?, ?)")
               ->execute([$plat, $lbl, $fbid ?: null, $fbtok ?: null, ($fbid && $fbtok) ? 1 : 0]);
            header("Location: ?action=ad_costs&amsg=acct_added");
        } else { header("Location: ?action=ad_costs&amsg=invalid"); }
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_ad_account'])) {
        $aid = (int)$_POST['acct_id'];
        $db->prepare("DELETE FROM ad_accounts WHERE id = ?")->execute([$aid]);
        $db->prepare("DELETE FROM ad_spends WHERE account_id = ?")->execute([$aid]);
        header("Location: ?action=ad_costs&amsg=acct_deleted"); exit;
    }
    // ---- USD রেট সেভ ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_usd_rate'])) {
        $r = (float)bnToEnNumber($_POST['usd_to_bdt'] ?? '122');
        update_setting('usd_to_bdt', (string)($r > 0 ? $r : 122));
        header("Location: ?action=ad_costs&amsg=rate_saved"); exit;
    }
    // ---- দৈনিক খরচ এন্ট্রি (USD বা BDT — যেটা দেবে, অন্যটা অটো) ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_spend'])) {
        $aid = (int)$_POST['spend_account'];
        $sdate = $_POST['spend_date'] ?? date('Y-m-d');
        $usd = $_POST['amount_usd'] !== '' ? (float)bnToEnNumber($_POST['amount_usd']) : 0;
        $bdt = $_POST['amount_bdt'] !== '' ? (float)bnToEnNumber($_POST['amount_bdt']) : 0;
        $snote = trim($_POST['spend_note'] ?? '');
        if ($usd > 0 && $bdt <= 0) $bdt = round($usd * $usd_rate, 2);
        if ($bdt > 0 && $usd <= 0) $usd = round($bdt / $usd_rate, 2);
        if ($aid && ($usd > 0 || $bdt > 0)) {
            // একই দিন+অ্যাকাউন্টে থাকলে আপডেট (UNIQUE key)
            $db->prepare("INSERT INTO ad_spends (account_id, spend_date, amount_usd, amount_bdt, note, source, created_by)
                          VALUES (?, ?, ?, ?, ?, 'manual', ?)
                          ON DUPLICATE KEY UPDATE amount_usd = VALUES(amount_usd), amount_bdt = VALUES(amount_bdt), note = VALUES(note), source = 'manual'")
               ->execute([$aid, $sdate, $usd, $bdt, $snote ?: null, $_SESSION['username'] ?? '']);
            header("Location: ?action=ad_costs&amsg=spend_added");
        } else { header("Location: ?action=ad_costs&amsg=invalid"); }
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['del_spend'])) {
        $db->prepare("DELETE FROM ad_spends WHERE id = ?")->execute([(int)$_POST['spend_id']]);
        header("Location: ?action=ad_costs&amsg=spend_deleted"); exit;
    }
    // ---- FB API অটো-সিঙ্ক (আজকের খরচ টেনে আনা) ----
    if ($action === 'ad_costs' && isset($_GET['sync']) && $_GET['sync'] === 'fb') {
        header('Content-Type: application/json; charset=utf-8');
        if (!function_exists('curl_init')) { echo json_encode(['status'=>'error','message'=>'সার্ভারে PHP cURL নেই']); exit; }
        $accts = $db->query("SELECT * FROM ad_accounts WHERE platform = 'facebook' AND auto_sync = 1 AND active = 1 AND fb_account_id <> '' AND fb_access_token IS NOT NULL")->fetchAll();
        $pulled = 0; $errs = [];
        foreach ($accts as $ac) {
            $acct_id = strpos($ac['fb_account_id'], 'act_') === 0 ? $ac['fb_account_id'] : 'act_' . $ac['fb_account_id'];
            $url = "https://graph.facebook.com/v19.0/{$acct_id}/insights?fields=spend&date_preset=today&access_token=" . rawurlencode($ac['fb_access_token']);
            $ch = curl_init($url);
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20]);
            $res = curl_exec($ch); $err = curl_error($ch); curl_close($ch);
            if ($err) { $errs[] = $ac['label'] . ': ' . $err; continue; }
            $j = json_decode($res, true);
            if (!is_array($j) || isset($j['error'])) { $errs[] = $ac['label'] . ': ' . ($j['error']['message'] ?? 'API এরর'); continue; }
            $spend_usd = (float)($j['data'][0]['spend'] ?? 0);
            if ($spend_usd > 0) {
                $bdt = round($spend_usd * $usd_rate, 2);
                $db->prepare("INSERT INTO ad_spends (account_id, spend_date, amount_usd, amount_bdt, source, created_by)
                              VALUES (?, CURDATE(), ?, ?, 'api', 'FB-API')
                              ON DUPLICATE KEY UPDATE amount_usd = VALUES(amount_usd), amount_bdt = VALUES(amount_bdt), source = 'api'")
                   ->execute([(int)$ac['id'], $spend_usd, $bdt]);
                $pulled++;
            }
        }
        echo json_encode(['status'=>'success','pulled'=>$pulled,'errors'=>$errs,
            'message'=> $pulled . ' টি অ্যাকাউন্টের আজকের খরচ সিঙ্ক হয়েছে' . (empty($errs) ? '' : ' (এরর: ' . implode('; ', array_slice($errs,0,2)) . ')')], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $ad_accounts = $db->query("SELECT * FROM ad_accounts ORDER BY id")->fetchAll();

    // ---- সামারি: আজ / এই মাসে / সর্বমোট (খরচ) + সেই সময়ের সেল/অর্ডার (ROAS) ----
    $plat_bn = ['facebook'=>'Facebook','tiktok'=>'TikTok','google'=>'Google','other'=>'অন্যান্য'];
    $plat_clr = ['facebook'=>'blue','tiktok'=>'pink','google'=>'amber','other'=>'slate'];
    $sum_row = function($where_spend, $where_order) use ($db) {
        $sp = $db->query("SELECT COALESCE(SUM(amount_usd),0) usd, COALESCE(SUM(amount_bdt),0) bdt FROM ad_spends WHERE $where_spend")->fetch();
        $od = $db->query("SELECT COUNT(*) cnt, COALESCE(SUM(cod_amount),0) sales FROM orders WHERE is_deleted = 0 AND status IN ('confirmed','booked','delivered') AND $where_order")->fetch();
        return ['usd'=>(float)$sp['usd'], 'bdt'=>(float)$sp['bdt'], 'orders'=>(int)$od['cnt'], 'sales'=>(float)$od['sales']];
    };
    $sum_today = $sum_row("spend_date = CURDATE()", "DATE(created_at) = CURDATE()");
    $sum_month = $sum_row("YEAR(spend_date)=YEAR(CURDATE()) AND MONTH(spend_date)=MONTH(CURDATE())", "YEAR(created_at)=YEAR(CURDATE()) AND MONTH(created_at)=MONTH(CURDATE())");
    $sum_all = $sum_row("1=1", "1=1");

    // প্ল্যাটফর্মভিত্তিক (এই মাস)
    $by_platform = $db->query("
        SELECT a.platform, COALESCE(SUM(s.amount_bdt),0) bdt, COALESCE(SUM(s.amount_usd),0) usd
        FROM ad_accounts a LEFT JOIN ad_spends s ON s.account_id = a.id
            AND YEAR(s.spend_date)=YEAR(CURDATE()) AND MONTH(s.spend_date)=MONTH(CURDATE())
        GROUP BY a.platform HAVING bdt > 0 ORDER BY bdt DESC
    ")->fetchAll();

    // সাম্প্রতিক খরচ এন্ট্রি (৩০টা)
    $recent = $db->query("SELECT s.*, a.label, a.platform FROM ad_spends s JOIN ad_accounts a ON a.id = s.account_id ORDER BY s.spend_date DESC, s.id DESC LIMIT 30")->fetchAll();
    // গত ১৪ দিনের চার্ট ডেটা
    $chart = $db->query("SELECT spend_date, SUM(amount_bdt) bdt FROM ad_spends WHERE spend_date >= (CURDATE() - INTERVAL 13 DAY) GROUP BY spend_date ORDER BY spend_date")->fetchAll();

    render_dashboard_header('অ্যাড খরচ');
    $roas = function($sales, $bdt) { return $bdt > 0 ? round($sales / $bdt, 2) : 0; };
    $cpo = function($bdt, $orders) { return $orders > 0 ? round($bdt / $orders) : 0; };
    ?>
    <div class="space-y-6 font-semibold">
        <?php if (isset($_GET['amsg'])): $am = ['acct_added'=>['s','অ্যাড অ্যাকাউন্ট যোগ হয়েছে!'],'acct_deleted'=>['s','অ্যাকাউন্ট ডিলিট হয়েছে!'],'spend_added'=>['s','খরচ সেভ হয়েছে!'],'spend_deleted'=>['s','খরচ এন্ট্রি ডিলিট হয়েছে!'],'rate_saved'=>['s','ডলার রেট সেভ হয়েছে!'],'invalid'=>['e','সব ঘর ঠিকভাবে পূরণ করুন!']][$_GET['amsg']] ?? null; if ($am): ?>
            <div class="<?= $am[0]==='e' ? 'bg-rose-500/10 border-rose-500 text-rose-400':'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= $am[1] ?></div>
        <?php endif; endif; ?>

        <!-- সামারি কার্ড -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <?php foreach ([['আজকের খরচ',$sum_today,'cyan'],['এই মাসের খরচ',$sum_month,'violet'],['সর্বমোট খরচ',$sum_all,'emerald']] as $c): $d = $c[1]; ?>
            <div class="bg-slate-800 p-5 rounded-2xl border border-slate-700 shadow-md">
                <span class="text-<?= $c[2] ?>-400 text-xs font-bold uppercase"><?= $c[0] ?></span>
                <div class="mt-2 text-2xl font-extrabold text-white">৳<?= number_format($d['bdt']) ?></div>
                <div class="text-[11px] text-slate-400 font-mono">$<?= number_format($d['usd'],2) ?></div>
                <div class="mt-2 pt-2 border-t border-slate-700 grid grid-cols-2 gap-1 text-[10px]">
                    <span class="text-slate-400">সেল: <b class="text-emerald-400">৳<?= number_format($d['sales']) ?></b></span>
                    <span class="text-slate-400">অর্ডার: <b class="text-white"><?= number_format($d['orders']) ?></b></span>
                    <span class="text-slate-400">ROAS: <b class="<?= $roas($d['sales'],$d['bdt']) >= 2 ? 'text-emerald-400':'text-amber-400' ?>"><?= $roas($d['sales'],$d['bdt']) ?>x</b></span>
                    <span class="text-slate-400">প্রতি অর্ডার: <b class="text-white">৳<?= number_format($cpo($d['bdt'],$d['orders'])) ?></b></span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <p class="text-[10px] text-slate-500 -mt-3">ROAS = অ্যাড খরচের প্রতি টাকায় কত বিক্রি (কনফার্ম+বুকড+ডেলিভারড অর্ডার ধরে)। ২x+ সাধারণত ভালো। প্রতি-অর্ডার খরচ = মোট অ্যাড খরচ ÷ অর্ডার সংখ্যা।</p>

        <?php if (!empty($by_platform)): ?>
        <div class="bg-slate-800 p-5 rounded-2xl border border-slate-700 shadow-md">
            <h3 class="text-sm font-bold text-white mb-3">এই মাসে প্ল্যাটফর্মভিত্তিক খরচ</h3>
            <div class="flex flex-wrap gap-3">
                <?php foreach ($by_platform as $bp): $cl = $plat_clr[$bp['platform']] ?? 'slate'; ?>
                <div class="bg-slate-900/60 border border-<?= $cl ?>-700/40 rounded-xl px-4 py-2.5">
                    <span class="text-<?= $cl ?>-400 text-xs font-bold"><?= $plat_bn[$bp['platform']] ?? $bp['platform'] ?></span>
                    <div class="text-lg font-extrabold text-white">৳<?= number_format($bp['bdt']) ?></div>
                    <div class="text-[10px] text-slate-500 font-mono">$<?= number_format($bp['usd'],2) ?></div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php if (count($chart) > 1): ?>
        <div class="bg-slate-800 p-5 rounded-2xl border border-slate-700 shadow-md">
            <h3 class="text-sm font-bold text-white mb-4">গত ১৪ দিনের দৈনিক খরচ (৳)</h3>
            <div class="flex items-end gap-1.5 h-32">
                <?php $maxv = max(array_map(fn($r)=>(float)$r['bdt'], $chart)) ?: 1; foreach ($chart as $cr): $h = round((float)$cr['bdt']/$maxv*100); ?>
                <div class="flex-1 flex flex-col items-center justify-end h-full group">
                    <span class="text-[8px] text-slate-400 mb-0.5 opacity-0 group-hover:opacity-100">৳<?= number_format($cr['bdt']) ?></span>
                    <div class="w-full bg-gradient-to-t from-cyan-600 to-cyan-400 rounded-t" style="height: <?= max(2,$h) ?>%"></div>
                    <span class="text-[7px] text-slate-500 mt-1"><?= date('d/m', strtotime($cr['spend_date'])) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- খরচ এন্ট্রি ফর্ম -->
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-plus-circle text-emerald-400"></i> দৈনিক খরচ যোগ করুন</h3>
                <?php if (empty($ad_accounts)): ?>
                    <p class="text-sm text-amber-400">আগে ডান পাশে একটি অ্যাড অ্যাকাউন্ট যোগ করুন।</p>
                <?php else: ?>
                <form action="?action=ad_costs" method="POST" class="space-y-3">
                    <input type="hidden" name="add_spend" value="1">
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-slate-300 text-xs mb-1">অ্যাকাউন্ট</label>
                            <select name="spend_account" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                                <?php foreach ($ad_accounts as $ac): ?><option value="<?= (int)$ac['id'] ?>"><?= htmlspecialchars($ac['label']) ?> (<?= $plat_bn[$ac['platform']] ?? $ac['platform'] ?>)</option><?php endforeach; ?>
                            </select></div>
                        <div><label class="block text-slate-300 text-xs mb-1">তারিখ</label>
                            <input type="date" name="spend_date" value="<?= date('Y-m-d') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm"></div>
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div><label class="block text-slate-300 text-xs mb-1">ডলার ($) <span class="text-slate-500">— যেকোনো একটা</span></label>
                            <input type="number" step="0.01" name="amount_usd" placeholder="যেমন: 10" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono"></div>
                        <div><label class="block text-slate-300 text-xs mb-1">টাকা (৳)</label>
                            <input type="number" step="0.01" name="amount_bdt" placeholder="যেমন: 1220" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono"></div>
                    </div>
                    <p class="text-[10px] text-slate-500">একটা দিলেই হবে — বর্তমান রেট (১$ = ৳<?= number_format($usd_rate) ?>) দিয়ে অন্যটা অটো হিসাব হবে। একই দিন+অ্যাকাউন্টে আবার দিলে আপডেট হবে।</p>
                    <input type="text" name="spend_note" placeholder="নোট (ঐচ্ছিক) — যেমন: ঈদ ক্যাম্পেইন" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-2.5 rounded-xl text-sm"><i class="fa-solid fa-floppy-disk"></i> খরচ সেভ করুন</button>
                </form>
                <?php endif; ?>
            </div>

            <!-- অ্যাকাউন্ট ম্যানেজার -->
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-bullhorn text-blue-400"></i> অ্যাড অ্যাকাউন্ট</h3>
                <form action="?action=ad_costs" method="POST" class="space-y-3 mb-4">
                    <input type="hidden" name="add_ad_account" value="1">
                    <div class="grid grid-cols-2 gap-3">
                        <select name="ad_platform" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                            <option value="facebook">Facebook</option><option value="tiktok">TikTok</option><option value="google">Google</option><option value="other">অন্যান্য</option>
                        </select>
                        <input type="text" name="ad_label" required placeholder="নাম যেমন: মেইন পেজ" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    </div>
                    <details class="text-xs text-slate-400">
                        <summary class="cursor-pointer text-blue-400">FB API অটো-সিঙ্ক (ঐচ্ছিক) — সেটআপ</summary>
                        <div class="mt-2 space-y-2">
                            <input type="text" name="fb_account_id" placeholder="Ad Account ID (যেমন: act_1234...)" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs font-mono">
                            <input type="text" name="fb_access_token" placeholder="Access Token (ads_read পারমিশন)" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs font-mono">
                            <p class="text-[10px] text-slate-500">দুটো দিলে "সিঙ্ক" বাটনে আজকের খরচ অটো আসবে। না দিলে শুধু ম্যানুয়াল এন্ট্রি চলবে।</p>
                        </div>
                    </details>
                    <button type="submit" class="w-full bg-blue-600 hover:bg-blue-500 text-white font-bold py-2 rounded-lg text-sm"><i class="fa-solid fa-plus"></i> অ্যাকাউন্ট যোগ করুন</button>
                </form>
                <?php if (!empty($ad_accounts)): ?>
                <div class="space-y-2">
                    <?php foreach ($ad_accounts as $ac): ?>
                    <div class="flex items-center gap-2 bg-slate-900/60 border border-slate-700 rounded-xl px-3 py-2 text-xs">
                        <span class="font-bold text-white"><?= htmlspecialchars($ac['label']) ?></span>
                        <span class="text-[9px] bg-<?= $plat_clr[$ac['platform']] ?? 'slate' ?>-500/20 text-<?= $plat_clr[$ac['platform']] ?? 'slate' ?>-400 px-2 py-0.5 rounded-full"><?= $plat_bn[$ac['platform']] ?? $ac['platform'] ?></span>
                        <?php if ($ac['auto_sync']): ?><span class="text-[9px] text-emerald-400" title="API সিঙ্ক চালু"><i class="fa-solid fa-rotate"></i> API</span><?php endif; ?>
                        <form action="?action=ad_costs" method="POST" class="ml-auto inline" onsubmit="return confirm('অ্যাকাউন্ট ও তার সব খরচ এন্ট্রি ডিলিট হবে?');">
                            <input type="hidden" name="del_ad_account" value="1"><input type="hidden" name="acct_id" value="<?= (int)$ac['id'] ?>">
                            <button class="text-rose-400 hover:text-rose-300"><i class="fa-solid fa-trash"></i></button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="flex flex-wrap items-center gap-2 mt-4 pt-3 border-t border-slate-700">
                    <button type="button" onclick="syncFbAds(this)" class="bg-blue-600/80 hover:bg-blue-500 text-white text-xs font-bold px-3 py-1.5 rounded-lg"><i class="fa-brands fa-facebook"></i> FB আজকের খরচ সিঙ্ক</button>
                    <form action="?action=ad_costs" method="POST" class="flex items-center gap-2">
                        <input type="hidden" name="save_usd_rate" value="1">
                        <label class="text-[11px] text-slate-400">১$ = ৳</label>
                        <input type="number" step="0.01" name="usd_to_bdt" value="<?= htmlspecialchars((string)$usd_rate) ?>" class="w-20 bg-slate-700 text-white rounded-lg px-2 py-1 border border-slate-600 outline-none text-xs font-mono">
                        <button class="bg-slate-600 hover:bg-slate-500 text-white text-[11px] px-3 py-1 rounded-lg">রেট সেভ</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- সাম্প্রতিক এন্ট্রি -->
        <?php if (!empty($recent)): ?>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md overflow-x-auto">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2"><i class="fa-solid fa-clock-rotate-left text-slate-400"></i> সাম্প্রতিক খরচ এন্ট্রি</h3>
            <table class="w-full text-left text-xs">
                <thead><tr class="text-slate-400 border-b border-slate-700">
                    <th class="py-2 px-2">তারিখ</th><th class="py-2 px-2">অ্যাকাউন্ট</th><th class="py-2 px-2 text-right">ডলার</th><th class="py-2 px-2 text-right">টাকা</th><th class="py-2 px-2">উৎস</th><th class="py-2 px-2">নোট</th><th class="py-2 px-2"></th>
                </tr></thead>
                <tbody>
                <?php foreach ($recent as $r): ?>
                <tr class="border-b border-slate-700/50">
                    <td class="py-2 px-2 font-mono text-slate-300"><?= date('d M Y', strtotime($r['spend_date'])) ?></td>
                    <td class="py-2 px-2 text-white"><?= htmlspecialchars($r['label']) ?> <span class="text-[9px] text-slate-500">(<?= $plat_bn[$r['platform']] ?? $r['platform'] ?>)</span></td>
                    <td class="py-2 px-2 text-right font-mono text-slate-400">$<?= number_format($r['amount_usd'],2) ?></td>
                    <td class="py-2 px-2 text-right font-mono text-emerald-400 font-bold">৳<?= number_format($r['amount_bdt']) ?></td>
                    <td class="py-2 px-2"><span class="text-[9px] px-2 py-0.5 rounded-full <?= $r['source']==='api' ? 'bg-blue-500/20 text-blue-400':'bg-slate-600/40 text-slate-400' ?>"><?= $r['source']==='api'?'API':'ম্যানুয়াল' ?></span></td>
                    <td class="py-2 px-2 text-slate-400 text-[10px]"><?= htmlspecialchars($r['note'] ?? '') ?></td>
                    <td class="py-2 px-2 text-right"><form action="?action=ad_costs" method="POST" class="inline" onsubmit="return confirm('এই খরচ এন্ট্রি ডিলিট করবেন?');"><input type="hidden" name="del_spend" value="1"><input type="hidden" name="spend_id" value="<?= (int)$r['id'] ?>"><button class="text-rose-400 hover:text-rose-300"><i class="fa-solid fa-trash text-[10px]"></i></button></form></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
    <script>
        function syncFbAds(btn) {
            btn.disabled = true; btn.innerHTML = 'সিঙ্ক হচ্ছে...';
            fetch('?action=ad_costs&sync=fb').then(r=>r.json()).then(d=>{
                showToast(d.message, d.status==='success'?'success':'error');
                if (d.status==='success' && d.pulled > 0) setTimeout(()=>location.reload(), 900);
                else { btn.disabled = false; btn.innerHTML = '<i class="fa-brands fa-facebook"></i> FB আজকের খরচ সিঙ্ক'; }
            }).catch(()=>{ showToast('সিঙ্ক ব্যর্থ', 'error'); btn.disabled=false; btn.innerHTML='<i class="fa-brands fa-facebook"></i> FB আজকের খরচ সিঙ্ক'; });
        }
    </script>
    <?php
    render_dashboard_footer();
    exit;
}

// রিপোর্ট ট্যাব: লাভ-ক্ষতি + এজেন্ট পারফরম্যান্স
if ($action === 'reports') {
    require_admin_or_office();
    render_dashboard_header('রিপোর্ট');


    // ---- লাভ-ক্ষতি (ডেলিভারড: COD − ডেলিভারি চার্জ − কেনা দাম) ----
    $profit_rows = [];
    foreach ([['আজ', "DATE(o.created_at) = CURDATE()"], ['এই মাসে', "YEAR(o.created_at) = YEAR(CURDATE()) AND MONTH(o.created_at) = MONTH(CURDATE())"], ['সর্বমোট', "1=1"]] as $pr) {
        $q = $db->query("SELECT COUNT(*) c, COALESCE(SUM(o.cod_amount),0) rev, COALESCE(SUM(o.delivery_charge),0) dch, COALESCE(SUM(p.cost_price),0) cost, COALESCE(SUM(p.cost_price IS NULL),0) nocost
                         FROM orders o LEFT JOIN products p ON p.id = o.product_id
                         WHERE o.is_deleted = 0 AND o.status = 'delivered' AND {$pr[1]}")->fetch();
        $profit_rows[] = ['label' => $pr[0], 'count' => (int)$q['c'], 'rev' => (float)$q['rev'], 'profit' => (float)$q['rev'] - (float)$q['dch'] - (float)$q['cost'], 'nocost' => (int)$q['nocost']];
    }
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md font-semibold">
        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-sack-dollar text-emerald-400"></i> লাভ-ক্ষতি হিসাব (ডেলিভারড অর্ডার)</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <?php foreach ($profit_rows as $pr): ?>
            <div class="bg-slate-900/60 border border-slate-700 rounded-2xl p-4">
                <span class="text-xs text-slate-400 font-bold uppercase"><?= $pr['label'] ?> (<?= number_format($pr['count']) ?> টি ডেলিভারড)</span>
                <div class="mt-2 text-sm text-slate-300">বিক্রি: <b class="text-white font-mono">৳<?= number_format($pr['rev']) ?></b></div>
                <div class="text-2xl font-extrabold mt-1 <?= $pr['profit'] >= 0 ? 'text-emerald-400' : 'text-rose-400' ?>">লাভ: ৳<?= number_format($pr['profit']) ?></div>
                <?php if ($pr['nocost'] > 0): ?><p class="text-[10px] text-amber-400 mt-1"><?= $pr['nocost'] ?> টি অর্ডারের প্রোডাক্টে কেনা দাম দেওয়া নেই</p><?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <p class="text-[10px] text-slate-500 mt-3">হিসাব: COD আদায় − ডেলিভারি চার্জ (কুরিয়ারের অংশ) − প্রোডাক্টের কেনা দাম। প্রোডাক্ট ফর্মে "কেনা দাম" দিলে হিসাব নির্ভুল হবে।</p>
    </div>

    <?php $agents = $db->query("SELECT username, role FROM users ORDER BY id")->fetchAll(); ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md mt-8 font-semibold overflow-x-auto">
        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-user-check text-cyan-400"></i> এজেন্ট পারফরম্যান্স (এই মাস)</h3>
        <table class="w-full text-left text-xs">
            <thead><tr class="text-slate-400 border-b border-slate-700">
                <th class="py-2 px-2">ইউজার</th><th class="py-2 px-2 text-center">কল</th><th class="py-2 px-2 text-center">টকটাইম</th><th class="py-2 px-2 text-center">কনফার্ম</th><th class="py-2 px-2 text-center">ডেলিভারড</th><th class="py-2 px-2 text-center">কনভার্শন</th>
            </tr></thead>
            <tbody>
            <?php foreach ($agents as $ag): $un = $ag['username'];
                $cl = $db->prepare("SELECT COUNT(*) c, COALESCE(SUM(duration_seconds),0) t FROM call_logs WHERE caller_name = ? AND YEAR(started_at)=YEAR(CURDATE()) AND MONTH(started_at)=MONTH(CURDATE())");
                $cl->execute([$un]); $c = $cl->fetch();
                $st2 = $db->prepare("SELECT COALESCE(SUM(status IN ('confirmed','booked','delivered')),0) cf, COALESCE(SUM(status='delivered'),0) dv, COUNT(*) tot FROM orders WHERE updated_by = ? AND is_deleted = 0 AND YEAR(updated_at)=YEAR(CURDATE()) AND MONTH(updated_at)=MONTH(CURDATE())");
                $st2->execute([$un]); $o = $st2->fetch();
                $conv = ($o['tot'] ?? 0) > 0 ? round(($o['cf'] ?? 0) / $o['tot'] * 100) : 0;
            ?>
            <tr class="border-b border-slate-700/50">
                <td class="py-2.5 px-2 font-bold text-white"><?= htmlspecialchars($un) ?> <span class="text-[9px] text-slate-500">(<?= $ag['role'] ?>)</span></td>
                <td class="py-2.5 px-2 text-center font-mono text-slate-300"><?= number_format((int)$c['c']) ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-slate-300"><?= gmdate('H:i:s', (int)$c['t']) ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-emerald-400 font-bold"><?= number_format((int)$o['cf']) ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-sky-400 font-bold"><?= number_format((int)$o['dv']) ?></td>
                <td class="py-2.5 px-2 text-center font-bold <?= $conv >= 50 ? 'text-emerald-400' : 'text-amber-400' ?>"><?= $conv ?>%</td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <p class="text-[10px] text-slate-500 mt-3">"কনফার্ম" = ইউজার যেসব অর্ডার সর্বশেষ আপডেট করে confirmed/booked/delivered করেছে; কল ডেটা ওয়েব ডায়ালারের হিস্টোরি থেকে।</p>
    </div>

    <?php
    // ============ ২. প্রোডাক্টভিত্তিক রিপোর্ট ============
    $prod_report = $db->query("
        SELECT p.title, p.stock,
               COUNT(o.id) total,
               SUM(o.status = 'delivered') delivered,
               SUM(o.status IN ('cancelled','did_not_order')) cancelled,
               COALESCE(SUM(CASE WHEN o.status='delivered' THEN o.cod_amount ELSE 0 END),0) revenue
        FROM products p
        LEFT JOIN orders o ON o.product_id = p.id AND o.is_deleted = 0
        GROUP BY p.id ORDER BY total DESC, revenue DESC LIMIT 30
    ")->fetchAll();
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md mt-8 font-semibold overflow-x-auto">
        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-box-open text-amber-400"></i> প্রোডাক্টভিত্তিক রিপোর্ট</h3>
        <table class="w-full text-left text-xs">
            <thead><tr class="text-slate-400 border-b border-slate-700">
                <th class="py-2 px-2">পণ্য</th><th class="py-2 px-2 text-center">স্টক</th><th class="py-2 px-2 text-center">মোট অর্ডার</th><th class="py-2 px-2 text-center">ডেলিভারড</th><th class="py-2 px-2 text-center">ক্যান্সেল</th><th class="py-2 px-2 text-center">ক্যান্সেল রেট</th><th class="py-2 px-2 text-right">আয় (ডেলিভারড)</th>
            </tr></thead>
            <tbody>
            <?php foreach ($prod_report as $pr): $crate = $pr['total'] > 0 ? round($pr['cancelled']/$pr['total']*100) : 0; ?>
            <tr class="border-b border-slate-700/50">
                <td class="py-2.5 px-2 font-bold text-white"><?= htmlspecialchars($pr['title']) ?></td>
                <td class="py-2.5 px-2 text-center font-mono <?= $pr['stock'] !== null && $pr['stock'] <= 5 ? 'text-rose-400 font-bold' : 'text-slate-300' ?>"><?= $pr['stock'] === null ? '—' : (int)$pr['stock'] ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-white"><?= (int)$pr['total'] ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-emerald-400 font-bold"><?= (int)$pr['delivered'] ?></td>
                <td class="py-2.5 px-2 text-center font-mono text-rose-400"><?= (int)$pr['cancelled'] ?></td>
                <td class="py-2.5 px-2 text-center font-bold <?= $crate >= 40 ? 'text-rose-400' : ($crate >= 20 ? 'text-amber-400' : 'text-emerald-400') ?>"><?= $crate ?>%</td>
                <td class="py-2.5 px-2 text-right font-mono text-emerald-400">৳<?= number_format((float)$pr['revenue']) ?></td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($prod_report)): ?><tr><td colspan="7" class="py-4 text-center text-slate-500">কোনো ডেটা নেই।</td></tr><?php endif; ?>
            </tbody>
        </table>
        <p class="text-[10px] text-slate-500 mt-3">লাল স্টক = ৫ বা কম (রিস্টক দরকার)। ক্যান্সেল রেট ৪০%+ হলে সেই পণ্যের কোয়ালিটি/ছবি/দাম যাচাই করুন।</p>
    </div>

    <?php
    // ============ ৩. ডেলিভারি সাকসেস রেট (জেলাভিত্তিক) ============
    global $zone_to_bangla;
    $final_orders = $db->query("
        SELECT address, status FROM orders
        WHERE is_deleted = 0 AND status IN ('delivered','cancelled','did_not_order')
    ")->fetchAll();
    // জেলা অনুযায়ী গ্রুপ
    $dist_stat = [];
    foreach ($final_orders as $fo) {
        $dist = 'অন্যান্য';
        foreach ($zone_to_bangla as $en_d => $bn_d) {
            if (mb_stripos($fo['address'], $bn_d) !== false || stripos($fo['address'], $en_d) !== false) { $dist = $bn_d; break; }
        }
        if (!isset($dist_stat[$dist])) $dist_stat[$dist] = ['total'=>0,'delivered'=>0];
        $dist_stat[$dist]['total']++;
        if ($fo['status'] === 'delivered') $dist_stat[$dist]['delivered']++;
    }
    // সাজানো: বেশি অর্ডার আগে
    uasort($dist_stat, fn($a,$b) => $b['total'] - $a['total']);
    $dist_stat = array_slice($dist_stat, 0, 20, true);
    // সামগ্রিক
    $g_total = array_sum(array_column($dist_stat, 'total'));
    $g_deliv = array_sum(array_column($dist_stat, 'delivered'));
    $g_rate = $g_total > 0 ? round($g_deliv/$g_total*100) : 0;
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md mt-8 font-semibold">
        <div class="flex items-center justify-between flex-wrap gap-2 border-b border-slate-700 pb-3 mb-4">
            <h3 class="text-lg font-bold text-white flex items-center gap-2"><i class="fa-solid fa-truck-fast text-sky-400"></i> ডেলিভারি সাকসেস রেট (জেলাভিত্তিক)</h3>
            <span class="text-sm">সামগ্রিক: <b class="<?= $g_rate >= 70 ? 'text-emerald-400' : ($g_rate >= 50 ? 'text-amber-400':'text-rose-400') ?>"><?= $g_rate ?>%</b> <span class="text-[10px] text-slate-500">(<?= number_format($g_deliv) ?>/<?= number_format($g_total) ?>)</span></span>
        </div>
        <?php if (empty($dist_stat)): ?>
            <p class="text-sm text-slate-500 text-center py-4">এখনো কোনো ডেলিভারড/ক্যান্সেল অর্ডার নেই।</p>
        <?php else: ?>
        <div class="space-y-2">
            <?php foreach ($dist_stat as $dname => $ds): $rate = $ds['total'] > 0 ? round($ds['delivered']/$ds['total']*100) : 0; ?>
            <div class="flex items-center gap-3">
                <span class="w-24 text-xs text-slate-300 truncate"><?= htmlspecialchars($dname) ?></span>
                <div class="flex-1 bg-slate-900 rounded-full h-5 overflow-hidden relative">
                    <div class="h-full rounded-full <?= $rate >= 70 ? 'bg-emerald-500' : ($rate >= 50 ? 'bg-amber-500':'bg-rose-500') ?>" style="width: <?= max(3,$rate) ?>%"></div>
                    <span class="absolute inset-0 flex items-center px-2 text-[10px] font-bold text-white"><?= $rate ?>% (<?= $ds['delivered'] ?>/<?= $ds['total'] ?>)</span>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <p class="text-[10px] text-slate-500 mt-3">যেসব জেলায় সাকসেস রেট ৫০%-এর নিচে (লাল/হলুদ), সেখানে এডভান্স পেমেন্ট নেওয়া বা কনফার্মেশন কড়া করা যেতে পারে — রিটার্ন লস কমবে।</p>
        <?php endif; ?>
    </div>

    <?php
    // ============ ৪. কাস্টমার লয়াল্টি / রিপিট রিপোর্ট ============
    $loyal = $db->query("
        SELECT customer_name, phone,
               COUNT(*) orders,
               SUM(status = 'delivered') delivered,
               COALESCE(SUM(CASE WHEN status='delivered' THEN cod_amount ELSE 0 END),0) spent,
               MAX(created_at) last_order
        FROM orders WHERE is_deleted = 0
        GROUP BY phone HAVING orders >= 2
        ORDER BY orders DESC, spent DESC LIMIT 30
    ")->fetchAll();
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md mt-8 mb-4 font-semibold overflow-x-auto">
        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3"><i class="fa-solid fa-heart text-rose-400"></i> রিপিট কাস্টমার (২+ বার অর্ডার করেছে)</h3>
        <?php if (empty($loyal)): ?>
            <p class="text-sm text-slate-500 text-center py-4">এখনো কোনো রিপিট কাস্টমার নেই (একই নম্বরে ২+ অর্ডার হলে এখানে আসবে)।</p>
        <?php else: ?>
        <table class="w-full text-left text-xs">
            <thead><tr class="text-slate-400 border-b border-slate-700">
                <th class="py-2 px-2">কাস্টমার</th><th class="py-2 px-2">ফোন</th><th class="py-2 px-2 text-center">মোট অর্ডার</th><th class="py-2 px-2 text-center">ডেলিভারড</th><th class="py-2 px-2 text-right">মোট কিনেছে</th><th class="py-2 px-2">শেষ অর্ডার</th><th class="py-2 px-2 text-center">WA</th>
            </tr></thead>
            <tbody>
            <?php foreach ($loyal as $lc): ?>
            <tr class="border-b border-slate-700/50">
                <td class="py-2.5 px-2 font-bold text-white"><?= htmlspecialchars($lc['customer_name']) ?></td>
                <td class="py-2.5 px-2 font-mono text-slate-400"><?= htmlspecialchars($lc['phone']) ?></td>
                <td class="py-2.5 px-2 text-center"><span class="bg-rose-500/20 text-rose-300 px-2 py-0.5 rounded-full font-bold"><?= (int)$lc['orders'] ?></span></td>
                <td class="py-2.5 px-2 text-center font-mono text-emerald-400"><?= (int)$lc['delivered'] ?></td>
                <td class="py-2.5 px-2 text-right font-mono text-emerald-400 font-bold">৳<?= number_format((float)$lc['spent']) ?></td>
                <td class="py-2.5 px-2 text-[10px] text-slate-400"><?= date('d M Y', strtotime($lc['last_order'])) ?></td>
                <td class="py-2.5 px-2 text-center"><a href="https://wa.me/<?= wa_number($lc['phone']) ?>" target="_blank" class="text-emerald-400 hover:text-emerald-300"><i class="fa-brands fa-whatsapp"></i></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        <p class="text-[10px] text-slate-500 mt-3">এরা আপনার সবচেয়ে মূল্যবান কাস্টমার — নতুন অফার/ছাড়ে এদের WhatsApp করতে পারেন। রিপিট কাস্টমার ধরে রাখা নতুন কাস্টমার আনার চেয়ে সস্তা।</p>
        <?php endif; ?>
    </div>
    <?php
    render_dashboard_footer();
    exit;
}

if ($action === 'fraud_detection') {
    require_admin_or_office();

    $fd_msg = null;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // সেভ/রিমুভ শেষে একই লিংকে রিডাইরেক্ট (রিফ্রেশে ডাবল-সাবমিট হবে না)
        if (isset($_POST['add_block'])) {
            $b_phone = trim(bnToEnNumber($_POST['block_phone'] ?? ''));
            $b_ip = trim($_POST['block_ip'] ?? '');
            $b_reason = trim($_POST['block_reason'] ?? '');
            if ($b_phone === '' && $b_ip === '') {
                header("Location: ?action=fraud_detection&fdmsg=need_input");
                exit;
            }
            $chk = $db->prepare("SELECT COUNT(*) FROM blocked_customers WHERE phone = ? AND ip = ?");
            $chk->execute([$b_phone, $b_ip]);
            if ($chk->fetchColumn() > 0) {
                header("Location: ?action=fraud_detection&fdmsg=exists");
                exit;
            }
            $ins = $db->prepare("INSERT INTO blocked_customers (phone, ip, reason, blocked_by) VALUES (?, ?, ?, ?)");
            $ins->execute([$b_phone, $b_ip, $b_reason, $_SESSION['username']]);
            header("Location: ?action=fraud_detection&fdmsg=blocked");
            exit;
        }
        if (isset($_POST['remove_block'])) {
            $bid = (int)$_POST['block_id'];
            $db->prepare("DELETE FROM blocked_customers WHERE id = ?")->execute([$bid]);
            header("Location: ?action=fraud_detection&fdmsg=unblocked");
            exit;
        }
        // ফ্রড রিস্ক থ্রেশহোল্ড + এডভান্স পেমেন্ট সেটিংস সেভ
        if (isset($_POST['save_fraud_settings'])) {
            $th = (int)bnToEnNumber($_POST['fraud_block_threshold'] ?? '0');
            if ($th < 0) $th = 0; if ($th > 100) $th = 100;
            update_setting('fraud_block_threshold', (string)$th);
            $amt = (int)bnToEnNumber($_POST['advance_amount'] ?? '150');
            update_setting('advance_amount', (string)($amt > 0 ? $amt : 150));
            update_setting('advance_bkash', trim(bnToEnNumber($_POST['advance_bkash'] ?? '')));
            update_setting('advance_nagad', trim(bnToEnNumber($_POST['advance_nagad'] ?? '')));
            update_setting('support_whatsapp', trim(bnToEnNumber($_POST['support_whatsapp'] ?? '')));
            $brh = (int)bnToEnNumber($_POST['block_repeat_hours'] ?? '24');
            if ($brh < 0) $brh = 0;
            update_setting('block_repeat_hours', (string)$brh);
            header("Location: ?action=fraud_detection&fdmsg=settings_saved");
            exit;
        }
    }
    $fd_msg_map = [
        'blocked'    => ['type' => 'success', 'text' => 'কাস্টমার সফলভাবে ব্লক করা হয়েছে!'],
        'unblocked'  => ['type' => 'success', 'text' => 'ব্লক সফলভাবে রিমুভ করা হয়েছে!'],
        'exists'     => ['type' => 'error', 'text' => 'এই নাম্বার/আইপি ইতিমধ্যে ব্লক তালিকায় আছে।'],
        'need_input' => ['type' => 'error', 'text' => 'মোবাইল নাম্বার অথবা আইপি — যেকোনো একটি অবশ্যই দিতে হবে।'],
        'settings_saved' => ['type' => 'success', 'text' => 'ফ্রড রিস্ক ও এডভান্স পেমেন্ট সেটিংস সেভ হয়েছে!'],
    ];
    if (isset($_GET['fdmsg'], $fd_msg_map[$_GET['fdmsg']])) $fd_msg = $fd_msg_map[$_GET['fdmsg']];

    $blocked_list = $db->query("SELECT * FROM blocked_customers ORDER BY id DESC")->fetchAll();
    render_dashboard_header("ফ্রড ডিটেকশন");
    render_fraud_detection_panel($blocked_list, $fd_msg);
    render_dashboard_footer();
    exit;
}

// Quick block from order detail page
if ($action === 'quick_block' && isset($_GET['phone'])) {
    require_admin_or_office();
    header('Content-Type: application/json');
    $b_phone = trim(bnToEnNumber($_GET['phone']));
    $b_ip = trim($_GET['ip'] ?? '');
    if ($b_phone === '' && $b_ip === '') {
        echo json_encode(['status' => 'error', 'message' => 'নাম্বার/আইপি পাওয়া যায়নি।'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $chk = $db->prepare("SELECT COUNT(*) FROM blocked_customers WHERE phone = ? AND ip = ?");
    $chk->execute([$b_phone, $b_ip]);
    if ($chk->fetchColumn() == 0) {
        $ins = $db->prepare("INSERT INTO blocked_customers (phone, ip, reason, blocked_by) VALUES (?, ?, ?, ?)");
        $ins->execute([$b_phone, $b_ip, 'Quick block from order panel', $_SESSION['username']]);
    }
    echo json_encode(['status' => 'success', 'message' => 'কাস্টমার ব্লক তালিকায় যুক্ত হয়েছে!'], JSON_UNESCAPED_UNICODE);
    exit;
}

// -------------------------------------------------------------
// Feature 13: INCOMPLETE ORDER TRACKING TAB
// -------------------------------------------------------------

if ($action === 'incomplete_orders') {
    require_login();

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_incomplete']) && get_user_role() !== 'agent') {
        $iid = (int)$_POST['incomplete_id'];
        $db->prepare("DELETE FROM incomplete_orders WHERE id = ?")->execute([$iid]);
    }

    // শিফট হেল্পার — ইনকমপ্লিট রো থেকে নতুন অর্ডার তৈরি (single + bulk দুই জায়গায় ব্যবহৃত)
    $shift_incomplete_row = function ($inc_row) use ($db) {
        if (trim((string)$inc_row['phone']) === '') return 0;
        $shift_cod = 0;
        if (!empty($inc_row['product_id'])) {
            $pst = $db->prepare("SELECT price, sale_price FROM products WHERE id = ?");
            $pst->execute([(int)$inc_row['product_id']]);
            if ($pp = $pst->fetch()) {
                $shift_cod = ($pp['sale_price'] !== null && $pp['sale_price'] > 0) ? $pp['sale_price'] : $pp['price'];
            }
        }
        $note_txt = 'ইনকমপ্লিট অর্ডার থেকে শিফট করা হয়েছে (' . ($_SESSION['username'] ?? '') . ')';
        $ins = $db->prepare("INSERT INTO orders (customer_name, phone, address, product_id, cod_amount, status, is_deleted, customer_ip, note)
                             VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?)");
        $ins->execute([
            trim((string)$inc_row['customer_name']) !== '' ? $inc_row['customer_name'] : 'ইনকমপ্লিট কাস্টমার',
            $inc_row['phone'],
            trim((string)$inc_row['address']) !== '' ? $inc_row['address'] : '(ঠিকানা দেওয়া হয়নি — কাস্টমারকে কল করুন)',
            $inc_row['product_id'] ?: null,
            $shift_cod,
            $inc_row['customer_ip'] ?: null,
            $note_txt
        ]);
        $new_oid = (int)$db->lastInsertId();
        $db->prepare("DELETE FROM incomplete_orders WHERE id = ?")->execute([(int)$inc_row['id']]);
        return $new_oid;
    };

    // ১ ক্লিকে: যেসব এন্ট্রির নাম্বারে সফল অর্ডার আছে (সবুজ সারি) — সব ডিলিট
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_matched_incomplete']) && get_user_role() !== 'agent') {
        $all_inc = $db->query("SELECT id, phone FROM incomplete_orders")->fetchAll();
        $normf = function ($ph) { $c = preg_replace('/\D/', '', bnToEnNumber((string)$ph)); return strlen($c) > 11 ? substr($c, -11) : $c; };
        $mst2 = $db->prepare("SELECT id FROM orders WHERE is_deleted = 0 AND REPLACE(REPLACE(REPLACE(phone, '-', ''), ' ', ''), '+', '') LIKE ? LIMIT 1");
        $deleted_cnt = 0;
        foreach ($all_inc as $ir) {
            $np = $normf($ir['phone'] ?? '');
            if ($np === '' || strlen($np) < 6) continue;
            $mst2->execute(['%' . $np]);
            if ($mst2->fetch()) {
                $db->prepare("DELETE FROM incomplete_orders WHERE id = ?")->execute([(int)$ir['id']]);
                $deleted_cnt++;
            }
        }
        header("Location: ?action=incomplete_orders&bulk_done=" . $deleted_cnt . "&bulk_act=delete");
        exit;
    }

    // Bulk অ্যাকশন: একসাথে শিফট / ডিলিট
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_incomplete'])) {
        $bulk_ids = array_filter(array_map('intval', explode(',', $_POST['bulk_ids'] ?? '')));
        $bulk_act = $_POST['bulk_action'] ?? '';
        $done = 0;
        if (!empty($bulk_ids)) {
            if ($bulk_act === 'delete' && get_user_role() !== 'agent') {
                foreach ($bulk_ids as $bid) {
                    $db->prepare("DELETE FROM incomplete_orders WHERE id = ?")->execute([$bid]);
                    $done++;
                }
            } elseif ($bulk_act === 'shift') {
                foreach ($bulk_ids as $bid) {
                    $ist = $db->prepare("SELECT * FROM incomplete_orders WHERE id = ?");
                    $ist->execute([$bid]);
                    if ($row = $ist->fetch()) {
                        if ($shift_incomplete_row($row) > 0) $done++;
                    }
                }
            }
        }
        header("Location: ?action=incomplete_orders&bulk_done=" . $done . "&bulk_act=" . urlencode($bulk_act));
        exit;
    }

    // ইনকমপ্লিট → অর্ডার তালিকায় শিফট (নতুন অর্ডার হিসেবে কাউন্ট হবে)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['shift_to_order'])) {
        $iid = (int)$_POST['incomplete_id'];
        $ist = $db->prepare("SELECT * FROM incomplete_orders WHERE id = ?");
        $ist->execute([$iid]);
        if ($inc_row = $ist->fetch()) {
            if (trim((string)$inc_row['phone']) === '') {
                header("Location: ?action=incomplete_orders&msg=no_phone");
                exit;
            }
            // প্রোডাক্ট থাকলে তার দাম দিয়ে COD সেট
            $shift_cod = 0;
            if (!empty($inc_row['product_id'])) {
                $pst = $db->prepare("SELECT price, sale_price FROM products WHERE id = ?");
                $pst->execute([(int)$inc_row['product_id']]);
                if ($pp = $pst->fetch()) {
                    $shift_cod = ($pp['sale_price'] !== null && $pp['sale_price'] > 0) ? $pp['sale_price'] : $pp['price'];
                }
            }
            $note_txt = 'ইনকমপ্লিট অর্ডার থেকে শিফট করা হয়েছে (' . ($_SESSION['username'] ?? '') . ')';
            $ins = $db->prepare("INSERT INTO orders (customer_name, phone, address, product_id, cod_amount, status, is_deleted, customer_ip, note)
                                 VALUES (?, ?, ?, ?, ?, 'pending', 0, ?, ?)");
            $ins->execute([
                trim((string)$inc_row['customer_name']) !== '' ? $inc_row['customer_name'] : 'ইনকমপ্লিট কাস্টমার',
                $inc_row['phone'],
                trim((string)$inc_row['address']) !== '' ? $inc_row['address'] : '(ঠিকানা দেওয়া হয়নি — কাস্টমারকে কল করুন)',
                $inc_row['product_id'] ?: null,
                $shift_cod,
                $inc_row['customer_ip'] ?: null,
                $note_txt
            ]);
            $new_oid = (int)$db->lastInsertId();
            $db->prepare("DELETE FROM incomplete_orders WHERE id = ?")->execute([$iid]);
            header("Location: ?action=order_detail&id=" . $new_oid . "&msg=shifted");
            exit;
        }
        header("Location: ?action=incomplete_orders");
        exit;
    }

    $incompletes = $db->query("SELECT i.*, p.title AS product_title FROM incomplete_orders i LEFT JOIN products p ON i.product_id = p.id ORDER BY i.updated_at DESC, i.id DESC LIMIT 300")->fetchAll();

    // অটো-ম্যাচ: প্রতিটি ইনকমপ্লিট এন্ট্রির নাম্বার ধরে অর্ডার তালিকায় খোঁজা —
    // অর্ডার পাওয়া গেলে সেই সারি সবুজ হাইলাইট হবে (অর্ডার সফল হয়েছে বোঝাতে)
    $matched_orders = []; // normalized_phone => ['id'=>.., 'status'=>.., 'created_at'=>..]
    $norm = function ($ph) { $c = preg_replace('/\D/', '', bnToEnNumber((string)$ph)); return strlen($c) > 11 ? substr($c, -11) : $c; };
    $uniq_phones = [];
    foreach ($incompletes as $inc_row) {
        $np = $norm($inc_row['phone'] ?? '');
        if ($np !== '' && strlen($np) >= 6) $uniq_phones[$np] = true;
    }
    if (!empty($uniq_phones)) {
        $mst = $db->prepare("SELECT id, status, created_at FROM orders WHERE is_deleted = 0 AND REPLACE(REPLACE(REPLACE(phone, '-', ''), ' ', ''), '+', '') LIKE ? ORDER BY id DESC LIMIT 1");
        foreach (array_keys($uniq_phones) as $np) {
            $mst->execute(['%' . $np]);
            if ($m = $mst->fetch()) {
                $matched_orders[$np] = $m;
            }
        }
    }

    render_dashboard_header("ইনকমপ্লিট অর্ডার ট্র্যাকিং");
    render_incomplete_panel($incompletes, $matched_orders);
    render_dashboard_footer();
    exit;
}

// -------------------------------------------------------------
// WEB DIALER: CALL LOG SAVE / LIST / DELETE (+30 দিন অটো ক্লিনআপ)
// -------------------------------------------------------------

function cleanup_old_call_logs($db) {
    // ৩০ দিনের পুরোনো রেকর্ডিং ফাইল + লগ স্বয়ংক্রিয়ভাবে ডিলিট
    try {
        $old = $db->query("SELECT id, recording_path FROM call_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)")->fetchAll();
        foreach ($old as $row) {
            if (!empty($row['recording_path']) && file_exists($row['recording_path'])) {
                @unlink($row['recording_path']);
            }
            $db->prepare("DELETE FROM call_logs WHERE id = ?")->execute([$row['id']]);
        }
    } catch (Exception $e) {}
}

if ($action === 'call_log_save') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    cleanup_old_call_logs($db);

    $phone      = trim($_POST['phone'] ?? '');
    $duration   = max(0, (int)($_POST['duration_seconds'] ?? 0));
    $started_at = trim($_POST['started_at'] ?? '');
    $order_id   = (int)($_POST['order_id'] ?? 0);
    $cust_name  = trim($_POST['customer_name'] ?? '');
    $status     = trim($_POST['call_status'] ?? 'completed');
    if (!in_array($status, ['completed', 'failed', 'no_answer', 'cancelled'])) $status = 'completed';
    $direction  = trim($_POST['direction'] ?? 'outgoing');
    if (!in_array($direction, ['incoming', 'outgoing'])) $direction = 'outgoing';

    if ($phone === '') { echo json_encode(['status' => 'error', 'message' => 'ফোন নাম্বার পাওয়া যায়নি']); exit; }
    if ($started_at === '' || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $started_at)) {
        $started_at = date('Y-m-d H:i:s');
    }

    // অর্ডার আইডি / কাস্টমার নাম না দেওয়া থাকলে ফোন নাম্বার দিয়ে সর্বশেষ অর্ডার থেকে খুঁজে নেওয়া
    if (!$order_id || $cust_name === '') {
        try {
            $clean = preg_replace('/\D/', '', $phone);
            $last11 = strlen($clean) > 11 ? substr($clean, -11) : $clean;
            if ($last11 !== '') {
                $st = $db->prepare("SELECT id, customer_name FROM orders WHERE REPLACE(REPLACE(phone,'-',''),' ','') LIKE ? ORDER BY id DESC LIMIT 1");
                $st->execute(['%' . $last11]);
                if ($o = $st->fetch()) {
                    if (!$order_id) $order_id = (int)$o['id'];
                    if ($cust_name === '') $cust_name = $o['customer_name'];
                }
            }
        } catch (Exception $e) {}
    }

    // রেকর্ডিং ফাইল সেভ (auto save)
    $rec_path = null; $rec_url = null;
    if (!empty($_FILES['recording']) && $_FILES['recording']['error'] === UPLOAD_ERR_OK && $_FILES['recording']['size'] > 0) {
        if (!is_dir(REC_DIR)) @mkdir(REC_DIR, 0755, true);
        if (is_dir(REC_DIR) && is_writable(REC_DIR)) {
            if ($_FILES['recording']['size'] <= 60 * 1024 * 1024) { // সর্বোচ্চ ৬০MB
                $ext = 'webm';
                $mt = strtolower($_FILES['recording']['type'] ?? '');
                if (strpos($mt, 'ogg') !== false) $ext = 'ogg';
                elseif (strpos($mt, 'mp4') !== false || strpos($mt, 'm4a') !== false) $ext = 'm4a';
                $fname = 'rec_' . date('Ymd_His') . '_' . substr(bin2hex(random_bytes(4)), 0, 8) . '.' . $ext;
                $target = REC_DIR . '/' . $fname;
                if (@move_uploaded_file($_FILES['recording']['tmp_name'], $target)) {
                    $rec_path = $target;
                    $rec_url  = rtrim(base_url(), '/') . '/uploads/recordings/' . $fname;
                }
            }
        }
    }

    try {
        $st = $db->prepare("INSERT INTO call_logs (caller_id, caller_name, caller_role, direction, phone, customer_name, order_id, started_at, duration_seconds, call_status, recording_path, recording_url)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $st->execute([
            (int)($_SESSION['user_id'] ?? 0),
            $_SESSION['username'] ?? 'Unknown',
            get_user_role(),
            $direction,
            $phone,
            $cust_name ?: null,
            $order_id ?: null,
            $started_at,
            $duration,
            $status,
            $rec_path,
            $rec_url
        ]);
        echo json_encode(['status' => 'success', 'id' => $db->lastInsertId(), 'recording_url' => $rec_url]);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'লগ সেভ করা যায়নি']);
    }
    exit;
}

if ($action === 'call_log_list') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    cleanup_old_call_logs($db);
    try {
        $logs = $db->query("SELECT id, caller_id, caller_name, caller_role, direction, phone, customer_name, order_id,
                                   DATE_FORMAT(started_at, '%Y-%m-%d') AS call_date,
                                   DATE_FORMAT(started_at, '%h:%i %p') AS call_time,
                                   duration_seconds, call_status, recording_url, created_at
                            FROM call_logs ORDER BY id DESC LIMIT 300")->fetchAll(PDO::FETCH_ASSOC);
        $tot = $db->query("SELECT COUNT(*) AS total_calls, COALESCE(SUM(duration_seconds),0) AS total_talk FROM call_logs")->fetch();
        echo json_encode([
            'status' => 'success',
            'logs' => $logs,
            'total_calls' => (int)$tot['total_calls'],
            'total_talk_seconds' => (int)$tot['total_talk'],
            'my_user_id' => (int)($_SESSION['user_id'] ?? 0),
            'my_role' => get_user_role()
        ], JSON_UNESCAPED_UNICODE);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'লিস্ট লোড করা যায়নি']);
    }
    exit;
}

if ($action === 'call_log_delete') {
    require_login();
    header('Content-Type: application/json; charset=utf-8');
    $id = (int)($_POST['id'] ?? 0);
    try {
        $st = $db->prepare("SELECT * FROM call_logs WHERE id = ?");
        $st->execute([$id]);
        $log = $st->fetch();
        if (!$log) { echo json_encode(['status' => 'error', 'message' => 'লগ পাওয়া যায়নি']); exit; }
        $role = get_user_role();
        // শুধু অ্যাডমিন সব ডিলিট করতে পারবে; বাকিরা (অফিস/এজেন্ট) শুধু নিজের কল
        if ($role !== 'admin' && (int)$log['caller_id'] !== (int)($_SESSION['user_id'] ?? 0)) {
            echo json_encode(['status' => 'error', 'message' => 'কল রেকর্ডিং শুধু অ্যাডমিন অথবা যে ইউজার কল করেছে সে-ই ডিলিট করতে পারবে']); exit;
        }
        if (!empty($log['recording_path']) && file_exists($log['recording_path'])) @unlink($log['recording_path']);
        $db->prepare("DELETE FROM call_logs WHERE id = ?")->execute([$id]);
        echo json_encode(['status' => 'success']);
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'message' => 'ডিলিট করা যায়নি']);
    }
    exit;
}

// -------------------------------------------------------------
// Feature 7: SIP DIALER CONFIGURATION TAB
// -------------------------------------------------------------

if ($action === 'sip_dialer') {
    require_login();

    $sip_msg = null;
    $sip_keys = ['dialer_mode', 'sip_wss_url', 'sip_username', 'sip_password', 'sip_domain', 'sip_port', 'sip_transport', 'sip_proxy', 'sip_dtmf', 'sip_stun', 'sip_reg_interval', 'sip_portal_url', 'sip_balance_code'];

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // SIP কনফিগারেশন শুধু অ্যাডমিন পরিবর্তন করতে পারবে
        if (get_user_role() === 'admin') {
            if (isset($_POST['reset_sip'])) {
                update_setting('dialer_mode', 'tel');
                update_setting('sip_wss_url', '');
                update_setting('sip_username', '');
                update_setting('sip_password', '');
                update_setting('sip_domain', '');
                update_setting('sip_port', '5060');
                update_setting('sip_transport', 'UDP');
                update_setting('sip_proxy', '');
                update_setting('sip_dtmf', 'RFC2833');
                update_setting('sip_stun', 'stun.l.google.com:19302');
                update_setting('sip_reg_interval', '60');
                update_setting('sip_portal_url', 'https://webvoice.net');
                update_setting('sip_balance_code', '123');
                $sip_msg = ['type' => 'success', 'text' => 'SIP কনফিগারেশন ডিফল্টে রিসেট করা হয়েছে!'];
            } elseif (isset($_POST['save_sip'])) {
                foreach ($sip_keys as $k) {
                    if (isset($_POST[$k])) {
                        update_setting($k, trim($_POST[$k]));
                    }
                }
                $sip_msg = ['type' => 'success', 'text' => 'SIP ডায়ালার কনফিগারেশন সফলভাবে সেভ করা হয়েছে!'];
            }
        } else {
            $sip_msg = ['type' => 'error', 'text' => 'শুধুমাত্র অ্যাডমিন SIP কনফিগারেশন পরিবর্তন করতে পারবেন।'];
        }
    }

    render_dashboard_header("SIP ডায়ালার সেটিংস");
    render_sip_dialer_panel($sip_msg);
    render_dashboard_footer();
    exit;
}

// -------------------------------------------------------------
// Feature 16: BRANDING TAB
// -------------------------------------------------------------

if ($action === 'branding') {
    require_admin();

    $br_msg = null;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // ফর্ম ফিল্ড brand_* নামে আসে — দুই নামই সাপোর্ট করা হলো
        update_setting('site_name', trim($_POST['brand_site_name'] ?? $_POST['site_name'] ?? 'SunnahTi') ?: 'SunnahTi');
        update_setting('site_title', trim($_POST['brand_site_title'] ?? $_POST['site_title'] ?? ''));
        update_setting('home_url', trim($_POST['brand_home_url'] ?? $_POST['home_url'] ?? ''));
        update_setting('favicon_url', trim($_POST['brand_favicon_url'] ?? $_POST['favicon_url'] ?? ''));
        update_setting('logo_url', trim($_POST['brand_logo_url'] ?? $_POST['logo_url'] ?? ''));
        $br_msg = 'ব্র্যান্ডিং সেটিংস সফলভাবে আপডেট করা হয়েছে! লগইন পেজ, ড্যাশবোর্ড, ল্যান্ডিং পেজ ও ইনভয়েস — সব জায়গায় নতুন নাম প্রদর্শিত হবে।';
    }

    render_dashboard_header("সাইট ব্র্যান্ডিং");
    render_branding_panel($br_msg);
    render_dashboard_footer();
    exit;
}

// -------------------------------------------------------------
// Feature 20: DUPLICATE LANDING PAGE
// -------------------------------------------------------------

if ($action === 'duplicate_page' && isset($_GET['id'])) {
    require_admin();
    $pid = (int)$_GET['id'];
    $stmt = $db->prepare("SELECT * FROM pages WHERE id = ?");
    $stmt->execute([$pid]);
    $pg = $stmt->fetch();
    if ($pg) {
        $new_slug = $pg['slug'] . '-copy-' . substr((string)time(), -5);
        $new_title = $pg['title'] . ' (কপি)';
        $ins = $db->prepare("INSERT INTO pages (title, slug, content, bottom_content, seo_title, seo_desc, product_ids, checkout_fields, variant_config, og_image, builder_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $ins->execute([$new_title, $new_slug, $pg['content'], $pg['bottom_content'], $pg['seo_title'], $pg['seo_desc'], $pg['product_ids'], $pg['checkout_fields'], $pg['variant_config'] ?? null, $pg['og_image'] ?? null, $pg['builder_json'] ?? null]);
    }
    header("Location: ?action=pages&msg=duplicated");
    exit;
}

if ($action === 'duplicate_product' && isset($_GET['id'])) {
    require_admin();
    $pid = (int)$_GET['id'];
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$pid]);
    $p = $stmt->fetch();
    if ($p) {
        $new_slug = $p['slug'] . '-copy-' . substr((string)time(), -5);
        $new_title = $p['title'] . ' (কপি)';
        $ins = $db->prepare("INSERT INTO products (title, slug, price, sale_price, description, image_url, checkout_fields, variant_options, stock, category_id, og_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $ins->execute([$new_title, $new_slug, $p['price'], $p['sale_price'], $p['description'], $p['image_url'], $p['checkout_fields'], $p['variant_options'], $p['stock'], $p['category_id'] ?? null, $p['og_image'] ?? null]);
    }
    header("Location: ?action=products&msg=duplicated");
    exit;
}

// -------------------------------------------------------------
// DASHBOARD (Feature 1: Pagination + Feature 5: Agent call-first ordering
//            + Feature 12: Loyal customer ranks + Feature 15: AJAX table)
// -------------------------------------------------------------

if ($action === 'dashboard') {
    $today_date = date('Y-m-d');
    $total_orders = $db->query("SELECT COUNT(*) FROM orders WHERE is_deleted = 0")->fetchColumn();
    $pending_orders = $db->query("SELECT COUNT(*) FROM orders WHERE status = 'pending' AND is_deleted = 0")->fetchColumn();
    $delivered_orders = $db->query("SELECT COUNT(*) FROM orders WHERE status = 'delivered' AND is_deleted = 0")->fetchColumn();
    $today_sales = $db->query("SELECT SUM(cod_amount) FROM orders WHERE DATE(created_at) = '$today_date' AND is_deleted = 0")->fetchColumn() ?: 0;
    // Feature 4: Total sold amount (confirmed + booked + delivered)
    $total_sales = $db->query("SELECT SUM(cod_amount) FROM orders WHERE status IN ('confirmed','booked','delivered') AND is_deleted = 0")->fetchColumn() ?: 0;
    $deleted_orders_count = $db->query("SELECT COUNT(*) FROM orders WHERE is_deleted = 1")->fetchColumn();

    $search = trim($_GET['search'] ?? '');
    $status_filter = trim($_GET['status_filter'] ?? '');
    $date_filter = trim($_GET['date_filter'] ?? '');
    $start_date = trim($_GET['start_date'] ?? '');
    $end_date = trim($_GET['end_date'] ?? '');

    $product_filter = isset($_GET['product_filter']) ? (int)$_GET['product_filter'] : 0;
    $color_filter = isset($_GET['color_filter']) ? trim($_GET['color_filter']) : '';
    $zone_filter = isset($_GET['zone_filter']) ? trim($_GET['zone_filter']) : '';
    $courier_filter = isset($_GET['courier_filter']) ? trim($_GET['courier_filter']) : '';

    // Feature 1: pagination inputs (25 / 50 / 100 per page)
    $per_page = (int)($_GET['per_page'] ?? 100);
    if (!in_array($per_page, [25, 50, 100])) $per_page = 100;
    $page = max(1, (int)($_GET['page'] ?? 1));

    $params = [];

    if ($status_filter === 'deleted') {
        $where = "WHERE o.is_deleted = 1";
    } else {
        $where = "WHERE o.is_deleted = 0";
        if (!empty($status_filter)) {
            $where .= " AND o.status = ?";
            $params[] = $status_filter;
        }
    }

    // কুরিয়ার স্ট্যাটাস ফিল্টার (স্টিডফাস্ট থেকে সিঙ্ক হওয়া স্ট্যাটাস অনুযায়ী)
    if ($courier_filter !== '') {
        if ($courier_filter === 'zone_not_clear') {
            $where .= " AND (o.delivery_zone IS NULL OR o.delivery_zone = '')";
        } elseif ($courier_filter === 'not_booked') {
            $where .= " AND (o.consignment_id IS NULL OR o.consignment_id = '')";
        } elseif ($courier_filter === 'no_status') {
            $where .= " AND o.consignment_id IS NOT NULL AND o.consignment_id != '' AND (o.courier_status IS NULL OR o.courier_status = '')";
        } elseif ($courier_filter === 'approval_any') {
            $where .= " AND o.courier_status LIKE '%approval%'";
        } else {
            $where .= " AND o.courier_status = ?";
            $params[] = $courier_filter;
        }
    }

    if (!empty($search)) {
        $where .= " AND (o.customer_name LIKE ? OR o.phone LIKE ? OR o.id = ? OR o.tracking_code LIKE ? OR o.address LIKE ? OR o.consignment_id LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = $search;
        $params[] = "%$search%";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    if (!empty($date_filter)) {
        if ($date_filter === 'today') {
            $where .= " AND DATE(o.created_at) = CURRENT_DATE()";
        } elseif ($date_filter === 'yesterday') {
            $where .= " AND DATE(o.created_at) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)";
        } elseif ($date_filter === 'day_before') {
            $where .= " AND DATE(o.created_at) = DATE_SUB(CURRENT_DATE(), INTERVAL 2 DAY)";
        } elseif ($date_filter === 'last_7') {
            $where .= " AND o.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        } elseif ($date_filter === 'last_30') {
            $where .= " AND o.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        } elseif ($date_filter === 'custom' && !empty($start_date) && !empty($end_date)) {
            $where .= " AND DATE(o.created_at) BETWEEN ? AND ?";
            $params[] = $start_date;
            $params[] = $end_date;
        }
    }

    if ($product_filter > 0) {
        $where .= " AND o.product_id = ?";
        $params[] = $product_filter;
    }

    if (!empty($color_filter)) {
        $where .= " AND o.color_selected = ?";
        $params[] = $color_filter;
    }

    if (!empty($zone_filter)) {
        if (isset($zone_to_bangla[$zone_filter])) {
            $bn_dist = $zone_to_bangla[$zone_filter];
            $where .= " AND (o.address LIKE ? OR o.address LIKE ?)";
            $params[] = "%" . $zone_filter . "%";
            $params[] = "%" . $bn_dist . "%";
        }
    }

    // Total count for pagination (with the same filter conditions)
    $count_stmt = $db->prepare("SELECT COUNT(*) FROM orders o LEFT JOIN products p ON o.product_id = p.id $where");
    $count_stmt->execute($params);
    $total_filtered = (int)$count_stmt->fetchColumn();
    $total_pages = max(1, (int)ceil($total_filtered / $per_page));
    if ($page > $total_pages) $page = $total_pages;
    $offset = ($page - 1) * $per_page;

    // Feature 5: Calling agents see pending calls first (today, then yesterday,
    // then older), then "no answer", then everything else.
    if (get_user_role() === 'agent' && empty($status_filter)) {
        $order_by = "ORDER BY CASE
                        WHEN o.status = 'pending' AND DATE(o.created_at) = CURRENT_DATE() THEN 0
                        WHEN o.status = 'pending' AND DATE(o.created_at) = DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY) THEN 1
                        WHEN o.status = 'pending' THEN 2
                        WHEN o.status = 'no_answer' THEN 3
                        ELSE 4
                     END ASC, o.id DESC";
    } else {
        $order_by = "ORDER BY o.id DESC";
    }

    $stmt = $db->prepare("SELECT o.*, p.title as product_title FROM orders o LEFT JOIN products p ON o.product_id = p.id $where $order_by LIMIT $per_page OFFSET $offset");
    $stmt->execute($params);
    $orders = $stmt->fetchAll();

    // Feature 12: Loyal customer rank map (কততম বার অর্ডার) + phone total counts
    $order_rank = [];
    $phone_totals = [];
    $phones = array_values(array_unique(array_filter(array_column($orders, 'phone'))));
    if (!empty($phones)) {
        $ph = implode(',', array_fill(0, count($phones), '?'));
        $rstmt = $db->prepare("SELECT id, phone FROM orders WHERE phone IN ($ph) AND is_deleted = 0 ORDER BY id ASC");
        $rstmt->execute($phones);
        $cnt = [];
        foreach ($rstmt->fetchAll() as $r) {
            $cnt[$r['phone']] = ($cnt[$r['phone']] ?? 0) + 1;
            $order_rank[$r['id']] = $cnt[$r['phone']];
        }
        $phone_totals = $cnt;
    }

    // Feature 15: AJAX mode — return only the orders table (no full page reload)
    if (isset($_GET['ajax'])) {
        render_orders_table($orders, $search, $status_filter, $date_filter, $start_date, $end_date, $product_filter, $color_filter, $zone_filter, $page, $per_page, $total_filtered, $total_pages, $order_rank, $phone_totals, $courier_filter);
        exit;
    }

    render_dashboard_header("ড্যাশবোর্ড");
    $incomplete_count = 0;
    try { $incomplete_count = (int)$db->query("SELECT COUNT(*) FROM incomplete_orders")->fetchColumn(); } catch (Exception $e) {}
    // লো-স্টক অ্যালার্ট
    $low_stock = [];
    try { $low_stock = $db->query("SELECT title, stock FROM products WHERE stock IS NOT NULL AND stock <= 5 ORDER BY stock ASC LIMIT 10")->fetchAll(); } catch (Exception $e) {}
    if (!empty($low_stock)) {
        echo '<div class="bg-rose-950/40 border border-rose-700 rounded-2xl px-5 py-3.5 mb-5 text-sm font-semibold flex items-start gap-3">';
        echo '<i class="fa-solid fa-triangle-exclamation text-rose-400 mt-0.5"></i><div><span class="text-rose-300 font-bold">স্টক অ্যালার্ট!</span> <span class="text-slate-300">';
        $ls_parts = [];
        foreach ($low_stock as $ls) $ls_parts[] = htmlspecialchars($ls['title']) . ' (' . ((int)$ls['stock'] === 0 ? '<b class="text-rose-400">স্টক শেষ</b>' : 'বাকি ' . (int)$ls['stock'] . ' টি') . ')';
        echo implode(' · ', $ls_parts);
        echo '</span> — <a href="?action=products" class="text-cyan-400 hover:underline">স্টক আপডেট করুন →</a></div></div>';
    }

    // বাল্ক কুরিয়ার বুকিং ফলাফল ব্যানার (ডাবল-বুকিং কতটা ঠেকানো হলো তা স্পষ্ট দেখায়)
    if (isset($_GET['bulk_booked'])) {
        $bb = (int)$_GET['bulk_booked']; $bs = (int)($_GET['bulk_skipped'] ?? 0); $bf = (int)($_GET['bulk_failed'] ?? 0);
        echo '<div class="bg-slate-800 border border-emerald-700/50 rounded-2xl p-4 mb-6 flex flex-wrap items-center gap-4 text-sm font-semibold">';
        echo '<span class="text-emerald-400"><i class="fa-solid fa-circle-check"></i> ' . $bb . ' টি অর্ডার নতুন বুক হয়েছে</span>';
        if ($bs > 0) echo '<span class="text-amber-400"><i class="fa-solid fa-shield-halved"></i> ' . $bs . ' টি আগে থেকেই বুকড ছিল — বাদ দেওয়া হয়েছে (ডাবল বুকিং ঠেকানো হলো)</span>';
        if ($bf > 0) echo '<span class="text-rose-400"><i class="fa-solid fa-triangle-exclamation"></i> ' . $bf . ' টি ব্যর্থ হয়েছে (আবার চেষ্টা করা যাবে)</span>';
        echo '</div>';
    }

    $today_orders_count = (int)$db->query("SELECT COUNT(*) FROM orders WHERE is_deleted = 0 AND DATE(created_at) = CURDATE()")->fetchColumn();
    render_analytics_tiles($total_orders, $pending_orders, $delivered_orders, $today_sales, $deleted_orders_count, $total_sales, $incomplete_count, $today_orders_count);
    ?>
    <?php if (get_user_role() !== 'agent'): // কলিং এজেন্টে কুরিয়ার অটো সিঙ্ক বন্ধ ?>
    <div class="flex justify-end mb-3">
        <button type="button" id="courierSyncToggle" onclick="toggleCourierSync()" class="text-xs font-bold px-4 py-2 rounded-xl border transition bg-slate-800 border-slate-700 text-slate-300">
            <i class="fa-solid fa-rotate"></i> কুরিয়ার অটো সিঙ্ক: ...
        </button>
    </div>
    <?php endif; ?>
    <?php
    echo '<div id="ordersTableWrap">';
    render_orders_table($orders, $search, $status_filter, $date_filter, $start_date, $end_date, $product_filter, $color_filter, $zone_filter, $page, $per_page, $total_filtered, $total_pages, $order_rank, $phone_totals, $courier_filter);
    echo '</div>';
    render_dashboard_footer();
    exit;
}

if ($action === 'order_detail' && isset($_GET['id'])) {
    $order_id = (int)$_GET['id'];
    $stmt = $db->prepare("SELECT o.*, p.title as product_title FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.id = ?");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch();

    if (!$order) die("Order not found!");

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $status = $_POST['status'];
        $color = $_POST['color_selected'] ?? '';
        $size = trim($_POST['size_selected'] ?? '');
        $weight = trim($_POST['weight_selected'] ?? '');
        $cod = $_POST['cod_amount'];
        $note = $_POST['note'];
        $address = $_POST['address'];
        $new_product_id = (int)($_POST['product_id'] ?? 0);
        if (!$new_product_id) $new_product_id = (int)$order['product_id'];
        // গ্রাহকের নাম ও মোবাইল নাম্বার পরিবর্তন
        $cust_name = trim($_POST['customer_name'] ?? '');
        if ($cust_name === '') $cust_name = $order['customer_name'];
        $cust_phone = trim(bnToEnNumber($_POST['phone'] ?? ''));
        if ($cust_phone === '') $cust_phone = $order['phone'];

        // মাল্টি-প্রোডাক্ট: JSON ভ্যালিডেট করে সেভ (খালি হলে NULL)
        $order_items_save = null;
        if (!empty($_POST['order_items_json'])) {
            $decoded = json_decode($_POST['order_items_json'], true);
            if (is_array($decoded) && count($decoded) > 0) {
                $clean_items = [];
                foreach ($decoded as $it) {
                    $clean_items[] = [
                        'product_id' => (int)($it['product_id'] ?? 0),
                        'title' => mb_substr(trim((string)($it['title'] ?? '')), 0, 120),
                        'qty' => max(1, (int)($it['qty'] ?? 1)),
                        'price' => (float)($it['price'] ?? 0),
                    ];
                }
                $order_items_save = json_encode($clean_items, JSON_UNESCAPED_UNICODE);
                // প্রধান product_id = প্রথম আইটেম (কুরিয়ার/রিপোর্ট backward-compat)
                if (!empty($clean_items[0]['product_id'])) $new_product_id = $clean_items[0]['product_id'];
            }
        }

        $up = $db->prepare("UPDATE orders SET customer_name = ?, phone = ?, status = ?, product_id = ?, color_selected = ?, size_selected = ?, weight_selected = ?, cod_amount = ?, note = ?, address = ?, order_items = ?, updated_by = ?, updated_at = NOW() WHERE id = ?");
        $up->execute([$cust_name, $cust_phone, $status, $new_product_id, $color, $size, $weight, $cod, $note, $address, $order_items_save, $_SESSION['username'], $order_id]);

        // ডেলিভারি জোন আপডেট (Zone not clear ঠিক করা) — চার্জের পার্থক্য COD-তে সমন্বয়
        if (isset($_POST['delivery_zone'])) {
            $new_zone = in_array($_POST['delivery_zone'], ['dhaka', 'sub_dhaka', 'outside']) ? $_POST['delivery_zone'] : '';
            $old_zone = (string)($order['delivery_zone'] ?? '');
            if ($new_zone !== $old_zone) {
                $zmap = [
                    'dhaka' => (float)(get_setting('courier_charge_dhaka') ?: 60),
                    'sub_dhaka' => (float)(get_setting('courier_charge_sub_dhaka') ?: 100),
                    'outside' => (float)(get_setting('courier_charge_outside') ?: 130),
                ];
                $old_chg = (float)($order['delivery_charge'] ?? 0);
                $new_chg = $new_zone !== '' ? $zmap[$new_zone] : 0;
                $adj_cod = max(0, $cod - $old_chg + $new_chg);
                $db->prepare("UPDATE orders SET delivery_zone = ?, delivery_charge = ?, cod_amount = ? WHERE id = ?")
                   ->execute([$new_zone !== '' ? $new_zone : null, $new_chg, $adj_cod, $order_id]);
            }
        }

        // SMS: স্ট্যাটাস নতুন করে confirmed হলে কাস্টমারকে জানানো
        if (get_setting('sms_on_confirm') === '1' && $status === 'confirmed' && ($order['status'] ?? '') !== 'confirmed') {
            try {
                send_sms($cust_phone, sms_render(get_setting('sms_tpl_confirm'), ['customer_name' => $cust_name, 'id' => $order_id, 'cod_amount' => $cod]));
            } catch (Exception $e) {}
        }

        // SMS হুক: pending → confirmed হলে কাস্টমারকে কনফার্মেশন SMS
        if (get_setting('sms_on_confirm') === '1' && $status === 'confirmed' && ($order['status'] ?? '') !== 'confirmed') {
            $sms_order = ['id' => $order_id, 'customer_name' => $cust_name, 'cod_amount' => $cod];
            try { send_sms($cust_phone, sms_fill_template(get_setting('sms_tpl_confirm'), $sms_order)); } catch (Exception $e) {}
        }
        header("Location: ?action=order_detail&id=" . $order_id . "&msg=updated");
        exit;
    }

    $all_products_for_order = $db->query("SELECT id, title, price, sale_price FROM products ORDER BY id DESC")->fetchAll();
    render_dashboard_header("অর্ডার বিস্তারিত # " . $order['id']);
    render_order_detail_view($order, $all_products_for_order);
    render_dashboard_footer();
    exit;
}

if ($action === 'inventory') {
    require_login();
    $products = $db->query("SELECT * FROM products ORDER BY id DESC")->fetchAll();
    render_dashboard_header("ইনভেন্টরি ম্যানেজার");
    render_inventory_panel($products);
    render_dashboard_footer();
    exit;
}

if ($action === 'users') {
    require_admin();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['add_user'])) {
            $username = trim($_POST['username']);
            $password = password_hash(trim($_POST['password']), PASSWORD_BCRYPT);
            $role = $_POST['role'];
            try {
                $db->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, ?)")->execute([$username, $password, $role]);
            } catch (Exception $e) { $user_error = "User already exists!"; }
        }
        if (isset($_POST['edit_user'])) {
            $uid = (int)$_POST['user_id'];
            $username = trim($_POST['username']);
            $role = $_POST['role'];
            if (!empty($_POST['password'])) {
                $password = password_hash(trim($_POST['password']), PASSWORD_BCRYPT);
                $stmt = $db->prepare("UPDATE users SET username = ?, password = ?, role = ? WHERE id = ?");
                $stmt->execute([$username, $password, $role, $uid]);
            } else {
                $stmt = $db->prepare("UPDATE users SET username = ?, role = ? WHERE id = ?");
                $stmt->execute([$username, $role, $uid]);
            }
        }
        if (isset($_POST['delete_user'])) {
            $uid = (int)$_POST['user_id'];
            if ($uid !== (int)$_SESSION['user_id']) {
                $db->prepare("DELETE FROM users WHERE id = ?")->execute([$uid]);
            }
        }
    }

    $users = $db->query("SELECT * FROM users ORDER BY id DESC")->fetchAll();
    render_dashboard_header("ইউজার ম্যানেজমেন্ট");
    render_user_management($users, $user_error ?? null);
    render_dashboard_footer();
    exit;
}

if ($action === 'settings') {
    require_admin();

    // ---- প্রোমো কোড ম্যানেজার (আলাদা ফর্ম, PRG) ----
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_promo'])) {
        $p_code = strtoupper(trim($_POST['promo_code'] ?? ''));
        $p_type = ($_POST['promo_type'] ?? 'flat') === 'percent' ? 'percent' : 'flat';
        $p_val  = max(0, (float)bnToEnNumber($_POST['promo_value'] ?? '0'));
        $p_until = trim($_POST['promo_until'] ?? '');
        $p_max  = max(0, (int)bnToEnNumber($_POST['promo_max'] ?? '0'));
        if ($p_code === '' || $p_val <= 0) {
            header("Location: ?action=settings&pmsg=invalid"); exit;
        }
        if ($p_type === 'percent' && $p_val > 100) $p_val = 100;
        try {
            $db->prepare("INSERT INTO promo_codes (code, discount_type, discount_value, valid_until, max_uses) VALUES (?, ?, ?, ?, ?)")
               ->execute([$p_code, $p_type, $p_val, $p_until !== '' ? $p_until : null, $p_max]);
            header("Location: ?action=settings&pmsg=added");
        } catch (Exception $e) {
            header("Location: ?action=settings&pmsg=exists");
        }
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_promo'])) {
        $db->prepare("UPDATE promo_codes SET active = 1 - active WHERE id = ?")->execute([(int)$_POST['promo_id']]);
        header("Location: ?action=settings&pmsg=toggled"); exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_promo'])) {
        $db->prepare("DELETE FROM promo_codes WHERE id = ?")->execute([(int)$_POST['promo_id']]);
        header("Location: ?action=settings&pmsg=deleted"); exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['site_name'])) {
            update_setting('site_name', trim($_POST['site_name']) ?: 'SunnahTi');
            update_setting('site_title', trim($_POST['site_title'] ?? ''));
        }
        if (isset($_POST['contact_whatsapp']) || isset($_POST['contact_phone'])) {
            update_setting('contact_whatsapp', trim(bnToEnNumber($_POST['contact_whatsapp'] ?? '')));
            update_setting('contact_phone', trim(bnToEnNumber($_POST['contact_phone'] ?? '')));
        }
        if (isset($_POST['og_default_image'])) {
            update_setting('og_default_image', trim($_POST['og_default_image']));
        }
        if (isset($_POST['home_page_slug'])) {
            update_setting('home_page_slug', trim($_POST['home_page_slug']));
        }
        if (isset($_POST['sms_api_key'])) {
            update_setting('sms_api_key', trim($_POST['sms_api_key']));
            update_setting('sms_sender_id', trim($_POST['sms_sender_id'] ?? ''));
            update_setting('sms_tpl_confirm', trim($_POST['sms_tpl_confirm'] ?? ''));
            update_setting('sms_tpl_courier', trim($_POST['sms_tpl_courier'] ?? ''));
            update_setting('sms_on_confirm', isset($_POST['sms_on_confirm']) ? '1' : '0');
            update_setting('sms_on_courier', isset($_POST['sms_on_courier']) ? '1' : '0');
        }
        if (isset($_POST['telegram_bot_token'])) {
            update_setting('telegram_bot_token', trim($_POST['telegram_bot_token']));
            update_setting('telegram_chat_id', trim($_POST['telegram_chat_id'] ?? ''));
        }
        if (isset($_POST['courier_charge_dhaka'])) {
            update_setting('courier_charge_dhaka', (string)max(0, (float)bnToEnNumber($_POST['courier_charge_dhaka'])));
            update_setting('courier_charge_sub_dhaka', (string)max(0, (float)bnToEnNumber($_POST['courier_charge_sub_dhaka'] ?? '0')));
            update_setting('courier_charge_outside', (string)max(0, (float)bnToEnNumber($_POST['courier_charge_outside'] ?? '0')));
        }
        update_setting('fraud_api_key', trim($_POST['fraud_api_key']));
        update_setting('fraud_api_url', trim($_POST['fraud_api_url']));
        update_setting('steadfast_api_key', trim($_POST['steadfast_api_key']));
        update_setting('steadfast_secret_key', trim($_POST['steadfast_secret_key']));
        update_setting('steadfast_base_url', trim($_POST['steadfast_base_url']));
        if (isset($_POST['invoice_prefix'])) update_setting('invoice_prefix', trim($_POST['invoice_prefix']));
        update_setting('facebook_pixel', trim($_POST['facebook_pixel']));
        update_setting('facebook_access_token', trim($_POST['facebook_access_token']));
        update_setting('facebook_test_code', trim($_POST['facebook_test_code']));
        update_setting('tiktok_pixel', trim($_POST['tiktok_pixel']));
        update_setting('tiktok_access_token', trim($_POST['tiktok_access_token']));
        update_setting('tiktok_test_code', trim($_POST['tiktok_test_code']));
        update_setting('google_tag', trim($_POST['google_tag']));

        // Feature 3: Google Sheet connection settings
        update_setting('gsheet_enabled', isset($_POST['gsheet_enabled']) ? '1' : '0');
        update_setting('gsheet_webapp_url', trim($_POST['gsheet_webapp_url'] ?? ''));
        update_setting('gsheet_sheet_name', trim($_POST['gsheet_sheet_name'] ?? 'Orders'));

        $fields = [
            'name' => isset($_POST['field_name']),
            'phone' => isset($_POST['field_phone']),
            'alt_phone' => isset($_POST['field_alt_phone']),
            'address' => isset($_POST['field_address']),
            'color' => isset($_POST['field_color']),
            'note' => isset($_POST['field_note'])
        ];
        update_setting('checkout_fields', json_encode($fields));

        $colors = [];
        if (isset($_POST['color_en'])) {
            for ($i = 0; $i < count($_POST['color_en']); $i++) {
                if (!empty($_POST['color_en'][$i])) {
                    $colors[] = [
                        'en' => trim($_POST['color_en'][$i]),
                        'bn' => trim($_POST['color_bn'][$i] ?? '')
                    ];
                }
            }
            update_setting('product_colors', json_encode($colors));
        }

        $success_msg = "সিস্টেম সেটিংস সফলভাবে আপডেট করা হয়েছে!";
    }

    render_dashboard_header("সিস্টেম সেটিংস");
    render_settings_panel($success_msg ?? null);
    render_dashboard_footer();
    exit;
}

if ($action === 'products') {
    require_admin();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // ---- ক্যাটাগরি ম্যানেজমেন্ট (ক্রিয়েট / এডিট / ডুপ্লিকেট / ডিলিট) ----
        if (isset($_POST['save_category'])) {
            $cat_id = (int)($_POST['category_id'] ?? 0);
            $cat_name = trim($_POST['category_name'] ?? '');
            if ($cat_name !== '') {
                if ($cat_id > 0) {
                    $db->prepare("UPDATE categories SET name = ? WHERE id = ?")->execute([$cat_name, $cat_id]);
                } else {
                    $db->prepare("INSERT INTO categories (name) VALUES (?)")->execute([$cat_name]);
                }
            }
            header("Location: ?action=products&msg=cat_saved");
            exit;
        }
        if (isset($_POST['duplicate_category'])) {
            $cat_id = (int)($_POST['category_id'] ?? 0);
            $st = $db->prepare("SELECT name FROM categories WHERE id = ?");
            $st->execute([$cat_id]);
            if ($cat = $st->fetch()) {
                $db->prepare("INSERT INTO categories (name) VALUES (?)")->execute([$cat['name'] . ' (কপি)']);
            }
            header("Location: ?action=products&msg=cat_duplicated");
            exit;
        }
        if (isset($_POST['delete_category'])) {
            $cat_id = (int)($_POST['category_id'] ?? 0);
            $db->prepare("UPDATE products SET category_id = NULL WHERE category_id = ?")->execute([$cat_id]);
            $db->prepare("DELETE FROM categories WHERE id = ?")->execute([$cat_id]);
            header("Location: ?action=products&msg=cat_deleted");
            exit;
        }

        if (isset($_POST['save_product'])) {
            $pid = (int)($_POST['product_id'] ?? 0);
            $title = trim($_POST['title']);
            $slug = trim($_POST['slug']) ?: strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $title));
            $slug = trim($slug, '-');
            if ($slug === '') $slug = 'product-' . bin2hex(random_bytes(3)); // বাংলা টাইটেলে slug খালি হলে ইউনিক fallback
            // একই slug আগেই থাকলে (অন্য প্রোডাক্টে) ইউনিক করা
            $chk = $db->prepare("SELECT COUNT(*) FROM products WHERE slug = ? AND id != ?");
            $chk->execute([$slug, $pid]);
            if ($chk->fetchColumn() > 0) $slug .= '-' . bin2hex(random_bytes(3));
            $price = (float)$_POST['price'];
            $sale_price = !empty($_POST['sale_price']) ? (float)$_POST['sale_price'] : null;
            $description = trim($_POST['description']);
            $image_url = trim($_POST['image_url']);
            $stock = (int)($_POST['stock'] ?? 0);
            $category_id = (int)($_POST['category_id'] ?? 0) ?: null;

            $p_fields = [
                'name' => isset($_POST['p_field_name']),
                'phone' => isset($_POST['p_field_phone']),
                'alt_phone' => isset($_POST['p_field_alt_phone']),
                'address' => isset($_POST['p_field_address']),
                'color' => isset($_POST['p_field_color']),
                'note' => isset($_POST['p_field_note']),
                'custom_field' => isset($_POST['p_custom_field']),
                'custom_field_label' => trim($_POST['p_custom_field_label'] ?? ''),
                'courier_charge' => isset($_POST['p_courier_charge']),
                'promo_code' => isset($_POST['p_promo_code'])
            ];
            $checkout_fields_json = json_encode($p_fields);

            // Feature 19: per-product variant option selection (size teen/kids, weight)
            $v_options = [
                'size_teen' => isset($_POST['p_variant_size_teen']),
                'size_kids' => isset($_POST['p_variant_size_kids']),
                'weight'    => isset($_POST['p_variant_weight'])
            ];
            $variant_options_json = json_encode($v_options);

            $og_image = trim($_POST['og_image'] ?? '');
            $cost_price = $_POST['cost_price'] !== '' ? (float)bnToEnNumber($_POST['cost_price']) : null;
            if ($pid > 0) {
                $stmt = $db->prepare("UPDATE products SET title = ?, slug = ?, price = ?, sale_price = ?, cost_price = ?, description = ?, image_url = ?, checkout_fields = ?, variant_options = ?, stock = ?, category_id = ?, og_image = ? WHERE id = ?");
                $stmt->execute([$title, $slug, $price, $sale_price, $cost_price, $description, $image_url, $checkout_fields_json, $variant_options_json, $stock, $category_id, $og_image, $pid]);
            } else {
                $stmt = $db->prepare("INSERT INTO products (title, slug, price, sale_price, cost_price, description, image_url, checkout_fields, variant_options, stock, category_id, og_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $price, $sale_price, $cost_price, $description, $image_url, $checkout_fields_json, $variant_options_json, $stock, $category_id, $og_image]);
            }
            header("Location: ?action=products&msg=saved");
            exit;
        }
        if (isset($_POST['delete_product'])) {
            $pid = (int)$_POST['product_id'];
            $db->prepare("DELETE FROM products WHERE id = ?")->execute([$pid]);
            header("Location: ?action=products&msg=deleted");
            exit;
        }
    }

    $cat_filter = (int)($_GET['cat'] ?? 0);
    if ($cat_filter > 0) {
        $pst = $db->prepare("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.category_id = ? ORDER BY p.id DESC");
        $pst->execute([$cat_filter]);
        $products = $pst->fetchAll();
    } elseif ($cat_filter === -1) {
        $products = $db->query("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.category_id IS NULL ORDER BY p.id DESC")->fetchAll();
    } else {
        $products = $db->query("SELECT p.*, c.name AS category_name FROM products p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.id DESC")->fetchAll();
    }
    $all_categories = $db->query("SELECT * FROM categories ORDER BY name ASC")->fetchAll();
    render_dashboard_header("প্রোডাক্ট ম্যানেজমেন্ট");
    render_products_panel($products, $all_categories, $cat_filter);
    render_dashboard_footer();
    exit;
}

if ($action === 'pages') {
    require_admin();

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['save_page'])) {
            $id = (int)($_POST['page_id'] ?? 0);
            $title = trim($_POST['title']);
            $slug = trim($_POST['slug']) ?: strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $title));
            $slug = trim($slug, '-');
            if ($slug === '') $slug = 'page-' . bin2hex(random_bytes(3)); // বাংলা টাইটেলে slug খালি হলে ইউনিক fallback
            $chk = $db->prepare("SELECT COUNT(*) FROM pages WHERE slug = ? AND id != ?");
            $chk->execute([$slug, $id]);
            if ($chk->fetchColumn() > 0) $slug .= '-' . bin2hex(random_bytes(3));
            $content = $_POST['content'];
            $bottom_content = $_POST['bottom_content'];
            $seo_title = trim($_POST['seo_title'] ?? '');
            $seo_desc = trim($_POST['seo_desc'] ?? '');

            $page_products = isset($_POST['page_products']) ? json_encode($_POST['page_products']) : null;

            $pg_fields = [
                'name' => isset($_POST['pg_field_name']),
                'phone' => isset($_POST['pg_field_phone']),
                'alt_phone' => isset($_POST['pg_field_alt_phone']),
                'address' => isset($_POST['pg_field_address']),
                'color' => isset($_POST['pg_field_color']),
                'note' => isset($_POST['pg_field_note']),
                'wa_icon' => isset($_POST['pg_wa_icon']),
                'call_icon' => isset($_POST['pg_call_icon']),
                'custom_field' => isset($_POST['pg_custom_field']),
                'custom_field_label' => trim($_POST['pg_custom_field_label'] ?? ''),
                'courier_charge' => isset($_POST['pg_courier_charge']),
                'promo_code' => isset($_POST['pg_promo_code'])
            ];
            $checkout_fields_json = json_encode($pg_fields);

            // এই ল্যান্ডিং পেজের কাস্টম ভ্যারিয়েন্ট কনফিগ (সাইজ/কালার/ওজন — কোন কোন অপশন থাকবে)
            $variant_config = null;
            if (($_POST['vc_mode'] ?? 'default') === 'custom') {
                $clean_list = function ($key) {
                    $arr = $_POST[$key] ?? [];
                    if (!is_array($arr)) return [];
                    return array_values(array_filter(array_map(function ($v) { return trim((string)$v); }, $arr), function ($v) { return $v !== ''; }));
                };
                $variant_config = json_encode([
                    'size_teen' => ['enabled' => isset($_POST['vc_size_teen']), 'options' => $clean_list('vc_size_teen_opts')],
                    'size_kids' => ['enabled' => isset($_POST['vc_size_kids']), 'options' => $clean_list('vc_size_kids_opts')],
                    'weight'    => ['enabled' => isset($_POST['vc_weight']), 'options' => $clean_list('vc_weight_opts'), 'custom' => isset($_POST['vc_weight_custom'])],
                    'colors'    => ['enabled' => isset($_POST['vc_colors']), 'options' => $clean_list('vc_color_opts')]
                ], JSON_UNESCAPED_UNICODE);
            }

            $multi_product = isset($_POST['multi_product']) ? 1 : 0;
            if ($id > 0) {
                $og_image = trim($_POST['og_image'] ?? '');
                $builder_json = trim($_POST['builder_json'] ?? '') ?: null;
                $stmt = $db->prepare("UPDATE pages SET title = ?, slug = ?, content = ?, bottom_content = ?, seo_title = ?, seo_desc = ?, product_ids = ?, checkout_fields = ?, variant_config = ?, og_image = ?, builder_json = ?, multi_product = ? WHERE id = ?");
                $stmt->execute([$title, $slug, $content, $bottom_content, $seo_title, $seo_desc, $page_products, $checkout_fields_json, $variant_config, $og_image, $builder_json, $multi_product, $id]);
            } else {
                $og_image = trim($_POST['og_image'] ?? '');
                $builder_json = trim($_POST['builder_json'] ?? '') ?: null;
                $stmt = $db->prepare("INSERT INTO pages (title, slug, content, bottom_content, seo_title, seo_desc, product_ids, checkout_fields, variant_config, og_image, builder_json, multi_product) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$title, $slug, $content, $bottom_content, $seo_title, $seo_desc, $page_products, $checkout_fields_json, $variant_config, $og_image, $builder_json, $multi_product]);
            }
            header("Location: ?action=pages&msg=saved");
            exit;
        }
        if (isset($_POST['delete_page'])) {
            $id = (int)$_POST['page_id'];
            $db->prepare("DELETE FROM pages WHERE id = ?")->execute([$id]);
            header("Location: ?action=pages&msg=deleted");
            exit;
        }
    }

    $pages = $db->query("SELECT * FROM pages ORDER BY id DESC")->fetchAll();
    $all_products_list = $db->query("SELECT id, title, price, sale_price FROM products ORDER BY id DESC")->fetchAll();
    render_dashboard_header("পেজ ও ল্যান্ডিং ক্রিয়েটর");
    render_pages_panel($pages, $all_products_list);
    render_dashboard_footer();
    exit;
}

// -------------------------------------------------------------
// 6. UI Rendition & HTML Templating Block
// -------------------------------------------------------------

function render_login_view($error) {
    $site_name = branding('site_name', 'SunnahTi');
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($site_name) ?> ERP Secure Access</title>
        <?php render_favicon_tag(); ?>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
        <style>body { font-family: 'Hind Siliguri', sans-serif; }</style>
    </head>
    <body class="bg-slate-900 flex items-center justify-center min-h-screen p-4">
        <div class="bg-slate-800 p-8 rounded-2xl shadow-2xl w-full max-w-md border border-slate-700">
            <div class="text-center mb-6">
                <?php $logo = branding('logo_url'); if ($logo): ?>
                    <img src="<?= htmlspecialchars($logo) ?>" alt="logo" class="h-14 mx-auto mb-2 object-contain">
                <?php endif; ?>
                <span class="text-emerald-500 text-5xl font-extrabold tracking-wider block"><?= htmlspecialchars($site_name) ?></span>
                <p class="text-slate-400 mt-2 text-sm uppercase tracking-widest">Enterprise Core Login</p>
            </div>

            <?php if ($error): ?>
                <div class="bg-red-500/10 border border-red-500 text-red-400 p-3 rounded-lg text-sm mb-4">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <form action="?action=do_login" method="POST" class="space-y-4">
                <div>
                    <label class="block text-slate-300 text-sm font-semibold mb-1">ইউজারনেম</label>
                    <input type="text" name="username" required class="w-full bg-slate-700 border border-slate-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:border-emerald-500">
                </div>
                <div>
                    <label class="block text-slate-300 text-sm font-semibold mb-1">পাসওয়ার্ড</label>
                    <input type="password" name="password" required class="w-full bg-slate-700 border border-slate-600 rounded-lg py-2 px-3 text-white focus:outline-none focus:border-emerald-500">
                </div>
                <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-2.5 rounded-lg transition duration-200">প্রবেশ করুন</button>
            </form>
        </div>
    </body>
    </html>
    <?php
}

function render_dashboard_header($title) {
    $role = get_user_role();
    $balance = ($role === 'admin' || $role === 'office_team') ? IntegrationEngine::checkSteadfastBalance() : null;
    $site_name = branding('site_name', 'SunnahTi');
    $logo = branding('logo_url');
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= $title ?> - <?= htmlspecialchars($site_name) ?> Console</title>
        <?php render_favicon_tag(); ?>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <script>
            // সেভ করা থিম পেজ আঁকার আগেই অ্যাপ্লাই (ফ্ল্যাশ এড়াতে)
            (function() {
                try {
                    var t = localStorage.getItem('dashTheme');
                    if (t && t !== 'slate') document.documentElement.setAttribute('data-theme', t);
                } catch (e) {}
            })();
        </script>
        <style>
            body { font-family: 'Hind Siliguri', sans-serif; transition: background-color 0.3s, color 0.3s; }

            /* ===== ৭টি ড্যাশবোর্ড থিম (data-theme অ্যাট্রিবিউট দিয়ে) ===== */
            html[data-theme="midnight"] body, html[data-theme="midnight"] .bg-slate-950 { background-color: #010b1f !important; }
            html[data-theme="midnight"] .bg-slate-900 { background-color: #04122e !important; }
            html[data-theme="midnight"] .bg-slate-800 { background-color: #0a1d42 !important; }
            html[data-theme="midnight"] .bg-slate-700 { background-color: #132b5c !important; }
            html[data-theme="midnight"] .border-slate-800 { border-color: #0e2247 !important; }
            html[data-theme="midnight"] .border-slate-700 { border-color: #1b3564 !important; }
            html[data-theme="midnight"] .border-slate-600 { border-color: #27457e !important; }
            html[data-theme="midnight"] .hover\:bg-slate-700:hover { background-color: #1b3564 !important; }
            html[data-theme="midnight"] .hover\:bg-slate-600:hover { background-color: #27457e !important; }
            html[data-theme="emerald"] body, html[data-theme="emerald"] .bg-slate-950 { background-color: #01150e !important; }
            html[data-theme="emerald"] .bg-slate-900 { background-color: #032118 !important; }
            html[data-theme="emerald"] .bg-slate-800 { background-color: #053024 !important; }
            html[data-theme="emerald"] .bg-slate-700 { background-color: #0a4534 !important; }
            html[data-theme="emerald"] .border-slate-800 { border-color: #07392b !important; }
            html[data-theme="emerald"] .border-slate-700 { border-color: #0e503d !important; }
            html[data-theme="emerald"] .border-slate-600 { border-color: #17694f !important; }
            html[data-theme="emerald"] .hover\:bg-slate-700:hover { background-color: #0e503d !important; }
            html[data-theme="emerald"] .hover\:bg-slate-600:hover { background-color: #17694f !important; }
            html[data-theme="purple"] body, html[data-theme="purple"] .bg-slate-950 { background-color: #100322 !important; }
            html[data-theme="purple"] .bg-slate-900 { background-color: #180735 !important; }
            html[data-theme="purple"] .bg-slate-800 { background-color: #241048 !important; }
            html[data-theme="purple"] .bg-slate-700 { background-color: #341a63 !important; }
            html[data-theme="purple"] .border-slate-800 { border-color: #2a1454 !important; }
            html[data-theme="purple"] .border-slate-700 { border-color: #3d2470 !important; }
            html[data-theme="purple"] .border-slate-600 { border-color: #523391 !important; }
            html[data-theme="purple"] .hover\:bg-slate-700:hover { background-color: #3d2470 !important; }
            html[data-theme="purple"] .hover\:bg-slate-600:hover { background-color: #523391 !important; }
            html[data-theme="crimson"] body, html[data-theme="crimson"] .bg-slate-950 { background-color: #1a020a !important; }
            html[data-theme="crimson"] .bg-slate-900 { background-color: #270511 !important; }
            html[data-theme="crimson"] .bg-slate-800 { background-color: #380a1c !important; }
            html[data-theme="crimson"] .bg-slate-700 { background-color: #4e132b !important; }
            html[data-theme="crimson"] .border-slate-800 { border-color: #420e24 !important; }
            html[data-theme="crimson"] .border-slate-700 { border-color: #5c1a34 !important; }
            html[data-theme="crimson"] .border-slate-600 { border-color: #792645 !important; }
            html[data-theme="crimson"] .hover\:bg-slate-700:hover { background-color: #5c1a34 !important; }
            html[data-theme="crimson"] .hover\:bg-slate-600:hover { background-color: #792645 !important; }
            html[data-theme="coffee"] body, html[data-theme="coffee"] .bg-slate-950 { background-color: #140d06 !important; }
            html[data-theme="coffee"] .bg-slate-900 { background-color: #1f150b !important; }
            html[data-theme="coffee"] .bg-slate-800 { background-color: #2d1f12 !important; }
            html[data-theme="coffee"] .bg-slate-700 { background-color: #3f2d1b !important; }
            html[data-theme="coffee"] .border-slate-800 { border-color: #352515 !important; }
            html[data-theme="coffee"] .border-slate-700 { border-color: #4a3722 !important; }
            html[data-theme="coffee"] .border-slate-600 { border-color: #5f4830 !important; }
            html[data-theme="coffee"] .hover\:bg-slate-700:hover { background-color: #4a3722 !important; }
            html[data-theme="coffee"] .hover\:bg-slate-600:hover { background-color: #5f4830 !important; }
            html[data-theme="cyber"] body, html[data-theme="cyber"] .bg-slate-950 { background-color: #00090d !important; }
            html[data-theme="cyber"] .bg-slate-900 { background-color: #001318 !important; }
            html[data-theme="cyber"] .bg-slate-800 { background-color: #012026 !important; }
            html[data-theme="cyber"] .bg-slate-700 { background-color: #04333c !important; }
            html[data-theme="cyber"] .border-slate-800 { border-color: #022931 !important; }
            html[data-theme="cyber"] .border-slate-700 { border-color: #064450 !important; }
            html[data-theme="cyber"] .border-slate-600 { border-color: #0a5c6b !important; }
            html[data-theme="cyber"] .hover\:bg-slate-700:hover { background-color: #064450 !important; }
            html[data-theme="cyber"] .hover\:bg-slate-600:hover { background-color: #0a5c6b !important; }
            /* চোখ-বান্ধব লাইট থিম: নরম উষ্ণ ব্যাকগ্রাউন্ড, অফ-হোয়াইট কার্ড, নরম বর্ডার+শ্যাডো (কড়া সাদা নয়) */
            html[data-theme="light"] body, html[data-theme="light"] .bg-slate-950 { background-color: #e8ecf3 !important; }
            html[data-theme="light"] .bg-slate-900 { background-color: #f7f9fc !important; }
            html[data-theme="light"] .bg-slate-800 { background-color: #f7f9fc !important; border-color: #dde3ec !important; box-shadow: 0 1px 3px rgba(15,23,42,0.05) !important; }
            html[data-theme="light"] .bg-slate-700 { background-color: #eaeef4 !important; }
            html[data-theme="light"] .border-slate-800, html[data-theme="light"] .border-slate-700, html[data-theme="light"] .border-slate-600 { border-color: #dde3ec !important; }
            html[data-theme="light"] .text-white { color: #1e293b !important; }
            html[data-theme="light"] .text-slate-100, html[data-theme="light"] .text-slate-200, html[data-theme="light"] .text-slate-300 { color: #3d4a5c !important; }
            html[data-theme="light"] .text-slate-400, html[data-theme="light"] .text-slate-500 { color: #64748b !important; }
            html[data-theme="light"] .bg-slate-950\/40, html[data-theme="light"] .bg-slate-900\/60 { background-color: #eef2f7 !important; }
            html[data-theme="light"] .bg-slate-950\/20, html[data-theme="light"] .bg-slate-950\/30 { background-color: #eef2f7 !important; }
            html[data-theme="light"] .hover\:bg-slate-700:hover, html[data-theme="light"] .hover\:bg-slate-600:hover { background-color: #e2e8f0 !important; }
            html[data-theme="light"] .hover\:bg-slate-700\/20:hover, html[data-theme="light"] .hover\:bg-slate-700\/30:hover { background-color: #eef2f7 !important; }
            html[data-theme="light"] input, html[data-theme="light"] select, html[data-theme="light"] textarea { background-color: #ffffff !important; color: #1e293b !important; border-color: #d3dce8 !important; }
            html[data-theme="light"] input::placeholder, html[data-theme="light"] textarea::placeholder { color: #94a3b8 !important; }
            html[data-theme="light"] table thead tr { border-color: #dde3ec !important; }
            html[data-theme="light"] tbody tr { border-color: #eaeef4 !important; }


            body.light-mode {
                background-color: #f1f5f9;
                color: #0f172a;
            }
            body.light-mode aside {
                background-color: #ffffff;
                border-right: 1px solid #cbd5e1;
            }
            body.light-mode aside .text-slate-200, body.light-mode aside .text-slate-400 {
                color: #334155 !important;
            }
            body.light-mode aside a:hover, body.light-mode aside button:hover {
                background-color: #e2e8f0;
            }
            body.light-mode .bg-slate-800, body.light-mode .bg-slate-950, body.light-mode .bg-slate-900 {
                background-color: #ffffff !important;
                border-color: #cbd5e1 !important;
                color: #0f172a !important;
                box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.05);
            }
            body.light-mode tr.hover\:bg-slate-750:hover {
                background-color: #f8fafc !important;
            }
            body.light-mode input, body.light-mode select, body.light-mode textarea {
                background-color: #ffffff !important;
                border-color: #cbd5e1 !important;
                color: #0f172a !important;
            }
            body.light-mode th {
                background-color: #f8fafc !important;
                color: #1e293b !important;
                border-bottom: 2px solid #e2e8f0 !important;
            }
            body.light-mode .text-white {
                color: #0f172a !important;
            }
            body.light-mode .text-slate-300, body.light-mode .text-slate-200 {
                color: #1e293b !important;
            }
            body.light-mode .text-slate-400 {
                color: #475569 !important;
            }
            body.light-mode .bg-slate-800\/50 {
                background-color: #e2e8f0 !important;
            }
            body.light-mode .bg-emerald-950\/30 {
                background-color: #d1fae5 !important;
                border: 1px solid #34d399 !important;
                color: #065f46 !important;
            }
            body.light-mode .bg-emerald-950\/30 span, body.light-mode .bg-emerald-950\/30 div {
                color: #065f46 !important;
            }
            body.light-mode .bg-amber-950\/30 {
                background-color: #fef3c7 !important;
                border: 1px solid #fbbf24 !important;
                color: #92400e !important;
            }
            body.light-mode .bg-amber-950\/30 span, body.light-mode .bg-amber-950\/30 div {
                color: #92400e !important;
            }
            body.light-mode .bg-indigo-950\/30 {
                background-color: #e0e7ff !important;
                border: 1px solid #818cf8 !important;
                color: #3730a3 !important;
            }
            body.light-mode .bg-indigo-950\/30 span, body.light-mode .bg-indigo-950\/30 div {
                color: #3730a3 !important;
            }
            body.light-mode .bg-slate-900\/40 {
                background-color: #ffffff !important;
                border: 1px solid #e2e8f0 !important;
            }
            body.light-mode .bg-rose-950\/30 {
                background-color: #fee2e2 !important;
                border: 1px solid #f87171 !important;
                color: #991b1b !important;
            }
            body.light-mode .bg-rose-950\/30 span, body.light-mode .bg-rose-950\/30 div {
                color: #991b1b !important;
            }

            @media (min-width: 768px) {
                aside.collapsed {
                    width: 4rem;
                }
                aside.collapsed .nav-text,
                aside.collapsed .sidebar-header-text,
                aside.collapsed .quick-balance {
                    display: none;
                }
                aside.collapsed .nav-link {
                    justify-content: center;
                    padding-left: 0;
                    padding-right: 0;
                }
            }
            @media (max-width: 767px) {
                /* মোবাইলে collapsed = শুধু মেনু আইটেম লুকাবে; হ্যামবার্গার বারটা সবসময় দেখা যাবে */
                aside.collapsed nav,
                aside.collapsed .quick-balance {
                    display: none;
                }
                aside.collapsed .sidebar-header-text {
                    display: flex !important;
                }
                aside .sidebar-header {
                    padding: 0.9rem 1.25rem !important;
                }
            }
        </style>
    </head>
    <body class="bg-slate-900 text-slate-100 min-h-screen flex flex-col md:flex-row">
        <script>
            if (localStorage.getItem('theme') === 'light') {
                document.body.classList.add('light-mode');
            }
        </script>

        <!-- Sidebar Navigation -->
        <aside id="mainSidebar" class="w-full md:w-64 bg-slate-950 flex-shrink-0 border-r border-slate-800 transition-all duration-300">
            <div class="sidebar-header p-6 border-b border-slate-800 flex items-center justify-between gap-2">
                <span class="text-xl font-bold text-emerald-400 sidebar-header-text flex items-center gap-2">
                    <?php if ($logo): ?><img src="<?= htmlspecialchars($logo) ?>" class="h-7 w-7 object-contain rounded" alt="logo"><?php endif; ?>
                    <?= htmlspecialchars($site_name) ?> ERP
                </span>
                <span class="text-[10px] bg-slate-800 px-2 py-1 rounded text-slate-400 sidebar-header-text">v3.0</span>
                <button onclick="toggleSidebarCollapse()" class="text-slate-400 hover:text-white focus:outline-none p-1.5 rounded-lg bg-slate-900" title="মেনু ছোট/বড় করুন">
                    <i class="fa-solid fa-bars"></i>
                </button>
            </div>

            <nav class="p-4 space-y-1.5">
                <a href="?action=dashboard" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-gauge text-emerald-500 w-5 text-center"></i> <span class="nav-text">ড্যাশবোর্ড</span>
                </a>

                <a href="?action=incomplete_orders" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-hourglass-half text-orange-400 w-5 text-center"></i> <span class="nav-text">ইনকমপ্লিট অর্ডার</span>
                </a>

                <a href="?action=inbox" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-comments text-sky-400 w-5 text-center"></i> <span class="nav-text">ইনবক্স (WA + FB)</span>
                </a>

                <a href="?action=zone_change" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-map-location-dot text-orange-400 w-5 text-center"></i> <span class="nav-text">কুরিয়ার জোন চেঞ্জ</span>
                </a>

                <?php if ($role !== 'agent'): ?>
                <a href="?action=reports" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-chart-pie text-violet-400 w-5 text-center"></i> <span class="nav-text">রিপোর্ট</span>
                </a>
                <a href="?action=ad_costs" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-bullhorn text-pink-400 w-5 text-center"></i> <span class="nav-text">অ্যাড খরচ</span>
                </a>
                <a href="?action=short_links" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-link text-cyan-400 w-5 text-center"></i> <span class="nav-text">লিংক শর্টনার</span>
                </a>
                <?php endif; ?>

                <?php if ($role === 'admin'): ?>
                    <a href="?action=products" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-box text-blue-500 w-5 text-center"></i> <span class="nav-text">প্রোডাক্টস</span>
                    </a>
                    <a href="?action=pages" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-file-invoice text-amber-500 w-5 text-center"></i> <span class="nav-text">পেজেস/ল্যান্ডিং</span>
                    </a>
                    <a href="?action=users" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-users text-indigo-500 w-5 text-center"></i> <span class="nav-text">ইউজার ম্যানেজার</span>
                    </a>
                    <a href="?action=branding" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-star text-yellow-400 w-5 text-center"></i> <span class="nav-text">ব্র্যান্ডিং</span>
                    </a>
                    <a href="?action=settings" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-gears text-teal-500 w-5 text-center"></i> <span class="nav-text">সেটিংস</span>
                    </a>
                <?php endif; ?>

                <?php if ($role === 'admin' || $role === 'office_team'): ?>
                    <a href="?action=inventory" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-warehouse text-sky-400 w-5 text-center"></i> <span class="nav-text">ইনভেন্টরি</span>
                    </a>
                    <a href="?action=media" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-images text-pink-400 w-5 text-center"></i> <span class="nav-text">মিডিয়া ফাইল</span>
                    </a>
                    <a href="?action=fraud_detection" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                        <i class="fa-solid fa-user-shield text-rose-400 w-5 text-center"></i> <span class="nav-text">ফ্রড ডিটেকশন</span>
                    </a>
                <?php endif; ?>

                <a href="?action=sip_dialer" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 nav-link">
                    <i class="fa-solid fa-phone-volume text-cyan-400 w-5 text-center"></i> <span class="nav-text">SIP ডায়ালার</span>
                </a>

                <button onclick="toggleDarkMode()" class="w-full flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 border border-transparent outline-none text-left nav-link">
                    <i class="fa-solid fa-circle-half-stroke text-purple-400 w-5 text-center"></i> <span class="nav-text" id="themeToggleText">লাইট মোড</span>
                </button>

                <!-- Feature 18: Language Toggle Bn -> EN -> Bn+EN -->
                <button onclick="toggleLanguageMode()" class="w-full flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-slate-800 transition text-slate-200 border border-transparent outline-none text-left nav-link" title="সব বাটন/টেবিল/টাইটেল ভাষা পরিবর্তন">
                    <i class="fa-solid fa-language text-lime-400 w-5 text-center"></i> <span class="nav-text">ভাষা: <span id="langModeLabel">বাং</span>/EN</span>
                </button>

                <div class="pt-6 border-t border-slate-800 mt-6">
                    <?php if (($role === 'admin' || $role === 'office_team') && $balance !== null): ?>
                        <div class="px-4 py-2 bg-slate-800/50 rounded-lg text-sm mb-4 quick-balance">
                            <span class="text-xs text-slate-400 block">Steadfast কুরিয়ার ব্যালেন্স</span>
                            <span class="font-bold text-emerald-400"><?= htmlspecialchars($balance) ?></span>
                        </div>
                    <?php endif; ?>
                    <a href="?action=logout" class="flex items-center gap-3 px-4 py-2.5 rounded-lg hover:bg-rose-950/40 text-rose-400 transition nav-link">
                        <i class="fa-solid fa-right-from-bracket w-5 text-center"></i> <span class="nav-text">লগআউট</span>
                    </a>
                </div>
            </nav>
        </aside>

        <!-- Main Content Panel -->
        <main class="flex-1 p-6 md:p-8 overflow-x-hidden">
        <script>
            if (window.innerWidth < 768) {
                // মোবাইলে সবসময় ভাঁজ অবস্থায় শুরু — হ্যামবার্গার আইকনে ট্যাপ করলে মেনু খুলবে
                document.getElementById('mainSidebar').classList.add('collapsed');
            } else if (localStorage.getItem('sidebar_collapsed') === 'collapsed') {
                document.getElementById('mainSidebar').classList.add('collapsed');
            }
            function toggleSidebarCollapse() {
                const sidebar = document.getElementById('mainSidebar');
                if (sidebar.classList.contains('collapsed')) {
                    sidebar.classList.remove('collapsed');
                    localStorage.setItem('sidebar_collapsed', 'expanded');
                } else {
                    sidebar.classList.add('collapsed');
                    localStorage.setItem('sidebar_collapsed', 'collapsed');
                }
            }
        </script>
    <?php
}

function render_dashboard_footer() {
    global $status_map, $status_map_en;
    ?>
        </main>

        <!-- অ্যাডমিন প্যানেল ফ্লোটিং স্ক্রল বাটন (ওপরে / নিচে যান) -->
        <div style="position: fixed; right: 12px; bottom: 18px; z-index: 90; display: flex; flex-direction: column; gap: 8px;">
            <button type="button" onclick="window.scrollTo({top: 0, behavior: 'smooth'})" title="একদম ওপরে যান"
                style="width: 28px; height: 28px; border-radius: 9999px; background: #6366f1; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 12px; box-shadow: 0 3px 9px rgba(99,102,241,.45); border: none; cursor: pointer; transition: transform .15s;"
                onmouseover="this.style.transform='scale(1.12)'" onmouseout="this.style.transform='scale(1)'">
                <i class="fa-solid fa-arrow-up"></i>
            </button>
            <button type="button" onclick="window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'})" title="একদম নিচে যান"
                style="width: 28px; height: 28px; border-radius: 9999px; background: #0ea5e9; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 12px; box-shadow: 0 3px 9px rgba(14,165,233,.45); border: none; cursor: pointer; transition: transform .15s;"
                onmouseover="this.style.transform='scale(1.12)'" onmouseout="this.style.transform='scale(1)'">
                <i class="fa-solid fa-arrow-down"></i>
            </button>
        </div>

        <!-- ম্যানুয়াল কুরিয়ার (Pathao/RedX) মোডাল -->
        <!-- WhatsApp টেমপ্লেট পিকার মোডাল -->
        <div id="waTemplateModal" class="hidden fixed inset-0 z-[170] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-md w-full p-6 text-slate-100 shadow-2xl relative">
                <button onclick="document.getElementById('waTemplateModal').classList.add('hidden')" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold">&times;</button>
                <h3 class="text-lg font-bold text-white mb-1 flex items-center gap-2"><i class="fa-brands fa-whatsapp text-emerald-400"></i> WhatsApp মেসেজ পাঠান</h3>
                <p id="waTplContact" class="text-[11px] text-slate-400 mb-4"></p>
                <p class="text-[10px] text-slate-500 mb-2 uppercase font-bold">একটি টেমপ্লেট বাছুন — WhatsApp খুলবে, মেসেজ লেখা থাকবে:</p>
                <div id="waTplList" class="space-y-2"></div>
                <div class="mt-3 pt-3 border-t border-slate-700">
                    <label class="block text-[10px] text-slate-500 mb-1">অথবা খালি চ্যাট খুলুন:</label>
                    <button type="button" onclick="waOpenBlank()" class="w-full bg-slate-700 hover:bg-slate-600 text-slate-200 text-xs font-bold py-2 rounded-lg"><i class="fa-solid fa-comment"></i> মেসেজ ছাড়াই চ্যাট খুলুন</button>
                </div>
            </div>
        </div>

        <div id="manualCourierModal" class="hidden fixed inset-0 z-[160] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-md w-full p-6 text-slate-100 shadow-2xl relative">
                <button onclick="document.getElementById('manualCourierModal').classList.add('hidden')" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold">&times;</button>
                <h3 class="text-lg font-bold text-white mb-1 flex items-center gap-2"><i class="fa-solid fa-truck text-indigo-400"></i> অন্য কুরিয়ারে বুক (ম্যানুয়াল)</h3>
                <p class="text-[11px] text-slate-400 mb-4">Pathao/RedX-এর মার্চেন্ট প্যানেলে বুক করে এখানে ট্র্যাকিং আইডি সেভ করুন — অর্ডার "কুরিয়ারে বুকড" হবে ও SMS যাবে (চালু থাকলে)।</p>
                <input type="hidden" id="mc-order-id" value="0">
                <label class="block text-xs text-slate-300 mb-1 font-bold">কুরিয়ার</label>
                <div class="flex gap-2 mb-3">
                    <a href="https://merchant.pathao.com" target="_blank" class="text-[10px] text-indigo-400 hover:underline mt-1 mr-auto">Pathao প্যানেল ↗</a>
                    <a href="https://redx.com.bd/dashboard" target="_blank" class="text-[10px] text-rose-400 hover:underline mt-1">RedX প্যানেল ↗</a>
                </div>
                <select id="mc-courier" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm mb-3">
                    <option value="Pathao">Pathao</option>
                    <option value="RedX">RedX</option>
                    <option value="Other">অন্যান্য</option>
                </select>
                <label class="block text-xs text-slate-300 mb-1 font-bold">ট্র্যাকিং / কনসাইনমেন্ট আইডি</label>
                <input type="text" id="mc-tracking" placeholder="যেমন: PA123456789" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono mb-4">
                <button type="button" onclick="saveManualCourier()" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-2.5 rounded-xl text-sm"><i class="fa-solid fa-floppy-disk"></i> সেভ করুন (বুকড হবে)</button>
            </div>
        </div>
        <script>
            function openManualCourier(oid) {
                document.getElementById('mc-order-id').value = oid;
                document.getElementById('mc-tracking').value = '';
                document.getElementById('manualCourierModal').classList.remove('hidden');
            }
            function saveManualCourier() {
                const fd = new FormData();
                fd.append('id', document.getElementById('mc-order-id').value);
                fd.append('courier_name', document.getElementById('mc-courier').value);
                fd.append('tracking', document.getElementById('mc-tracking').value.trim());
                fetch('?action=manual_courier', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(d => {
                        showToast(d.message, d.status === 'success' ? 'success' : 'error');
                        if (d.status === 'success') {
                            document.getElementById('manualCourierModal').classList.add('hidden');
                            if (document.getElementById('ordersTableWrap')) loadOrders(); else location.reload();
                        }
                    }).catch(() => showToast('সেভ করা যায়নি', 'error'));
            }
        </script>

        <!-- মিডিয়া পিকার মোডাল (OG ইমেজ/যেকোনো ইমেজ ফিল্ডে মিডিয়া থেকে বাছাই) -->
        <div id="mediaPickerModal" class="hidden fixed inset-0 z-[170] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-3xl w-full p-6 text-slate-100 shadow-2xl relative max-h-[85vh] flex flex-col">
                <button onclick="closeMediaPicker()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-images text-sky-400"></i> মিডিয়া থেকে ইমেজ বাছুন
                </h3>
                <div id="mediaPickerGrid" class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3 overflow-y-auto flex-1 pr-1"></div>
                <div class="text-center mt-4">
                    <button id="mediaPickerMoreBtn" onclick="loadPickerMedia(false)" class="hidden bg-sky-600 hover:bg-sky-500 text-white text-xs px-6 py-2 rounded-xl font-bold">আরো লোড করুন</button>
                    <p id="mediaPickerEmpty" class="hidden text-xs text-slate-400 py-4">কোনো ছবি নেই — আগে <a href="?action=media" class="text-sky-400 hover:underline">মিডিয়া ট্যাব</a> থেকে ছবি আপলোড করুন।</p>
                </div>
            </div>
        </div>
        <script>
            let mpTargetInput = null, mpTargetPreview = null, mpOffset = 0;
            function openMediaPicker(inputId, previewId) {
                mpTargetInput = inputId; mpTargetPreview = previewId || null; mpOffset = 0;
                document.getElementById('mediaPickerGrid').innerHTML = '';
                document.getElementById('mediaPickerModal').classList.remove('hidden');
                loadPickerMedia(true);
            }
            function closeMediaPicker() { document.getElementById('mediaPickerModal').classList.add('hidden'); }
            function loadPickerMedia(reset) {
                if (reset) { mpOffset = 0; document.getElementById('mediaPickerGrid').innerHTML = ''; }
                fetch('?action=media_list&offset=' + mpOffset)
                    .then(r => r.json())
                    .then(d => {
                        if (d.status !== 'success') return;
                        const grid = document.getElementById('mediaPickerGrid');
                        document.getElementById('mediaPickerEmpty').classList.toggle('hidden', !(d.total === 0));
                        d.files.forEach(f => {
                            const div = document.createElement('div');
                            div.className = 'aspect-square bg-slate-900 border-2 border-slate-700 hover:border-sky-500 rounded-xl overflow-hidden cursor-pointer transition';
                            div.innerHTML = '<img src="' + f.rel_url + '" onerror="this.onerror=null; this.src=\'' + f.file_url + '\';" loading="lazy" class="w-full h-full object-cover">';
                            div.onclick = () => {
                                const inp = document.getElementById(mpTargetInput);
                                if (inp) {
                                    inp.value = f.file_url;
                                    inp.dispatchEvent(new Event('input'));
                                }
                                if (mpTargetPreview) {
                                    const pv = document.getElementById(mpTargetPreview);
                                    if (pv) { pv.src = f.file_url; pv.style.display = 'block'; }
                                }
                                closeMediaPicker();
                                showToast('ইমেজ সিলেক্ট হয়েছে!', 'success');
                            };
                            grid.appendChild(div);
                        });
                        mpOffset += d.files.length;
                        document.getElementById('mediaPickerMoreBtn').classList.toggle('hidden', mpOffset >= d.total);
                    }).catch(() => showToast('মিডিয়া লোড করা যায়নি', 'error'));
            }
        </script>

        <!-- FraudShield Dynamic Report Modal Panel -->
        <div id="fraudDetailsModal" class="hidden fixed inset-0 z-[110] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-fade-in">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-lg w-full p-6 text-slate-100 shadow-2xl relative max-h-[90vh] overflow-y-auto">
                <button onclick="closeFraudModal()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>

                <div class="flex items-center gap-2.5 mb-6 border-b border-slate-700 pb-3">
                    <div class="w-10 h-10 bg-rose-500/10 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-shield-halved text-rose-400 text-lg"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-white">FraudShield&trade; ক্লায়েন্ট রিপোর্ট</h3>
                        <p class="text-[10px] text-slate-400 font-mono">মোবাইল: <span id="fraudModalPhone"></span></p>
                    </div>
                </div>

                <div id="fraudModalBody" class="space-y-4">
                </div>
            </div>
        </div>

        <!-- Custom Print Configure Modal Panel -->
        <div id="printSettingsModal" class="hidden fixed inset-0 z-[120] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm animate-fade-in">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-md w-full p-6 text-slate-100 shadow-2xl relative">
                <button onclick="closePrintModal()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>

                <div class="flex items-center gap-2.5 mb-6 border-b border-slate-700 pb-3">
                    <div class="w-10 h-10 bg-indigo-500/10 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-print text-indigo-400 text-lg"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-white">লেবেল প্রিন্ট কনফিগারেশন</h3>
                        <p class="text-[11px] text-slate-400">লেবেলে কোন কোন তথ্য প্রদর্শন করতে চান তা সিলেক্ট করুন</p>
                    </div>
                </div>
                <div id="printPreviewList" class="hidden mb-4"></div>
                <div class="hidden">
                </div>

                <input type="hidden" id="printSelectedType" value="80mm">

                <div class="space-y-4">
                    <div class="grid grid-cols-2 gap-3 text-xs">
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_name" checked class="rounded text-emerald-500"> গ্রাহকের নাম
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_phone" checked class="rounded text-emerald-500"> মোবাইল নম্বর
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer col-span-2">
                            <input type="checkbox" id="p_show_address" checked class="rounded text-emerald-500"> সম্পূর্ণ ঠিকানা
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_product" checked class="rounded text-emerald-500"> পণ্য টাইটেল
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_color" checked class="rounded text-emerald-500"> নির্বাচিত কালার/সাইজ/ওজন
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_consignment" checked class="rounded text-emerald-500"> কুরিয়ার কনসাইনমেন্ট ID
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer">
                            <input type="checkbox" id="p_show_cod" checked class="rounded text-emerald-500"> COD পরিমাণ
                        </label>
                        <label class="flex items-center gap-2 bg-slate-900/40 p-3 rounded-xl border border-slate-700 cursor-pointer col-span-2">
                            <input type="checkbox" id="p_show_footer" checked class="rounded text-emerald-500"> ধন্যবাদ বার্তা
                        </label>
                    </div>

                    <button onclick="confirmAndPrint()" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-sm py-3 rounded-xl transition shadow-lg mt-4 flex items-center justify-center gap-2">
                        <i class="fa-solid fa-print"></i> লেবেল প্রিন্ট করুন
                    </button>
                </div>
            </div>
        </div>

        <!-- Custom Dynamic Confirm Popup Modal -->
        <div id="customConfirmModal" class="hidden fixed inset-0 z-[150] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-sm w-full p-6 text-slate-100 shadow-2xl text-center">
                <div class="w-12 h-12 bg-amber-500/10 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa-solid fa-triangle-exclamation text-amber-500 text-xl"></i>
                </div>
                <h3 class="text-base font-bold text-white mb-2" id="confirmModalText">আপনি কি নিশ্চিত?</h3>
                <div class="flex gap-3 justify-center mt-6">
                    <button id="confirmBtnYes" class="bg-rose-600 hover:bg-rose-500 text-white px-5 py-2 rounded-xl text-xs font-bold transition">হ্যাঁ, নিশ্চিত</button>
                    <button onclick="closeConfirmModal()" class="bg-slate-700 hover:bg-slate-600 text-white px-5 py-2 rounded-xl text-xs font-bold transition">বাতিল</button>
                </div>
            </div>
        </div>

        <!-- Feature 14: Order Note View/Update Modal -->
        <div id="noteModal" class="hidden fixed inset-0 z-[140] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-md w-full p-6 text-slate-100 shadow-2xl relative">
                <button onclick="closeNoteModal()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>
                <div class="flex items-center gap-2.5 mb-4 border-b border-slate-700 pb-3">
                    <div class="w-10 h-10 bg-amber-500/10 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-note-sticky text-amber-400 text-lg"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-white">কাস্টমার নোট / কল আপডেট</h3>
                        <p class="text-[10px] text-slate-400 font-mono">অর্ডার আইডি: #<span id="noteModalOrderIdLabel"></span></p>
                    </div>
                </div>
                <input type="hidden" id="noteModalOrderId" value="">
                <textarea id="noteModalText" rows="5" placeholder="কাস্টমারের সাথে কী কথা হয়েছে বা কী নির্দেশনা দিয়েছে তা লিখুন..." class="w-full bg-slate-700 text-white rounded-xl px-3 py-2 border border-slate-600 outline-none text-sm"></textarea>
                <button onclick="saveOrderNote()" class="mt-4 w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-sm py-2.5 rounded-xl transition flex items-center justify-center gap-2">
                    <i class="fa-solid fa-floppy-disk"></i> নোট সেভ করুন
                </button>
            </div>
        </div>

        <!-- Feature 12: Loyal Customer Order History Modal -->
        <div id="custHistoryModal" class="hidden fixed inset-0 z-[130] flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm">
            <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-lg w-full p-6 text-slate-100 shadow-2xl relative max-h-[85vh] overflow-y-auto">
                <button onclick="closeCustHistoryModal()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>
                <div class="flex items-center gap-2.5 mb-4 border-b border-slate-700 pb-3">
                    <div class="w-10 h-10 bg-emerald-500/10 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-clock-rotate-left text-emerald-400 text-lg"></i>
                    </div>
                    <div>
                        <h3 class="text-base font-bold text-white">কাস্টমারের সকল অর্ডার হিস্টোরি</h3>
                        <p class="text-[10px] text-slate-400 font-mono">মোবাইল: <span id="custHistoryPhone"></span> | মোট অর্ডার: <span id="custHistoryTotal">0</span> টি</p>
                    </div>
                </div>
                <div id="custHistoryBody" class="space-y-2"></div>
            </div>
        </div>

        <!-- Toast Notifications Overlay -->
        <div id="toastContainer" class="fixed bottom-5 right-5 z-[200] space-y-2 pointer-events-none"></div>

        <!-- Real-Time Client Side Engine Controller -->
        <script>
            // Global config from server
            window.DIALER_MODE = '<?= htmlspecialchars(get_setting('dialer_mode') ?: 'tel') ?>';
            window.IS_ADMIN_OR_OFFICE = <?= in_array(get_user_role(), ['admin', 'office_team']) ? 'true' : 'false' ?>;
            window.SIP_DOMAIN = '<?= htmlspecialchars(get_setting('sip_domain') ?: '') ?>';
            window.STATUS_MAP_BN = <?= json_encode($status_map, JSON_UNESCAPED_UNICODE) ?>;
            window.STATUS_MAP_EN = <?= json_encode($status_map_en, JSON_UNESCAPED_UNICODE) ?>;

            function applyTheme() {
                const theme = localStorage.getItem('theme') || 'dark';
                const body = document.body;
                const toggleBtnText = document.getElementById('themeToggleText');
                if (theme === 'light') {
                    body.classList.add('light-mode');
                    if (toggleBtnText) toggleBtnText.innerText = 'ডার্ক মোড';
                } else {
                    body.classList.remove('light-mode');
                    if (toggleBtnText) toggleBtnText.innerText = 'লাইট মোড';
                }
            }
            function toggleDarkMode() {
                const currentTheme = localStorage.getItem('theme') || 'dark';
                const nextTheme = currentTheme === 'dark' ? 'light' : 'dark';
                localStorage.setItem('theme', nextTheme);
                applyTheme();
            }

            // ------------------------------------------------------------------
            // Feature 18: One-click language toggle (বাং -> EN -> বাং+EN -> বাং)
            // ------------------------------------------------------------------
            const LANG_MAP = {
                'ড্যাশবোর্ড': 'Dashboard', 'প্রোডাক্টস': 'Products', 'পেজেস/ল্যান্ডিং': 'Pages/Landing',
                'ইউজার ম্যানেজার': 'User Manager', 'সেটিংস': 'Settings', 'ইনভেন্টরি': 'Inventory',
                'মিডিয়া ফাইল': 'Media Files', 'ফ্রড ডিটেকশন': 'Fraud Detection', 'ইনকমপ্লিট অর্ডার': 'Incomplete Orders',
                'SIP ডায়ালার': 'SIP Dialer', 'ব্র্যান্ডিং': 'Branding', 'লগআউট': 'Logout',
                'লাইট মোড': 'Light Mode', 'ডার্ক মোড': 'Dark Mode',
                'অর্ডার তালিকা': 'Order List', 'অর্ডার আইডি': 'Order ID', 'গ্রাহকের তথ্য': 'Customer Info',
                'পণ্য ও ভ্যারিয়েন্ট': 'Product & Variant', 'পণ্য ও কালার': 'Product & Color',
                'COD মূল্য': 'COD Amount', 'স্ট্যাটাস': 'Status', 'কুরিয়ার ট্র্যাকিং': 'Courier Tracking',
                'ফ্রড চেক': 'Fraud Check', 'অ্যাকশন': 'Action', 'নোট': 'Note',
                'সর্বমোট অর্ডার': 'Total Orders', 'কল বাকি (পেন্ডিং)': 'Pending Calls', 'ডেলিভারড অর্ডার': 'Delivered Orders',
                'আজকের মোট বিক্রি': "Today's Sales", 'মোট মাল বিক্রি': 'Total Sales', 'ডিলিট করা অর্ডার': 'Deleted Orders',
                'অনুসন্ধান': 'Search', 'স্ট্যাটাস ফিল্টার': 'Status Filter', 'প্রোডাক্ট ফিল্টার': 'Product Filter',
                'কালার ফিল্টার': 'Color Filter', 'জোন / জেলা ফিল্টার': 'Zone / District Filter', 'তারিখের ফিল্টার': 'Date Filter',
                'প্রতি পেজে': 'Per Page', 'পেজ': 'Page', 'লাস্ট পেজ': 'Last Page', 'প্রথম পেজ': 'First Page',
                'প্রয়োগ করুন': 'Apply', '80mm প্রিন্ট': '80mm Print', '40mm প্রিন্ট': '40mm Print',
                'বুক কুরিয়ার': 'Book Courier', 'রিস্ক চেক': 'Risk Check', 'সম্পাদনা': 'Edit',
                'মুছে ফেলুন': 'Delete', 'রিসেট': 'Reset', 'সেভ প্রোডাক্ট': 'Save Product', 'সেভ পেজ': 'Save Page',
                'সেভ পরিবর্তন': 'Save Changes', 'পিছনে যান': 'Go Back', 'ডুপ্লিকেট': 'Duplicate',
                'নতুন প্রোডাক্ট তৈরি করুন': 'Create New Product', 'সকল প্রোডাক্টের তালিকা': 'All Products List',
                'নতুন ল্যান্ডিং পেজ তৈরি করুন': 'Create New Landing Page', 'সকল লাইভ পেজ ও ল্যান্ডিং সোর্স': 'All Live Pages & Landing Sources',
                'ইউজার ম্যানেজমেন্ট': 'User Management', 'সকল সক্রিয় টিম মেম্বার্স': 'All Active Team Members',
                'ইনভেন্টরি ম্যানেজার': 'Inventory Manager', 'ইনভেন্টরি প্রোডাক্ট লিস্ট': 'Inventory Product List',
                'রিটার্ন স্টক রিস্টক করুন': 'Restock Returned Items', 'স্টক আপডেট করুন': 'Update Stock',
                'মিডিয়া ফাইল ম্যানেজার': 'Media File Manager', 'ইমেজ আপলোড করুন': 'Upload Image',
                'লোড মোর': 'Load More', 'লিংক কপি': 'Copy Link', 'ক্রপ করুন': 'Crop', 'ডিলিট': 'Delete',
                'ব্লক করা কাস্টমার তালিকা': 'Blocked Customer List', 'নতুন ব্লক যোগ করুন': 'Add New Block',
                'ব্লক করুন': 'Block', 'রিমুভ': 'Remove', 'কারণ': 'Reason', 'মোবাইল নাম্বার': 'Mobile Number',
                'আইপি নাম্বার': 'IP Number', 'ইমেজ': 'Image', 'টাইটেল': 'Title', 'মূল্য (৳)': 'Price (৳)',
                'স্টক পিস': 'Stock Pcs', 'অটো-লিঙ্ক': 'Auto Link', 'অটো লিংক': 'Auto Link',
                'পেজ টাইটেল': 'Page Title', 'স্লাগ': 'Slug', 'পদক্ষেপ': 'Actions', 'আইডি': 'ID',
                'ইউজারনেম': 'Username', 'রোল': 'Role', 'যোগদানের তারিখ': 'Joined Date',
                'পণ্য টাইটেল': 'Product Title', 'ইনভেন্টরি স্টক': 'Inventory Stock', 'পণ্য মূল্য': 'Product Price',
                'গ্রাহকের নাম': 'Customer Name', 'ঠিকানা': 'Address', 'তারিখ': 'Date', 'সময়': 'Time',
                'সিস্টেম সেটিংস': 'System Settings', 'কনফিগারেশন সেভ করুন': 'Save Configuration',
                'সেভ এন্ড চেঞ্জ': 'Save & Change', 'অর্ডার তথ্য পরিবর্তন করুন': 'Edit Order Info',
                'নাম': 'Name', 'ফোন': 'Phone', 'পণ্য': 'Product', 'কালার': 'Color', 'সাইজ': 'Size', 'ওজন': 'Weight',
                'ভাষা': 'Language', 'সাইট ব্র্যান্ডিং': 'Site Branding', 'ইনকমপ্লিট অর্ডার ট্র্যাকিং': 'Incomplete Order Tracking'
            };
            const LANG_MAP_REVERSE = {};
            Object.keys(LANG_MAP).forEach(k => { LANG_MAP_REVERSE[LANG_MAP[k]] = k; });

            function applyLanguage() {
                const mode = localStorage.getItem('lang_mode') || 'bn'; // bn | en | both
                document.querySelectorAll('body *').forEach(el => {
                    if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE' || el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') return;
                    // only elements without element children (pure text) or already tagged
                    if (el.children.length > 0 && !el.dataset.i18n) return;
                    let key = el.dataset.i18n;
                    if (!key) {
                        const txt = (el.textContent || '').trim();
                        if (LANG_MAP[txt]) key = txt;
                        else if (LANG_MAP_REVERSE[txt]) key = LANG_MAP_REVERSE[txt];
                    }
                    if (!key || !LANG_MAP[key]) return;
                    el.dataset.i18n = key;
                    const en = LANG_MAP[key];
                    if (mode === 'en') el.textContent = en;
                    else if (mode === 'both') el.textContent = key + ' (' + en + ')';
                    else el.textContent = key;
                });
                const label = document.getElementById('langModeLabel');
                if (label) label.textContent = mode === 'bn' ? 'বাং' : (mode === 'en' ? 'EN' : 'বাং+EN');
            }
            function toggleLanguageMode() {
                const cur = localStorage.getItem('lang_mode') || 'bn';
                const next = cur === 'bn' ? 'en' : (cur === 'en' ? 'both' : 'bn');
                localStorage.setItem('lang_mode', next);
                applyLanguage();
                showToast(next === 'bn' ? 'ভাষা: বাংলা' : (next === 'en' ? 'Language: English' : 'ভাষা: বাংলা + English'), 'success');
            }

            // ------------------------------------------------------------------
            // Feature 11: Copy to clipboard (phone number, IP, media link)
            // ------------------------------------------------------------------
            function copyText(text) {
                const done = () => showToast('কপি হয়েছে: ' + text, 'success');
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(text).then(done).catch(() => fallbackCopy(text, done));
                } else {
                    fallbackCopy(text, done);
                }
            }
            function fallbackCopy(text, done) {
                const el = document.createElement('textarea');
                el.value = text;
                el.style.position = 'fixed';
                el.style.opacity = '0';
                document.body.appendChild(el);
                el.select();
                try { document.execCommand('copy'); done(); } catch (e) { showToast('কপি করা যায়নি!', 'error'); }
                el.remove();
            }
            // Feature 10: click-and-hold (long press) to copy IP
            function bindLongPressCopy(el, text) {
                if (!el) return;
                let timer = null;
                const start = () => { timer = setTimeout(() => copyText(text), 600); };
                const stop = () => { if (timer) clearTimeout(timer); };
                el.addEventListener('mousedown', start);
                el.addEventListener('mouseup', stop);
                el.addEventListener('mouseleave', stop);
                el.addEventListener('touchstart', start, { passive: true });
                el.addEventListener('touchend', stop);
            }

            // ------------------------------------------------------------------
            // Feature 8: Click-to-call using configured dialer mode
            // ------------------------------------------------------------------
            // ---- কুরিয়ার স্ট্যাটাস অটো সিঙ্ক (১ মিনিট পর পর, অন/অফ করা যায়) ----
            function courierSyncEnabled() {
                if (!window.IS_ADMIN_OR_OFFICE) return false; // কলিং এজেন্টে অটো সিঙ্ক সবসময় বন্ধ
                return localStorage.getItem('courierAutoSync') !== 'off';
            }
            function updateCourierSyncBtn() {
                const btn = document.getElementById('courierSyncToggle');
                if (!btn) return;
                if (!window.IS_ADMIN_OR_OFFICE) { btn.style.display = 'none'; return; } // এজেন্ট টগল বাটনও দেখবে না
                const on = courierSyncEnabled();
                btn.innerHTML = '<i class="fa-solid fa-rotate"></i> কুরিয়ার অটো সিঙ্ক: ' + (on ? 'চালু ✓' : 'বন্ধ');
                btn.className = 'text-xs font-bold px-4 py-2 rounded-xl border transition ' + (on ? 'bg-emerald-600/20 border-emerald-600 text-emerald-400' : 'bg-slate-800 border-slate-700 text-slate-400');
            }
            function toggleCourierSync() {
                if (!window.IS_ADMIN_OR_OFFICE) return;
                localStorage.setItem('courierAutoSync', courierSyncEnabled() ? 'off' : 'on');
                updateCourierSyncBtn();
                showToast('কুরিয়ার অটো সিঙ্ক ' + (courierSyncEnabled() ? 'চালু হয়েছে — ১ মিনিট পর পর স্টিডফাস্ট থেকে স্ট্যাটাস আসবে' : 'বন্ধ করা হয়েছে'), 'success');
                if (courierSyncEnabled()) runCourierSync();
            }
            let courierSyncBusy = false;
            function runCourierSync() {
                if (!document.getElementById('ordersTableWrap')) return; // শুধু ড্যাশবোর্ড পেজে
                if (!courierSyncEnabled() || courierSyncBusy) return;
                courierSyncBusy = true;
                fetch('?action=courier_sync')
                    .then(r => r.json())
                    .then(d => {
                        courierSyncBusy = false;
                        if (d.status === 'success' && d.updated && d.updated.length > 0) {
                            loadOrders(); // টেবিল সাইলেন্ট রিফ্রেশ — নতুন স্ট্যাটাস দেখাবে
                        }
                    })
                    .catch(() => { courierSyncBusy = false; });
            }
            setInterval(runCourierSync, 60000);
            document.addEventListener('DOMContentLoaded', () => {
                updateCourierSyncBtn();
                if (document.getElementById('ordersTableWrap')) setTimeout(runCourierSync, 3000);
            });

            // ==== WhatsApp টেমপ্লেট পিকার (web.whatsapp/অ্যাপ — API ছাড়া, wa.me লিংক) ====
            let waCur = { num: '', name: '', id: 0 };
            function openWaTemplates(num, name, orderId, product, cod, tracking) {
                if (!num) { showToast('এই অর্ডারে সঠিক WhatsApp নম্বর নেই।', 'error'); return; }
                waCur = { num: num, name: name, id: orderId };
                const shop = <?= json_encode(branding('site_name') ?: 'আমাদের শপ', JSON_UNESCAPED_UNICODE) ?>;
                const codTxt = (cod ? Math.round(cod).toLocaleString('en-US') : '0');
                // টেমপ্লেটগুলো — {ভেরিয়েবল} প্রি-ফিল করা
                const templates = [
                    { label: '✅ অর্ডার কনফার্মেশন', icon: 'fa-circle-check', color: 'emerald',
                      msg: 'আসসালামু আলাইকুম ' + name + '।\n\nআপনার অর্ডার #' + orderId + ' (' + (product || 'পণ্য') + ') আমরা পেয়েছি ✅\nমোট: ' + codTxt + ' টাকা (ক্যাশ অন ডেলিভারি)।\n\nঅর্ডারটি কনফার্ম করতে "হ্যাঁ" লিখে রিপ্লাই দিন। ধন্যবাদ — ' + shop },
                    { label: '🚚 কুরিয়ারে পাঠানো হয়েছে', icon: 'fa-truck', color: 'indigo',
                      msg: 'প্রিয় ' + name + ',\n\nআপনার অর্ডার #' + orderId + ' কুরিয়ারে পাঠানো হয়েছে 🚚' + (tracking ? '\nট্র্যাকিং: ' + tracking : '') + '\nডেলিভারিতে ' + codTxt + ' টাকা রেডি রাখবেন।\n\nধন্যবাদ — ' + shop },
                    { label: '📞 কল ধরুন', icon: 'fa-phone', color: 'cyan',
                      msg: 'আসসালামু আলাইকুম ' + name + '।\nআপনার অর্ডার #' + orderId + ' কনফার্মের জন্য আমরা কল দিচ্ছি কিন্তু ধরছেন না। অনুগ্রহ করে একটু সময় দিন অথবা এখানে রিপ্লাই দিন। — ' + shop },
                    { label: '💳 এডভান্স পেমেন্ট', icon: 'fa-wallet', color: 'amber',
                      msg: 'প্রিয় ' + name + ',\nআপনার অর্ডার #' + orderId + ' কনফার্ম করতে সামান্য এডভান্স পেমেন্ট প্রয়োজন। বিস্তারিত জানতে রিপ্লাই দিন। ধন্যবাদ — ' + shop }
                ];
                document.getElementById('waTplContact').innerHTML = '<b class="text-white">' + name + '</b> — <span class="font-mono">+' + num + '</span>';
                document.getElementById('waTplList').innerHTML = templates.map((t, i) =>
                    '<button type="button" onclick="waSend(' + i + ')" class="w-full text-left bg-slate-900/60 hover:bg-slate-700 border border-slate-700 hover:border-' + t.color + '-500 rounded-xl px-4 py-2.5 transition flex items-center gap-3">'
                    + '<i class="fa-solid ' + t.icon + ' text-' + t.color + '-400"></i>'
                    + '<span class="text-sm font-bold text-slate-200">' + t.label + '</span></button>'
                ).join('');
                window._waTemplates = templates;
                document.getElementById('waTemplateModal').classList.remove('hidden');
            }
            function waSend(i) {
                const t = window._waTemplates[i];
                window.open('https://wa.me/' + waCur.num + '?text=' + encodeURIComponent(t.msg), '_blank');
                document.getElementById('waTemplateModal').classList.add('hidden');
            }
            function waOpenBlank() {
                window.open('https://wa.me/' + waCur.num, '_blank');
                document.getElementById('waTemplateModal').classList.add('hidden');
            }

            // মূল অর্ডার লিস্ট থেকে জোন চেঞ্জ তালিকায় যোগ/বাদ
            function addToZoneList(id, btn) {
                fetch('?action=toggle_zone_flag&id=' + id)
                    .then(r => r.json())
                    .then(d => {
                        showToast(d.message, d.status === 'success' ? 'success' : 'error');
                        if (d.status === 'success') {
                            // বাটনের রঙ টগল
                            if (d.flagged) { btn.classList.add('text-orange-400'); btn.classList.remove('text-slate-500'); btn.classList.add('bg-orange-600'); }
                            else { btn.classList.remove('text-orange-400'); btn.classList.add('text-slate-500'); btn.classList.remove('bg-orange-600'); }
                        }
                    }).catch(() => showToast('আপডেট ব্যর্থ', 'error'));
            }

            function dialCustomer(phone, orderId, customerName) {
                const mode = window.DIALER_MODE || 'tel';
                const domain = window.SIP_DOMAIN || '';
                if (mode === 'webrtc') {
                    // ওয়েব ডায়ালার পেজে নাম্বার নিয়ে যাওয়া হবে (অর্ডার আইডি ও কাস্টমার নামসহ)
                    let url = '?action=sip_dialer&dial=' + encodeURIComponent(phone);
                    if (orderId) url += '&dial_order=' + encodeURIComponent(orderId);
                    if (customerName) url += '&dial_name=' + encodeURIComponent(customerName);
                    window.location.href = url;
                    return;
                }
                let href = 'tel:' + phone;
                if (mode === 'sip' && domain) href = 'sip:' + phone + '@' + domain;
                else if (mode === 'sip' && !domain) { showToast('SIP ডোমেইন কনফিগার করা হয়নি! SIP ডায়ালার ট্যাব থেকে সেট করুন।', 'error'); return; }
                else if (mode === 'callto') href = 'callto:' + phone;
                window.location.href = href;
            }

            function closeFraudModal() {
                document.getElementById('fraudDetailsModal').classList.add('hidden');
            }
            function closePrintModal() {
                document.getElementById('printSettingsModal').classList.add('hidden');
            }
            function confirmAndPrint() {
                const type = document.getElementById('printSelectedType').value;
                const checked = document.querySelectorAll('.order-chk:checked');
                const ids = Array.from(checked).map(chk => chk.value).join(',');

                const showName = document.getElementById('p_show_name').checked ? '1' : '0';
                const showPhone = document.getElementById('p_show_phone').checked ? '1' : '0';
                const showAddress = document.getElementById('p_show_address').checked ? '1' : '0';
                const showProduct = document.getElementById('p_show_product').checked ? '1' : '0';
                const showColor = document.getElementById('p_show_color').checked ? '1' : '0';
                const showConsignment = document.getElementById('p_show_consignment').checked ? '1' : '0';
                const showCod = document.getElementById('p_show_cod').checked ? '1' : '0';
                const showFooter = document.getElementById('p_show_footer').checked ? '1' : '0';

                const url = `?action=invoice&type=${type}&ids=${ids}&show_name=${showName}&show_phone=${showPhone}&show_address=${showAddress}&show_product=${showProduct}&show_color=${showColor}&show_consignment=${showConsignment}&show_cod=${showCod}&show_footer=${showFooter}`;

                closePrintModal();
                window.open(url, '_blank');
            }

            let currentConfirmCallback = null;
            function showConfirmModal(text, callback) {
                document.getElementById('confirmModalText').innerText = text;
                currentConfirmCallback = callback;
                document.getElementById('customConfirmModal').classList.remove('hidden');
            }
            // Feature 20: double confirmation before delete
            function showDoubleConfirm(text1, text2, callback) {
                // ২ আর্গুমেন্টে কল হলে (text, callback) হিসেবে ধরা হবে
                if (typeof text2 === 'function') {
                    callback = text2;
                    text2 = 'আপনি কি সম্পূর্ণ নিশ্চিত? এই কাজটি আর ফেরানো যাবে না!';
                }
                showConfirmModal(text1, () => {
                    setTimeout(() => { showConfirmModal(text2, callback); }, 150);
                });
            }
            function closeConfirmModal() {
                document.getElementById('customConfirmModal').classList.add('hidden');
                currentConfirmCallback = null;
            }
            document.getElementById('confirmBtnYes').addEventListener('click', () => {
                const cb = currentConfirmCallback;
                closeConfirmModal();
                if (cb) cb();
            });

            function showToast(message, type = 'success') {
                const container = document.getElementById('toastContainer');
                const toast = document.createElement('div');
                toast.className = `p-4 rounded-xl shadow-xl border text-xs font-bold transition-all duration-300 transform translate-y-2 pointer-events-auto flex items-center gap-2 animate-fade-in ${
                    type === 'success'
                    ? 'bg-emerald-600/20 text-emerald-400 border-emerald-500/30'
                    : 'bg-rose-600/20 text-rose-400 border-rose-500/30'
                }`;
                toast.innerHTML = `<i class="fa-solid ${type === 'success' ? 'fa-circle-check' : 'fa-circle-exclamation'}"></i> <span>${message}</span>`;
                container.appendChild(toast);
                setTimeout(() => {
                    toast.classList.add('opacity-0', 'translate-y-0');
                    setTimeout(() => toast.remove(), 300);
                }, 3000);
            }

            // ------------------------------------------------------------------
            // Realtime order status change (used by orders table select)
            // ------------------------------------------------------------------
            function saveOrderStatus(id, status, selectEl) {
                fetch('?action=ajax_update_status&id=' + id + '&status=' + encodeURIComponent(status))
                    .then(r => r.json())
                    .then(d => {
                        if (d.status === 'success') {
                            showToast(d.message, 'success');
                        } else {
                            showToast(d.message || 'স্ট্যাটাস আপডেট ব্যর্থ!', 'error');
                        }
                    })
                    .catch(() => showToast('নেটওয়ার্ক ত্রুটি! স্ট্যাটাস আপডেট হয়নি।', 'error'));
            }

            // ------------------------------------------------------------------
            // Feature 14: Note modal
            // ------------------------------------------------------------------
            function openNoteModal(id, el) {
                document.getElementById('noteModalOrderId').value = id;
                document.getElementById('noteModalOrderIdLabel').innerText = id;
                document.getElementById('noteModalText').value = (el && el.dataset && el.dataset.note) ? el.dataset.note : '';
                document.getElementById('noteModal').classList.remove('hidden');
            }
            function closeNoteModal() {
                document.getElementById('noteModal').classList.add('hidden');
            }
            function saveOrderNote() {
                const id = document.getElementById('noteModalOrderId').value;
                const note = document.getElementById('noteModalText').value;
                const body = new URLSearchParams();
                body.set('id', id);
                body.set('note', note);
                fetch('?action=ajax_save_note', { method: 'POST', body: body })
                    .then(r => r.json())
                    .then(d => {
                        if (d.status === 'success') {
                            showToast(d.message, 'success');
                            closeNoteModal();
                            const icon = document.querySelector('.note-icon-btn[data-oid="' + id + '"]');
                            if (icon) { icon.dataset.note = note; icon.title = note || 'কোনো নোট নেই'; }
                        } else {
                            showToast(d.message || 'নোট সেভ ব্যর্থ!', 'error');
                        }
                    })
                    .catch(() => showToast('নেটওয়ার্ক ত্রুটি! নোট সেভ হয়নি।', 'error'));
            }

            // ------------------------------------------------------------------
            // Feature 12: Loyal customer - full order history modal
            // ------------------------------------------------------------------
            let lastHistoryPhone = '';
            function histToggleDelete(oid, mode) {
                const msg = mode === 'delete'
                    ? 'অর্ডার #' + oid + ' ডিলিট (রিসাইকেল বিনে) হবে — লয়াল কাউন্টেও আর ধরা হবে না। নিশ্চিত?'
                    : 'অর্ডার #' + oid + ' রিস্টোর হয়ে আবার অর্ডার তালিকায় ফিরে আসবে। নিশ্চিত?';
                showConfirmModal(msg, () => {
                    const fd = new FormData();
                    fd.append('id', oid);
                    fd.append('mode', mode);
                    fetch('?action=ajax_toggle_order_delete', { method: 'POST', body: fd })
                        .then(r => r.json())
                        .then(d => {
                            showToast(d.message || (d.status === 'success' ? 'সম্পন্ন' : 'ব্যর্থ'), d.status === 'success' ? 'success' : 'error');
                            if (d.status === 'success') {
                                if (lastHistoryPhone) showCustomerHistory(lastHistoryPhone); // মোডাল রিফ্রেশ
                                if (typeof loadOrders === 'function' && document.getElementById('ordersTableWrap')) loadOrders();
                            }
                        }).catch(() => showToast('কাজটি সম্পন্ন করা যায়নি', 'error'));
                });
            }

            function showCustomerHistory(phone) {
                lastHistoryPhone = phone;
                const modal = document.getElementById('custHistoryModal');
                const body = document.getElementById('custHistoryBody');
                document.getElementById('custHistoryPhone').innerText = phone;
                document.getElementById('custHistoryTotal').innerText = '...';
                body.innerHTML = '<div class="text-center py-8 text-slate-400"><i class="fa-solid fa-spinner animate-spin text-2xl mb-2 block"></i> হিস্টোরি লোড হচ্ছে...</div>';
                modal.classList.remove('hidden');

                fetch('?action=ajax_customer_history&phone=' + encodeURIComponent(phone))
                    .then(r => r.json())
                    .then(d => {
                        if (d.status !== 'success') {
                            body.innerHTML = '<p class="text-xs text-center py-6 text-rose-400">হিস্টোরি লোড করা যায়নি।</p>';
                            return;
                        }
                        document.getElementById('custHistoryTotal').innerText = d.total + (d.total_all > d.total ? ' (+' + (d.total_all - d.total) + ' ডিলিটেড)' : '');
                        if (!d.orders.length) {
                            body.innerHTML = '<p class="text-xs text-center py-6 text-slate-400">এই নাম্বারে কোনো অর্ডার পাওয়া যায়নি।</p>';
                            return;
                        }
                        let html = '';
                        d.orders.forEach(o => {
                            const badge = o.is_deleted
                                ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-400">ডিলিট করা</span>'
                                : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-600/40 text-slate-200">' + o.status_label + '</span>';
                            let variants = '';
                            if (o.color) variants += ' | কালার: ' + o.color;
                            if (o.size) variants += ' | সাইজ: ' + o.size;
                            if (o.weight) variants += ' | ওজন: ' + o.weight;
                            html += `
                                <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-3 text-xs flex items-start justify-between gap-2">
                                    <div>
                                        <div class="font-bold text-white">#${o.id} — ${o.product}</div>
                                        <div class="text-slate-400 mt-0.5">${o.created_at}${variants}</div>
                                    </div>
                                    <div class="text-right space-y-1">
                                        ${badge}
                                        <div class="font-mono font-bold text-emerald-400">${o.cod} ৳</div>
                                        <a href="?action=order_detail&id=${o.id}" class="text-indigo-400 hover:underline text-[10px] block">বিস্তারিত দেখুন</a>
                                        ${window.IS_ADMIN_OR_OFFICE ? (o.is_deleted
                                            ? '<button type="button" onclick="histToggleDelete(' + o.id + ', \'restore\')" class="text-emerald-400 hover:text-emerald-300 text-[10px] font-bold block w-full text-right"><i class="fa-solid fa-rotate-left"></i> রিস্টোর করুন</button>'
                                            : '<button type="button" onclick="histToggleDelete(' + o.id + ', \'delete\')" class="text-rose-400 hover:text-rose-300 text-[10px] font-bold block w-full text-right"><i class="fa-solid fa-trash"></i> ডিলিট করুন</button>') : ''}
                                    </div>
                                </div>`;
                        });
                        body.innerHTML = html;
                    })
                    .catch(() => {
                        body.innerHTML = '<p class="text-xs text-center py-6 text-rose-400">নেটওয়ার্ক ত্রুটি!</p>';
                    });
            }
            function closeCustHistoryModal() {
                document.getElementById('custHistoryModal').classList.add('hidden');
            }

            // ------------------------------------------------------------------
            // Feature 15: AJAX orders table reload (no full page refresh)
            //   + Feature 1: pagination navigation
            // ------------------------------------------------------------------
            let searchTimer = null;
            let refocusSearch = false;
            function loadOrders(page) {
                const form = document.getElementById('filterForm');
                if (!form) return;
                if (page !== undefined && page !== null) {
                    const pi = document.getElementById('pageInput');
                    if (pi) pi.value = page;
                }
                const params = new URLSearchParams(new FormData(form));
                const url = '?' + params.toString();
                const wrap = document.getElementById('ordersTableWrap');
                if (!wrap) { window.location.href = url; return; }
                wrap.style.opacity = '0.45';
                fetch(url + '&ajax=1')
                    .then(r => r.text())
                    .then(html => {
                        wrap.innerHTML = html;
                        wrap.style.opacity = '1';
                        applyLanguage();
                        if (refocusSearch) {
                            const si = document.getElementById('searchInput');
                            if (si) {
                                si.focus();
                                const len = si.value.length;
                                si.setSelectionRange(len, len);
                            }
                            refocusSearch = false;
                        }
                    })
                    .catch(() => {
                        wrap.style.opacity = '1';
                        showToast('অর্ডার তালিকা লোড করা যায়নি!', 'error');
                    });
                try { history.replaceState(null, '', url); } catch (e) {}
            }
            function filterChanged() {
                loadOrders(1);
            }
            function toggleCustomDates(val) {
                const box = document.getElementById('customDateInputs');
                if (!box) return;
                if (val === 'custom') box.classList.remove('hidden');
                else box.classList.add('hidden');
            }

            // Delegated events (survive AJAX table replacement)
            document.addEventListener('input', function (e) {
                if (e.target && e.target.id === 'searchInput') {
                    clearTimeout(searchTimer);
                    searchTimer = setTimeout(() => {
                        refocusSearch = true;
                        loadOrders(1);
                    }, 450);
                }
            });
            document.addEventListener('change', function (e) {
                if (e.target && e.target.id === 'selectAll') {
                    document.querySelectorAll('.order-chk').forEach(cb => cb.checked = e.target.checked);
                    showBulkCount();
                } else if (e.target && e.target.classList.contains('order-chk')) {
                    showBulkCount();
                }
            });
            // বাল্ক সিলেক্ট কাউন্ট পপআপ
            // বাল্ক সাবমিট গার্ড: একবার ক্লিকেই সাবমিট হবে, দ্বিতীয়বার ব্লকড (ডাবল বুকিং ঠেকাতে)
            let bulkSubmitting = false;
            function handleBulkSubmit(form) {
                if (bulkSubmitting) return false; // ইতিমধ্যে সাবমিট হচ্ছে
                const op = form.querySelector('[name="bulk_op"]') ? form.querySelector('[name="bulk_op"]').value : '';
                const checked = form.querySelectorAll('.order-chk:checked').length;
                if (!op) { showToast('অনুগ্রহ করে একটি বাল্ক অপশন নির্বাচন করুন।', 'error'); return false; }
                if (checked === 0) { showToast('অন্তত একটি অর্ডার সিলেক্ট করুন।', 'error'); return false; }
                // কুরিয়ার বুকিং হলে বাড়তি কনফার্মেশন — ভুল করে দুবার পাঠানো ঠেকাতে
                if (op === 'book_steadfast') {
                    if (!confirm('⚠️ নিশ্চিত করুন:\n\n' + checked + ' টি অর্ডার স্টিডফাস্ট কুরিয়ারে বুক হবে।\n\nইতিমধ্যে বুক করা অর্ডার স্বয়ংক্রিয়ভাবে বাদ পড়বে — একই পার্সেল দুবার যাবে না।\n\nএগিয়ে যাবেন?')) {
                        return false;
                    }
                }
                // সাবমিট লক — বাটন নিষ্ক্রিয় করে দ্বিতীয় ক্লিক ব্লক
                bulkSubmitting = true;
                const btn = document.getElementById('bulkApplyBtn');
                if (btn) { btn.disabled = true; btn.innerText = 'প্রসেস হচ্ছে... অপেক্ষা করুন'; }
                return true;
            }

            function showBulkCount() {
                const n = document.querySelectorAll('.order-chk:checked').length;
                showToast(n > 0 ? ('✅ ' + n + ' টি অর্ডার সিলেক্ট হয়েছে') : 'কোনো অর্ডার সিলেক্টেড নেই', n > 0 ? 'success' : 'error');
            }

            function printSelected(type) {
                const checked = document.querySelectorAll('.order-chk:checked');
                if (checked.length === 0) {
                    showToast('অনুগ্রহ করে প্রিন্ট করার জন্য ন্যূনতম একটি অর্ডার সিলেক্ট করুন।', 'error');
                    return;
                }
                document.getElementById('printSelectedType').value = type;
                // প্রিভিউ: কী কী প্রিন্ট হবে (নাম ছাড়া — অর্ডার নং + প্রোডাক্ট + COD)
                const pv = document.getElementById('printPreviewList');
                if (pv) {
                    let html = '<div class="text-xs font-bold text-emerald-400 mb-2">🖨️ মোট ' + checked.length + ' টি ইনভয়েস প্রিন্ট হবে:</div><div class="max-h-40 overflow-y-auto space-y-1">';
                    checked.forEach(cb => {
                        html += '<div class="flex justify-between gap-2 text-[11px] bg-slate-900/60 border border-slate-700 rounded-lg px-3 py-1.5">'
                              + '<span class="font-mono font-bold text-white">#' + cb.value + '</span>'
                              + '<span class="text-slate-300 truncate flex-1 text-center">' + (cb.dataset.product || '—') + '</span>'
                              + '<span class="font-mono text-emerald-400">' + (cb.dataset.cod || '') + '৳</span>'
                              + '</div>';
                    });
                    html += '</div>';
                    pv.innerHTML = html;
                    pv.classList.remove('hidden');
                }
                document.getElementById('printSettingsModal').classList.remove('hidden');
            }

            function triggerFraudCheck(phone, btn) {
                btn.innerText = 'চেকিং...';
                btn.disabled = true;
                fetch('?action=ajax_fraud_check&phone=' + encodeURIComponent(phone))
                    .then(r => r.text())
                    .then(text => {
                        let d;
                        try { d = JSON.parse(text); } catch (err) { d = { status: 'error', message: 'API থেকে সঠিক ডাটা আসেনি।' }; }
                        if (d.status === 'error') {
                            showToast('API Error: ' + d.message, 'error');
                            btn.innerText = 'রিস্ক চেক';
                            btn.disabled = false;
                            return;
                        }
                        if (d.fraudRiskScore !== undefined) {
                            btn.outerHTML = `<button type="button" onclick="showFraudDetails('${phone}')" class="mx-auto px-2 py-0.5 rounded text-[11px] font-bold block hover:opacity-80 transition ${d.fraudRiskScore.score >= 70 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400'}">ঝুঁকি: ${d.fraudRiskScore.score}%</button>`;
                            showToast('ফ্রড ডাটা সফলভাবে রিট্রিভ করা হয়েছে!', 'success');
                        } else {
                            btn.innerText = 'ব্যর্থ!';
                            btn.disabled = false;
                        }
                    })
                    .catch(() => {
                        btn.innerText = 'ত্রুটি!';
                        btn.disabled = false;
                    });
            }

            function bookSteadfast(id, btn) {
                btn.innerText = 'বুকিং হচ্ছে...';
                btn.disabled = true;
                fetch('?action=book_courier&id=' + id)
                    .then(r => r.json())
                    .then(d => {
                        if (d.status === 'success') {
                            showToast('অর্ডার বুকিং সফল হয়েছে! Consignment ID: ' + (d.consignment_id || ''), 'success');
                            setTimeout(() => {
                                if (document.getElementById('ordersTableWrap')) loadOrders();
                                else location.reload();
                            }, 800);
                        } else if (d.status === 'already') {
                            // ইতিমধ্যে বুকড — বাটন নিষ্ক্রিয় রেখে জানানো, আবার পাঠানোর সুযোগ নেই
                            showToast(d.message, 'error');
                            btn.innerText = '✓ বুকড';
                            setTimeout(() => {
                                if (document.getElementById('ordersTableWrap')) loadOrders();
                                else location.reload();
                            }, 1200);
                        } else {
                            showToast(d.message, 'error');
                            btn.innerText = 'বুক কুরিয়ার';
                            btn.disabled = false;
                        }
                    })
                    .catch(() => {
                        showToast('সিস্টেম নেটওয়ার্ক ত্রুটি!', 'error');
                        btn.innerText = 'বুক কুরিয়ার';
                        btn.disabled = false;
                    });
            }

            // Feature 17 FIX: robust JSON parsing so "Unexpected end of JSON input" never surfaces
            function showFraudDetails(phone) {
                const modal = document.getElementById('fraudDetailsModal');
                const modalPhone = document.getElementById('fraudModalPhone');
                const modalBody = document.getElementById('fraudModalBody');

                modalPhone.innerText = phone;
                modalBody.innerHTML = '<div class="text-center py-8 text-slate-400"><i class="fa-solid fa-spinner animate-spin text-2xl mb-2 block"></i> ডাটা লোড হচ্ছে...</div>';
                modal.classList.remove('hidden');

                fetch('?action=ajax_get_fraud_details&phone=' + encodeURIComponent(phone))
                    .then(r => r.text())
                    .then(text => {
                        let d;
                        try {
                            d = JSON.parse(text);
                        } catch (err) {
                            modalBody.innerHTML = '<p class="text-xs text-center py-6 text-rose-400">API থেকে সঠিক JSON ডাটা পাওয়া যায়নি। FraudShield API Key ও URL সেটিংসে সঠিকভাবে দেওয়া আছে কিনা যাচাই করুন।</p>';
                            return;
                        }
                        if (!d || d.status === 'error') {
                            modalBody.innerHTML = `<p class="text-xs text-center py-6 text-rose-400">${(d && d.message) ? d.message : 'ডাটা রিট্রিভ করা যায়নি।'}</p>`;
                            return;
                        }

                        const risk = d.fraudRiskScore || {};
                        const score = risk.score !== undefined ? risk.score : 0;
                        const label = risk.label || 'N/A';
                        const summary = d.summary || (d.courierData ? (d.courierData.summary || {}) : {});

                        let riskColor = 'text-emerald-400';
                        let riskBg = 'bg-emerald-500/10 border-emerald-500/30';
                        if (score >= 40 && score < 70) {
                            riskColor = 'text-amber-400';
                            riskBg = 'bg-amber-500/10 border-amber-500/30';
                        } else if (score >= 70) {
                            riskColor = 'text-rose-400';
                            riskBg = 'bg-rose-500/10 border-rose-500/30';
                        }

                        let html = `
                            <div class="grid grid-cols-2 gap-4">
                                <div class="p-4 rounded-2xl border ${riskBg} flex flex-col items-center justify-center">
                                    <span class="text-[10px] text-slate-400 uppercase tracking-widest block font-bold">ঝুঁকির হার</span>
                                    <span class="text-3xl font-extrabold ${riskColor} mt-1">${score}%</span>
                                </div>
                                <div class="p-4 rounded-2xl border border-slate-700 bg-slate-900/40 flex flex-col items-center justify-center">
                                    <span class="text-[10px] text-slate-400 uppercase tracking-widest block font-bold">নিরাপত্তা স্তর</span>
                                    <span class="text-base font-bold ${riskColor} mt-2">${label}</span>
                                </div>
                            </div>

                            <div class="border border-slate-700 bg-slate-900/60 p-4 rounded-2xl">
                                <h4 class="text-xs font-bold text-white uppercase tracking-wider mb-2 border-b border-slate-800 pb-1.5 flex items-center gap-1.5">
                                    <i class="fa-solid fa-chart-simple text-indigo-400"></i> কুরিয়ার ডেলিভারি সামারি
                                </h4>
                                <div class="grid grid-cols-2 gap-y-2 text-xs">
                                    <div><span class="text-slate-400">সর্বমোট পার্সেল:</span> <span class="font-bold text-slate-100">${summary.total_parcel ?? 0} টি</span></div>
                                    <div><strong class="text-slate-400">ডেলিভারি সাকসেস:</strong> <span class="font-bold text-emerald-400">${summary.success_parcel ?? 0} টি</span></div>
                                    <div><strong class="text-slate-400">ক্যানসেল পার্সেল:</strong> <span class="font-bold text-rose-400">${summary.cancelled_parcel ?? 0} টি</span></div>
                                    <div><strong class="text-slate-400">সফলতার হার:</strong> <span class="font-bold text-sky-400">${summary.success_ratio ?? 0}%</span></div>
                                </div>
                            </div>
                        `;

                        const couriers = ['steadfast', 'pathao', 'redx', 'paperfly', 'carrybee', 'parceldex'];
                        let courierHtml = '';

                        couriers.forEach(c => {
                            if (d.courierData && d.courierData[c]) {
                                const details = d.courierData[c];
                                courierHtml += `
                                    <div class="flex items-center justify-between text-xs py-1.5 border-b border-slate-800 last:border-0">
                                        <span class="font-semibold text-slate-300 flex items-center gap-1.5">
                                            <i class="fa-solid fa-truck-fast text-slate-500 text-[10px]"></i> ${details.name}
                                        </span>
                                        <span class="font-mono text-slate-400">
                                            মোট: <b class="text-white">${details.total_parcel}</b> |
                                            সফল: <b class="text-emerald-400">${details.success_parcel}</b> |
                                            ক্যানসেল: <b class="text-rose-400">${details.cancelled_parcel}</b> (${details.success_ratio}%)
                                        </span>
                                    </div>
                                `;
                            }
                        });

                        if (courierHtml) {
                            html += `
                                <div class="border border-slate-700 bg-slate-900/60 p-4 rounded-2xl">
                                    <h4 class="text-xs font-bold text-white uppercase tracking-wider mb-2 border-b border-slate-800 pb-1.5">কুরিয়ার ভিত্তিক বিশ্লেষণ</h4>
                                    <div class="space-y-1">${courierHtml}</div>
                                </div>
                            `;
                        }

                        if (d.reviews && d.reviews.length > 0) {
                            let reviewHtml = '';
                            d.reviews.forEach(r => {
                                reviewHtml += `
                                    <div class="bg-slate-950/40 p-2.5 rounded-lg border border-slate-800 mb-2 last:mb-0 text-xs">
                                        <div class="flex justify-between font-bold text-amber-400 mb-1">
                                            <span>${r.name || 'Anonymous'} (রেটিং: ${r.rating}/5)</span>
                                            <span class="text-[10px] text-slate-500 font-normal">${new Date(r.created_at).toLocaleDateString('bn-BD')}</span>
                                        </div>
                                        <p class="text-slate-300 text-[11px] leading-relaxed italic">"${r.comment}"</p>
                                    </div>
                                `;
                            });

                            html += `
                                <div class="border border-slate-700 bg-slate-900/60 p-4 rounded-2xl max-h-48 overflow-y-auto">
                                    <h4 class="text-xs font-bold text-white uppercase tracking-wider mb-2 border-b border-slate-800 pb-1.5 flex items-center gap-1.5">
                                        <i class="fa-solid fa-comments text-amber-400"></i> মার্চেন্ট রিভিউসমূহ
                                    </h4>
                                    <div>${reviewHtml}</div>
                                </div>
                            `;
                        }

                        modalBody.innerHTML = html;
                    })
                    .catch(err => {
                        modalBody.innerHTML = `<p class="text-xs text-center py-6 text-rose-400">ডাটা রিট্রিভ করতে সমস্যা হয়েছে: ${err.message}</p>`;
                    });
            }

            applyTheme();
            applyLanguage();
        </script>
    </body>
    </html>
    <?php
}

function render_analytics_tiles($total, $pending, $delivered, $sales, $deleted_count, $total_sales = 0, $incomplete_count = 0, $today_orders = 0) {
    $role = get_user_role();
    ?>
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-8 font-semibold">
        <?php if ($role !== 'agent'): // কলিং এজেন্টে সর্বমোট/আজকের/ডেলিভারড টাইল দেখাবে না ?>
        <a href="?action=dashboard" class="block bg-slate-800 p-5 rounded-2xl border border-slate-700 shadow-md hover:border-slate-400 transition group" title="ক্লিক করলে সব অর্ডার একসাথে দেখাবে">
            <span class="text-slate-400 text-xs font-semibold uppercase block flex items-center gap-1.5">সর্বমোট অর্ডার <i class="fa-solid fa-arrow-up-right-from-square text-[9px] opacity-60 group-hover:opacity-100"></i></span>
            <div class="flex items-baseline gap-2 mt-2">
                <span class="text-2xl font-extrabold text-white"><?= number_format($total) ?></span>
                <span class="text-xs text-slate-400">টি</span>
            </div>
        </a>

        <a href="?action=dashboard&date_filter=today" class="block bg-cyan-950/30 p-5 rounded-2xl border border-cyan-900/40 shadow-md hover:border-cyan-500 transition group" title="ক্লিক করলে শুধু আজকের অর্ডারগুলো দেখাবে">
            <span class="text-cyan-400 text-xs font-semibold uppercase block flex items-center gap-1.5">আজকের অর্ডার <i class="fa-solid fa-arrow-up-right-from-square text-[9px] opacity-60 group-hover:opacity-100"></i></span>
            <div class="flex items-baseline gap-2 mt-2">
                <span class="text-2xl font-extrabold text-cyan-300"><?= number_format($today_orders) ?></span>
                <span class="text-xs text-cyan-400">টি</span>
            </div>
        </a>
        <?php endif; ?>

        <a href="?action=dashboard&status_filter=pending" class="block bg-amber-950/30 p-5 rounded-2xl border border-amber-900/40 shadow-md hover:border-amber-500 transition group" title="ক্লিক করলে সব 'কল বাকি' অর্ডার একসাথে দেখাবে">
            <span class="text-amber-400 text-xs font-semibold uppercase block flex items-center gap-1.5">কল বাকি (পেন্ডিং) <i class="fa-solid fa-arrow-up-right-from-square text-[9px] opacity-60 group-hover:opacity-100"></i></span>
            <div class="flex items-baseline gap-2 mt-2">
                <span class="text-2xl font-extrabold text-amber-300"><?= number_format($pending) ?></span>
                <span class="text-xs text-amber-400">টি</span>
            </div>
        </a>

        <?php if ($role !== 'agent'): ?>
        <a href="?action=dashboard&status_filter=delivered" class="block bg-emerald-950/30 p-5 rounded-2xl border border-emerald-900/40 shadow-md hover:border-emerald-500 transition group" title="ক্লিক করলে সব ডেলিভারড অর্ডার একসাথে দেখাবে">
            <span class="text-emerald-400 text-xs font-semibold uppercase block flex items-center gap-1.5">ডেলিভারড অর্ডার <i class="fa-solid fa-arrow-up-right-from-square text-[9px] opacity-60 group-hover:opacity-100"></i></span>
            <div class="flex items-baseline gap-2 mt-2">
                <span class="text-2xl font-extrabold text-emerald-300"><?= number_format($delivered) ?></span>
                <span class="text-xs text-slate-400">টি</span>
            </div>
        </a>
        <?php endif; ?>

        <a href="?action=incomplete_orders" class="block bg-orange-950/30 p-5 rounded-2xl border border-orange-900/40 shadow-md hover:border-orange-500 transition group" title="ইনকমপ্লিট অর্ডার তালিকা দেখুন">
            <span class="text-orange-400 text-xs font-semibold uppercase block flex items-center gap-1.5">ইনকমপ্লিট অর্ডার <i class="fa-solid fa-arrow-up-right-from-square text-[9px] opacity-60 group-hover:opacity-100"></i></span>
            <div class="flex items-baseline gap-2 mt-2">
                <span class="text-2xl font-extrabold text-orange-300"><?= number_format($incomplete_count) ?></span>
                <span class="text-xs text-slate-400">টি</span>
            </div>
        </a>

        <?php if ($role === 'admin' || $role === 'office_team'): ?>
            <div class="bg-indigo-950/30 p-5 rounded-2xl border border-indigo-900/40 shadow-md">
                <span class="text-indigo-400 text-xs font-semibold uppercase block">আজকের মোট বিক্রি</span>
                <div class="flex items-baseline gap-2 mt-2">
                    <span class="text-2xl font-extrabold text-indigo-300"><?= number_format($sales, 2) ?></span>
                    <span class="text-xs text-indigo-400">BDT</span>
                </div>
            </div>

            <!-- Feature 4: Total sold amount -->
            <div class="bg-sky-950/30 p-5 rounded-2xl border border-sky-900/40 shadow-md">
                <span class="text-sky-400 text-xs font-semibold uppercase block">মোট মাল বিক্রি</span>
                <div class="flex items-baseline gap-2 mt-2">
                    <span class="text-2xl font-extrabold text-sky-300"><?= number_format($total_sales, 2) ?></span>
                    <span class="text-xs text-sky-400">BDT</span>
                </div>
                <span class="text-[10px] text-slate-400 block mt-1">কনফার্ম + বুকড + ডেলিভারড</span>
            </div>

            <!-- Feature 4: Deleted orders/customers count with quick link to the list -->
            <a href="?action=dashboard&status_filter=deleted" class="bg-rose-950/30 p-5 rounded-2xl border border-rose-900/40 shadow-md block hover:opacity-90 transition">
                <span class="text-rose-400 text-xs font-semibold uppercase block">ডিলিট করা অর্ডার</span>
                <div class="flex items-baseline gap-2 mt-2">
                    <span class="text-2xl font-extrabold text-rose-300"><?= number_format($deleted_count) ?></span>
                    <span class="text-xs text-rose-400">টি</span>
                </div>
                <span class="text-[10px] text-slate-400 block mt-1">ডিলিট করা কাস্টমার লিস্ট দেখুন &rarr;</span>
            </a>
        <?php else: ?>
            <div class="bg-slate-800 p-5 rounded-2xl border border-slate-700 shadow-md">
                <span class="text-slate-400 text-xs font-semibold uppercase block">সক্রিয় ড্যাশবোর্ড</span>
                <div class="flex items-baseline gap-2 mt-2">
                    <span class="text-sm text-slate-400">কলিং এজেন্ট প্যানেল</span>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <?php
}

// Feature 1: pagination bar (1,2,3,4,5 ... last page + per page 25/50/100)
function render_pagination_bar($page, $per_page, $total_filtered, $total_pages) {
    ?>
    <div class="p-4 bg-slate-900 border-t border-slate-700 flex flex-wrap items-center justify-between gap-3">
        <div class="flex items-center gap-2 text-xs text-slate-400">
            <span>প্রতি পেজে</span>
            <select name="per_page" form="filterForm" onchange="loadOrders(1)" class="bg-slate-800 text-white text-xs border border-slate-700 rounded px-2 py-1 outline-none font-semibold">
                <option value="25" <?= $per_page == 25 ? 'selected' : '' ?>>২৫ টি</option>
                <option value="50" <?= $per_page == 50 ? 'selected' : '' ?>>৫০ টি</option>
                <option value="100" <?= $per_page == 100 ? 'selected' : '' ?>>১০০ টি</option>
            </select>
            <span class="hidden sm:inline">| মোট <?= enToBnNumber(number_format($total_filtered)) ?> টি অর্ডার | পেজ <?= enToBnNumber($page) ?>/<?= enToBnNumber($total_pages) ?></span>
        </div>

        <input type="hidden" name="page" id="pageInput" form="filterForm" value="<?= (int)$page ?>">

        <div class="flex items-center gap-1 flex-wrap">
            <?php
            $btn_base = 'min-w-[34px] px-2 py-1.5 rounded-lg text-xs font-bold transition border ';
            $btn_off = $btn_base . 'bg-slate-800 text-slate-300 border-slate-700 hover:bg-slate-700';
            $btn_on = $btn_base . 'bg-emerald-600 text-white border-emerald-500';

            if ($page > 1): ?>
                <button type="button" onclick="loadOrders(1)" class="<?= $btn_off ?>" title="প্রথম পেজ"><i class="fa-solid fa-angles-left"></i></button>
                <button type="button" onclick="loadOrders(<?= $page - 1 ?>)" class="<?= $btn_off ?>" title="আগের পেজ"><i class="fa-solid fa-angle-left"></i></button>
            <?php endif;

            // Windowed page numbers: max 5 around current
            $win_start = max(1, $page - 2);
            $win_end = min($total_pages, $win_start + 4);
            $win_start = max(1, $win_end - 4);

            if ($win_start > 1) {
                echo '<span class="text-slate-500 px-1">...</span>';
            }
            for ($p = $win_start; $p <= $win_end; $p++): ?>
                <button type="button" onclick="loadOrders(<?= $p ?>)" class="<?= $p == $page ? $btn_on : $btn_off ?>"><?= enToBnNumber($p) ?></button>
            <?php endfor;

            if ($win_end < $total_pages) {
                echo '<span class="text-slate-500 px-1">...</span>';
                echo '<button type="button" onclick="loadOrders(' . $total_pages . ')" class="' . $btn_off . '" title="লাস্ট পেজ">' . enToBnNumber($total_pages) . ' (লাস্ট)</button>';
            }

            if ($page < $total_pages): ?>
                <button type="button" onclick="loadOrders(<?= $page + 1 ?>)" class="<?= $btn_off ?>" title="নেক্সট পেজ"><i class="fa-solid fa-angle-right"></i></button>
                <button type="button" onclick="loadOrders(<?= $total_pages ?>)" class="<?= $btn_off ?>" title="লাস্ট পেজ"><i class="fa-solid fa-angles-right"></i></button>
            <?php endif; ?>
        </div>
    </div>
    <?php
}

function render_orders_table($orders, $search, $status_filter, $date_filter, $start_date, $end_date, $product_filter, $color_filter, $zone_filter, $page = 1, $per_page = 100, $total_filtered = 0, $total_pages = 1, $order_rank = [], $phone_totals = [], $courier_filter = '') {
    global $status_map, $zone_to_bangla, $db;
    $role = get_user_role();

    $filter_products = $db->query("SELECT id, title FROM products ORDER BY id DESC")->fetchAll();
    $filter_colors = json_decode(get_setting('product_colors'), true) ?: [];
    ?>
    <div class="bg-slate-800 rounded-2xl border border-slate-700 overflow-hidden shadow-lg mb-8 font-semibold">
        <div class="p-6 border-b border-slate-700 bg-slate-800/80 flex flex-col gap-4">
            <div class="flex flex-col md:flex-row gap-4 items-center justify-between">
                <h3 class="text-xl font-bold text-white flex items-center gap-2">
                    <i class="fa-solid fa-list text-emerald-400"></i> <span>অর্ডার তালিকা</span>
                </h3>
            </div>

            <form id="filterForm" method="GET" onsubmit="loadOrders(1); return false;" class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 w-full">
                <input type="hidden" name="action" value="dashboard">

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">অনুসন্ধান</label>
                    <input type="text" name="search" id="searchInput" value="<?= htmlspecialchars($search) ?>" placeholder="নাম, ফোন বা আইডি সার্চ..." autocomplete="off" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm outline-none focus:border-emerald-500 border border-slate-600">
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">স্ট্যাটাস ফিল্টার</label>
                    <select name="status_filter" onchange="filterChanged()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="">All Orders</option>
                        <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Call Pending</option>
                        <option value="confirmed" <?= $status_filter === 'confirmed' ? 'selected' : '' ?>>Confirmed</option>
                        <option value="no_answer" <?= $status_filter === 'no_answer' ? 'selected' : '' ?>>No Answer</option>
                        <option value="cancelled" <?= $status_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        <option value="interested_later" <?= $status_filter === 'interested_later' ? 'selected' : '' ?>>Interested Later</option>
                        <option value="did_not_order" <?= $status_filter === 'did_not_order' ? 'selected' : '' ?>>Did Not Order</option>
                        <option value="phone_off" <?= $status_filter === 'phone_off' ? 'selected' : '' ?>>Phone Off</option>
                        <option value="booked" <?= $status_filter === 'booked' ? 'selected' : '' ?>>Booked (Courier)</option>
                        <option value="delivered" <?= $status_filter === 'delivered' ? 'selected' : '' ?>>Delivered</option>
                        <?php if ($role === 'admin'): ?>
                            <option value="deleted" <?= $status_filter === 'deleted' ? 'selected' : '' ?>>রিসাইকেল বিন (Deleted)</option>
                        <?php endif; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold" data-i18n="কুরিয়ার স্ট্যাটাস">কুরিয়ার স্ট্যাটাস</label>
                    <select name="courier_filter" onchange="filterChanged()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="">সকল কুরিয়ার স্ট্যাটাস</option>
                        <option value="not_booked" <?= $courier_filter === 'not_booked' ? 'selected' : '' ?>>বুক করা হয়নি</option>
                        <option value="no_status" <?= $courier_filter === 'no_status' ? 'selected' : '' ?>>বুকড — স্ট্যাটাস আসেনি</option>
                        <option value="in_review" <?= $courier_filter === 'in_review' ? 'selected' : '' ?>>In Review — পারসেল বুক</option>
                        <option value="pending" <?= $courier_filter === 'pending' ? 'selected' : '' ?>>Pending — ডেলিভারি বাকি</option>
                        <option value="hold" <?= $courier_filter === 'hold' ? 'selected' : '' ?>>Hold — আটকে আছে</option>
                        <option value="delivered" <?= $courier_filter === 'delivered' ? 'selected' : '' ?>>Delivered — ডেলিভারি সম্পন্ন</option>
                        <option value="partial_delivered" <?= $courier_filter === 'partial_delivered' ? 'selected' : '' ?>>Partly — আংশিক/রিটার্ন</option>
                        <option value="cancelled" <?= $courier_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled — ক্যান্সেল</option>
                        <option value="approval_any" <?= $courier_filter === 'approval_any' ? 'selected' : '' ?>>Approval Pending — অনুমোদনের অপেক্ষায়</option>
                        <option value="zone_not_clear" <?= $courier_filter === 'zone_not_clear' ? 'selected' : '' ?>>⚠️ Zone not clear — জোন সিলেক্ট হয়নি</option>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">প্রোডাক্ট ফিল্টার</label>
                    <select name="product_filter" onchange="filterChanged()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="0">সকল প্রোডাক্ট</option>
                        <?php foreach ($filter_products as $p_item): ?>
                            <option value="<?= $p_item['id'] ?>" <?= (int)$product_filter === (int)$p_item['id'] ? 'selected' : '' ?>><?= htmlspecialchars($p_item['title']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">কালার ফিল্টার</label>
                    <select name="color_filter" onchange="filterChanged()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="">সকল কালার</option>
                        <?php foreach ($filter_colors as $c_item): ?>
                            <option value="<?= htmlspecialchars($c_item['en']) ?>" <?= $color_filter === $c_item['en'] ? 'selected' : '' ?>><?= htmlspecialchars($c_item['bn'] ?: $c_item['en']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">জোন / জেলা ফিল্টার</label>
                    <select name="zone_filter" onchange="filterChanged()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="">সকল জোন</option>
                        <?php foreach ($zone_to_bangla as $en_dist => $bn_dist): ?>
                            <option value="<?= $en_dist ?>" <?= $zone_filter === $en_dist ? 'selected' : '' ?>><?= $en_dist ?> (<?= $bn_dist ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">তারিখের ফিল্টার</label>
                    <select name="date_filter" id="dateFilterSelect" onchange="toggleCustomDates(this.value); if(this.value !== 'custom') filterChanged();" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 text-sm border border-slate-600 outline-none font-semibold">
                        <option value="">সকল সময়ের</option>
                        <option value="today" <?= $date_filter === 'today' ? 'selected' : '' ?>>আজকের অর্ডার</option>
                        <option value="yesterday" <?= $date_filter === 'yesterday' ? 'selected' : '' ?>>গতকালের অর্ডার</option>
                        <option value="last_7" <?= $date_filter === 'last_7' ? 'selected' : '' ?>>গত ৭ দিনের অর্ডার</option>
                        <option value="last_30" <?= $date_filter === 'last_30' ? 'selected' : '' ?>>গত ৩০ দিনের অর্ডার</option>
                        <option value="custom" <?= $date_filter === 'custom' ? 'selected' : '' ?>>কাস্টম ডেট অর্ডার</option>
                    </select>
                </div>
            </form>

            <div id="customDateInputs" class="<?= $date_filter === 'custom' ? '' : 'hidden' ?> grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2 border-t border-slate-700/60 font-semibold">
                <div class="w-full flex gap-4">
                    <div class="flex-1">
                        <label class="block text-xs text-slate-400 mb-1">শুরুর তারিখ</label>
                        <input type="date" form="filterForm" name="start_date" value="<?= htmlspecialchars($start_date) ?>" onchange="if(document.getElementsByName('end_date')[0].value) filterChanged();" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-sm border border-slate-600 font-semibold">
                    </div>
                    <div class="flex-1">
                        <label class="block text-xs text-slate-400 mb-1">শেষের তারিখ</label>
                        <input type="date" form="filterForm" name="end_date" value="<?= htmlspecialchars($end_date) ?>" onchange="if(document.getElementsByName('start_date')[0].value) filterChanged();" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-sm border border-slate-600 font-semibold">
                    </div>
                </div>
            </div>
        </div>

        <form id="bulkForm" action="?action=bulk_action" method="POST" onsubmit="return handleBulkSubmit(this)">
            <div class="hidden md:block overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="bg-slate-900 border-b border-slate-700 text-slate-300 text-sm">
                            <th class="p-4 w-12 text-center">
                                <input type="checkbox" id="selectAll" class="rounded text-emerald-600">
                            </th>
                            <th class="p-4">অর্ডার আইডি</th>
                            <th class="p-4">গ্রাহকের তথ্য</th>
                            <th class="p-4">পণ্য ও ভ্যারিয়েন্ট</th>
                            <th class="p-4 text-center">COD মূল্য</th>
                            <th class="p-4 text-center">স্ট্যাটাস</th>
                            <th class="p-4 text-center">কুরিয়ার ট্র্যাকিং</th>
                            <th class="p-4 text-center">ফ্রড চেক</th>
                            <th class="p-4 text-right">অ্যাকশন</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700">
                        <?php if (empty($orders)): ?>
                            <tr>
                                <td colspan="9" class="p-8 text-center text-slate-400">কোনো অর্ডার খুঁজে পাওয়া যায়নি।</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($orders as $order):
                                $rank = $order_rank[$order['id']] ?? 1;
                                $ptotal = $phone_totals[$order['phone']] ?? 1;
                                $note_attr = htmlspecialchars($order['note'] ?? '', ENT_QUOTES);
                                ?>
                                <tr class="hover:bg-slate-750 transition text-sm">
                                    <td class="p-4 text-center">
                                        <input type="checkbox" name="order_ids[]" value="<?= $order['id'] ?>" data-product="<?= htmlspecialchars(mb_substr($order['product_title'] ?? '', 0, 35), ENT_QUOTES) ?>" data-cod="<?= (float)$order['cod_amount'] ?>" class="order-chk rounded text-emerald-600">
                                    </td>
                                    <td class="p-4 font-mono font-bold text-slate-300 whitespace-nowrap">
                                        #<?= $order['id'] ?>
                                        <!-- Feature 8: Click-to-call icon (via configured SIP/tel dialer) -->
                                        <button type="button" onclick="dialCustomer('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>')" title="ডায়ালার দিয়ে কল করুন" class="ml-1 inline-flex items-center justify-center w-6 h-6 rounded-lg bg-cyan-600/20 text-cyan-400 hover:bg-cyan-600 hover:text-white transition text-[10px]">
                                            <i class="fa-solid fa-headset"></i>
                                        </button>
                                        <!-- অর্ডারের তারিখ ও সময় -->
                                        <span class="block mt-1 text-[10px] font-normal text-slate-400 whitespace-nowrap" title="অর্ডার করার তারিখ ও সময়">
                                            <i class="fa-regular fa-calendar text-emerald-500"></i> <?= date('d M Y', strtotime($order['created_at'])) ?>
                                        </span>
                                        <span class="block text-[10px] font-normal text-slate-500 whitespace-nowrap">
                                            <i class="fa-regular fa-clock text-sky-500"></i> <?= date('h:i A', strtotime($order['created_at'])) ?>
                                        </span>
                                        <?php if ($rank > 1): ?>
                                            <!-- Feature 12: Loyal customer badge -->
                                            <span class="block mt-1 bg-amber-500/15 text-amber-400 text-[10px] px-1.5 py-0.5 rounded font-bold border border-amber-500/30 whitespace-nowrap">
                                                <i class="fa-solid fa-crown text-[9px]"></i> <?= bnOrdinal($rank) ?> বার
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4">
                                        <div class="font-bold text-white"><?= htmlspecialchars($order['customer_name']) ?></div>
                                        <div class="text-xs text-slate-400 flex items-center gap-1.5 mt-1 flex-wrap">
                                            <!-- Feature 12: click number to see full history -->
                                            <span class="cursor-pointer hover:text-emerald-300 underline decoration-dotted <?= $ptotal > 1 ? 'text-amber-300 font-bold' : '' ?>" onclick="showCustomerHistory('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" title="সকল অর্ডার হিস্টোরি দেখুন">
                                                <i class="fa-solid fa-phone text-emerald-500"></i> <?= htmlspecialchars($order['phone']) ?>
                                            </span>
                                            <!-- Feature 11: copy phone icon -->
                                            <button type="button" onclick="copyText('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" title="নাম্বার কপি করুন" class="hover:text-white bg-slate-700 p-1 rounded-lg flex items-center justify-center w-6 h-6">
                                                <i class="fa-regular fa-copy"></i>
                                            </button>
                                            <a href="tel:<?= $order['phone'] ?>" class="hover:text-emerald-300 bg-slate-700 p-1.5 rounded-lg flex items-center justify-center w-6 h-6" title="সরাসরি কল">
                                                <i class="fa-solid fa-phone"></i>
                                            </a>
                                            <button type="button" onclick="openWaTemplates('<?= wa_number($order['phone']) ?>', '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars(mb_substr($order['product_title'] ?? '', 0, 40), ENT_QUOTES) ?>', <?= (float)$order['cod_amount'] ?>, '<?= htmlspecialchars($order['tracking_code'] ?? '', ENT_QUOTES) ?>')" class="text-emerald-400 hover:text-emerald-300" title="হোয়াটসঅ্যাপ মেসেজ"><i class="fa-brands fa-whatsapp"></i></button>
                                            <?php if ($role !== 'agent'): // জোন চেঞ্জ লিস্টে যোগ (এজেন্ট নয়) ?>
                                            <button type="button" onclick="addToZoneList(<?= (int)$order['id'] ?>, this)" class="<?= !empty($order['zone_change_flag']) ? 'text-orange-400' : 'text-slate-500 hover:text-orange-400' ?>" title="<?= !empty($order['zone_change_flag']) ? 'জোন চেঞ্জ তালিকায় আছে' : 'জোন চেঞ্জ তালিকায় যোগ করুন' ?>"><i class="fa-solid fa-map-location-dot"></i></button>
                                            <?php endif; ?>
                                            <?php if ($ptotal > 1): ?>
                                                <span class="bg-amber-500/15 text-amber-400 text-[10px] px-1.5 py-0.5 rounded font-bold border border-amber-500/30">লয়াল: <?= enToBnNumber($ptotal) ?> অর্ডার</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-xs text-slate-300 mt-2 max-w-xs break-words leading-relaxed font-semibold">
                                            <i class="fa-solid fa-location-dot text-rose-500 mr-1 text-[11px]"></i><?= htmlspecialchars($order['address']) ?>
                                            <?php
                                            $detected_zone = detectBanglaDistrict($order['address']);
                                            if ($detected_zone): ?>
                                                <span class="inline-block bg-emerald-500/10 text-emerald-400 text-[10px] px-1.5 py-0.5 rounded ml-1 font-bold uppercase tracking-wider">
                                                    <i class="fa-solid fa-map-pin"></i> Zone: <?= $detected_zone ?>
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td class="p-4">
                                        <div class="text-sm font-bold text-slate-200 break-words"><?= htmlspecialchars($order['product_title'] ?? 'Dynamic Item') ?></div>
                                        <div class="text-xs text-amber-400 mt-1 flex items-center gap-1 font-semibold flex-wrap">
                                            <i class="fa-solid fa-palette text-[10px]"></i> কালার: <?= htmlspecialchars($order['color_selected'] ?: 'N/A') ?>
                                        </div>
                                        <?php if (!empty($order['size_selected'])): ?>
                                            <div class="text-xs text-sky-400 mt-0.5 font-semibold"><i class="fa-solid fa-ruler text-[10px]"></i> সাইজ: <?= htmlspecialchars($order['size_selected']) ?></div>
                                        <?php endif; ?>
                                        <?php if (!empty($order['weight_selected'])): ?>
                                            <div class="text-xs text-lime-400 mt-0.5 font-semibold"><i class="fa-solid fa-weight-hanging text-[10px]"></i> ওজন: <?= htmlspecialchars($order['weight_selected']) ?></div>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-center font-bold text-emerald-400 whitespace-nowrap">
                                        <?= number_format($order['cod_amount'], 2) ?> ৳
                                        <?php if (!empty($order['delivery_charge']) && $order['delivery_charge'] > 0): ?>
                                            <span class="block text-[9px] font-semibold text-sky-400" title="ডেলিভারি চার্জ (<?= htmlspecialchars(delivery_zone_bn($order['delivery_zone'] ?? '')) ?>)"><i class="fa-solid fa-truck-fast"></i> +৳<?= number_format($order['delivery_charge']) ?> <?= htmlspecialchars(delivery_zone_bn($order['delivery_zone'] ?? '')) ?></span>
                                        <?php endif; ?>
                                        <?php if (!empty($order['discount_amount']) && $order['discount_amount'] > 0): ?>
                                            <span class="block text-[9px] font-semibold text-fuchsia-400" title="প্রোমো ছাড়"><i class="fa-solid fa-ticket"></i> −৳<?= number_format($order['discount_amount']) ?><?= !empty($order['promo_code']) ? ' (' . htmlspecialchars($order['promo_code']) . ')' : '' ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-center">
                                        <?php $st_style = get_status_style($order['status']); ?>
                                        <select onchange="saveOrderStatus(<?= $order['id'] ?>, this.value, this)" class="text-white rounded-lg px-2.5 py-1.5 text-xs border outline-none font-bold select-auto transition-all cursor-pointer <?= $st_style ?>">
                                            <?php foreach ($status_map as $val => $lbl): ?>
                                                <?php if ($val === 'booked' && $role === 'agent') continue; ?>
                                                <option value="<?= $val ?>" <?= $order['status'] === $val ? 'selected' : '' ?> class="bg-slate-800 text-white font-semibold"><?= $lbl ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td class="p-4 text-center font-semibold">
                                        <?php if ($order['tracking_code']): ?>
                                            <span class="font-mono text-xs bg-slate-700 px-2 py-1 rounded text-slate-300 block mb-0.5">Tracking: <?= htmlspecialchars($order['tracking_code']) ?></span>
                                            <!-- Feature 6: consignment id shown as a Steadfast link -->
                                            <?php if (!empty($order['consignment_id'])): ?>
                                                <a href="https://steadfast.com.bd/user/consignment/<?= urlencode($order['consignment_id']) ?>" target="_blank" class="font-mono text-[11px] bg-emerald-950/40 px-2 py-0.5 rounded text-emerald-400 block mb-0.5 hover:underline hover:text-emerald-300" title="Steadfast পোর্টালে দেখুন">
                                                    <i class="fa-solid fa-arrow-up-right-from-square text-[9px]"></i> CID: <?= htmlspecialchars($order['consignment_id']) ?>
                                                </a>
                                            <?php else: ?>
                                                <span class="font-mono text-[10px] text-slate-500 block mb-0.5">CID পাওয়া যায়নি</span>
                                            <?php endif; ?>
                                            <?php if (!empty($order['courier_name']) && $order['courier_name'] !== 'Steadfast'): ?>
                                                <span class="text-[9px] font-bold bg-indigo-500/20 text-indigo-300 px-2 py-0.5 rounded-full block w-fit mx-auto mb-0.5"><i class="fa-solid fa-truck"></i> <?= htmlspecialchars($order['courier_name']) ?></span>
                                            <?php endif; ?>
                                            <?php
                                            // কুরিয়ার লাইভ স্ট্যাটাস (১ মিনিট পর পর অটো সিঙ্ক হয়)
                                            if (!empty($order['courier_status'])):
                                                $cs_info = courier_status_info($order['courier_status']);
                                            ?>
                                                <span class="text-[10px] font-bold px-2 py-0.5 rounded-full block w-fit mx-auto mb-0.5 <?= $cs_info[1] ?>"><?= htmlspecialchars($cs_info[0]) ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($order['courier_note'])): ?>
                                                <span class="text-[9px] text-slate-400 block max-w-[180px] mx-auto break-words leading-tight" title="কুরিয়ারের সর্বশেষ নোট"><i class="fa-solid fa-comment-dots text-sky-400"></i> <?= htmlspecialchars(mb_substr($order['courier_note'], 0, 120)) ?></span>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <?php if ($role === 'admin' || $role === 'office_team'): ?>
                                                <div class="inline-flex items-center gap-1">
                                                    <button type="button" onclick="bookSteadfast(<?= $order['id'] ?>, this)" class="bg-blue-600 hover:bg-blue-500 text-white text-xs px-2.5 py-1 rounded shadow-sm transition" title="Steadfast API দিয়ে অটো বুক">Steadfast বুক</button>
                                                    <button type="button" onclick="openManualCourier(<?= $order['id'] ?>)" class="bg-slate-600 hover:bg-slate-500 text-white text-xs px-2 py-1 rounded shadow-sm transition" title="Pathao/RedX-এ বুক করে ট্র্যাকিং আইডি সেভ করুন"><i class="fa-solid fa-truck"></i>+</button>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-[10px] text-slate-500 font-bold block">বুকিং করা হয়নি</span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-center font-bold">
                                        <?php if ($order['fraud_score'] !== null): ?>
                                            <button type="button" onclick="showFraudDetails('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" class="mx-auto px-2 py-0.5 rounded text-[11px] font-bold block hover:opacity-80 transition <?= $order['fraud_score'] >= 70 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400' ?>">
                                                ঝুঁকি: <?= $order['fraud_score'] ?>%
                                            </button>
                                        <?php else: ?>
                                            <button type="button" onclick="triggerFraudCheck('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', this)" class="text-xs text-amber-400 hover:underline">রিস্ক চেক</button>
                                        <?php endif; ?>
                                        <?php if (!empty($order['customer_ip'])): ?>
                                            <span class="block mt-1 text-[10px] font-mono text-slate-400 cursor-pointer hover:text-white" onclick="copyText('<?= htmlspecialchars($order['customer_ip'], ENT_QUOTES) ?>')" title="ক্লিক করে আইপি কপি করুন">
                                                <i class="fa-solid fa-network-wired text-[9px]"></i> <?= htmlspecialchars($order['customer_ip']) ?>
                                            </span>
                                        <?php endif; ?>
                                        <?php if (!empty($order['custom_field_value'])): ?>
                                            <span class="block mt-1 text-[10px] bg-fuchsia-500/15 text-fuchsia-300 px-2 py-0.5 rounded w-fit mx-auto max-w-[180px] break-words" title="<?= htmlspecialchars($order['custom_field_label'] ?? 'কাস্টম ফিল্ড') ?>">📝 <?= htmlspecialchars(mb_substr($order['custom_field_value'], 0, 60)) ?></span>
                                        <?php endif; ?>
                                        <?php if (!empty($order['advance_trx']) || !empty($order['advance_proof_url'])): ?>
                                            <?php if (!empty($order['advance_proof_url'])): ?>
                                                <a href="<?= htmlspecialchars($order['advance_proof_url']) ?>" target="_blank" class="block mt-1 text-[10px] font-bold bg-violet-500/20 text-violet-300 px-2 py-0.5 rounded-full w-fit mx-auto hover:bg-violet-500/40" title="এডভান্স পেমেন্টের স্ক্রিনশট দেখুন">💰 এডভান্স প্রুফ</a>
                                            <?php else: ?>
                                                <span class="block mt-1 text-[10px] font-bold bg-violet-500/20 text-violet-300 px-2 py-0.5 rounded-full w-fit mx-auto cursor-pointer" onclick="copyText('<?= htmlspecialchars($order['advance_trx'], ENT_QUOTES) ?>')" title="TrxID কপি করুন: <?= htmlspecialchars($order['advance_trx']) ?>">💰 Trx: <?= htmlspecialchars(mb_substr($order['advance_trx'], 0, 10)) ?></span>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                    <td class="p-4 text-right space-x-1 whitespace-nowrap">
                                        <!-- Feature 14: note icon (hover shows note, click opens editor) -->
                                        <button type="button" data-oid="<?= $order['id'] ?>" data-note="<?= $note_attr ?>" title="<?= $note_attr !== '' ? $note_attr : 'কোনো নোট নেই' ?>" onclick="openNoteModal(<?= $order['id'] ?>, this)" class="note-icon-btn inline-flex items-center justify-center <?= $note_attr !== '' ? 'bg-amber-500/20 text-amber-400 border border-amber-500/40' : 'bg-slate-700 text-slate-400' ?> hover:bg-amber-500 hover:text-white p-2 rounded transition">
                                            <i class="fa-solid fa-note-sticky text-xs"></i>
                                        </button>
                                        <?php if ($order['is_deleted'] == 1): ?>
                                            <a href="?action=order_detail&id=<?= $order['id'] ?>" class="inline-flex items-center justify-center bg-slate-700 hover:bg-slate-600 text-white p-2 rounded transition">
                                                <i class="fa-solid fa-eye text-xs"></i>
                                            </a>
                                            <?php if ($role === 'admin' || $role === 'office_team'): ?>
                                                <button type="button" onclick="showConfirmModal('আপনি কি অর্ডারটি পুনরায় সচল তালিকায় ফিরিয়ে আনতে চান?', () => { window.location.href = '?action=restore_order&id=<?= $order['id'] ?>'; })" class="inline-flex items-center justify-center bg-emerald-600 hover:bg-emerald-500 text-white p-2 rounded transition">
                                                    <i class="fa-solid fa-rotate-left text-xs"></i>
                                                </button>
                                            <?php endif; ?>
                                            <?php if ($role === 'admin'): ?>
                                                <button type="button" onclick="showDoubleConfirm('অর্ডারটি স্থায়ীভাবে ডিলিট করলে তা আর কখনোই রিস্টোর করা যাবে না। আপনি কি নিশ্চিত?', 'শেষবারের মতো নিশ্চিত করুন — স্থায়ীভাবে ডিলিট করবেন?', () => { window.location.href = '?action=force_delete_order&id=<?= $order['id'] ?>'; })" class="inline-flex items-center justify-center bg-rose-600 hover:bg-rose-500 text-white p-2 rounded transition">
                                                    <i class="fa-solid fa-trash-can text-xs"></i>
                                                </button>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <a href="?action=order_detail&id=<?= $order['id'] ?>" class="inline-flex items-center justify-center bg-slate-700 hover:bg-slate-600 text-white p-2 rounded transition">
                                                <i class="fa-solid fa-pen-to-square text-xs"></i>
                                            </a>
                                            <?php if ($role === 'admin'): ?>
                                                <button type="button" onclick="showConfirmModal('অর্ডারটি রিসাইকেল বিনে স্থানান্তর করতে চান?', () => { window.location.href = '?action=delete_order&id=<?= $order['id'] ?>'; })" class="inline-flex items-center justify-center bg-rose-950/20 hover:bg-rose-500 text-rose-400 hover:text-white p-2 rounded transition border border-rose-500/30">
                                                    <i class="fa-solid fa-trash text-xs"></i>
                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mobile Layout -->
            <div class="block md:hidden p-4 space-y-4">
                <?php if (empty($orders)): ?>
                    <p class="text-center text-slate-400 text-sm py-8">কোনো অর্ডার খুঁজে পাওয়া যায়নি।</p>
                <?php else: ?>
                    <?php foreach ($orders as $order):
                        $rank = $order_rank[$order['id']] ?? 1;
                        $note_attr = htmlspecialchars($order['note'] ?? '', ENT_QUOTES);
                        ?>
                        <div class="bg-slate-900 border border-slate-700 rounded-2xl p-4 space-y-3 relative shadow-sm">
                            <div class="flex items-center justify-between pb-2 border-b border-slate-800">
                                <div class="flex items-center gap-2">
                                    <input type="checkbox" name="order_ids[]" value="<?= $order['id'] ?>" data-product="<?= htmlspecialchars(mb_substr($order['product_title'] ?? '', 0, 35), ENT_QUOTES) ?>" data-cod="<?= (float)$order['cod_amount'] ?>" class="order-chk rounded text-emerald-600">
                                    <span class="font-mono text-xs font-bold text-slate-400">#<?= $order['id'] ?></span>
                                    <?php if ($rank > 1): ?>
                                        <span class="bg-amber-500/15 text-amber-400 text-[10px] px-1.5 py-0.5 rounded font-bold border border-amber-500/30"><?= bnOrdinal($rank) ?> বার</span>
                                    <?php endif; ?>
                                </div>
                                <?php $st_style = get_status_style($order['status']); ?>
                                <select onchange="saveOrderStatus(<?= $order['id'] ?>, this.value, this)" class="text-white rounded-lg px-2 py-1 text-xs border outline-none font-bold select-auto transition-all cursor-pointer <?= $st_style ?>">
                                    <?php foreach ($status_map as $val => $lbl): ?>
                                        <?php if ($val === 'booked' && $role === 'agent') continue; ?>
                                        <option value="<?= $val ?>" <?= $order['status'] === $val ? 'selected' : '' ?> class="bg-slate-800 text-white font-semibold"><?= $lbl ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="space-y-1">
                                <h4 class="text-sm font-bold text-white"><?= htmlspecialchars($order['customer_name']) ?></h4>
                                <p class="text-xs text-slate-300 flex items-center gap-2">
                                    <span class="cursor-pointer underline decoration-dotted" onclick="showCustomerHistory('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')"><?= htmlspecialchars($order['phone']) ?></span>
                                    <button type="button" onclick="copyText('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" class="bg-slate-700 text-slate-300 w-6 h-6 rounded-lg flex items-center justify-center"><i class="fa-regular fa-copy text-[10px]"></i></button>
                                </p>
                                <p class="text-xs text-slate-300 leading-relaxed font-semibold flex items-center gap-1.5">
                                    <i class="fa-solid fa-map-marker-alt text-slate-500 text-[10px]"></i>
                                    <?= htmlspecialchars($order['address']) ?>
                                </p>
                            </div>

                            <div class="flex items-center gap-2 flex-wrap py-2 border-t border-slate-800">
                                <span class="text-[10px] text-slate-400 uppercase font-bold"><i class="fa-solid fa-user-shield text-rose-400"></i> ফ্রড চেক:</span>
                                <?php if ($order['fraud_score'] !== null): ?>
                                    <button type="button" onclick="showFraudDetails('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" class="px-2.5 py-1 rounded-lg text-[11px] font-bold hover:opacity-80 transition <?= $order['fraud_score'] >= 70 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400' ?>">
                                        ঝুঁকি: <?= $order['fraud_score'] ?>% — বিস্তারিত
                                    </button>
                                <?php else: ?>
                                    <button type="button" onclick="triggerFraudCheck('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', this)" class="px-2.5 py-1 rounded-lg text-[11px] font-bold bg-amber-500/15 text-amber-400 hover:bg-amber-500/25 transition"><i class="fa-solid fa-magnifying-glass"></i> রিস্ক চেক করুন</button>
                                <?php endif; ?>
                                <?php if (!empty($order['customer_ip'])): ?>
                                    <span class="text-[10px] font-mono text-slate-400 cursor-pointer hover:text-white" onclick="copyText('<?= htmlspecialchars($order['customer_ip'], ENT_QUOTES) ?>')" title="আইপি কপি করুন"><i class="fa-solid fa-network-wired text-[9px]"></i> <?= htmlspecialchars($order['customer_ip']) ?></span>
                                <?php endif; ?>
                            </div>

                            <div class="grid grid-cols-2 gap-2 text-xs py-2 border-t border-b border-slate-800 bg-slate-950/20 p-2 rounded-xl">
                                <div>
                                    <span class="text-[10px] text-slate-400 uppercase block">নির্বাচিত পণ্য</span>
                                    <span class="font-bold text-slate-200 block break-words"><?= htmlspecialchars($order['product_title'] ?? 'Dynamic Item') ?></span>
                                </div>
                                <div>
                                    <span class="text-[10px] text-slate-400 uppercase block">ভ্যারিয়েন্ট</span>
                                    <span class="font-bold text-amber-400 block break-words text-[11px]">
                                        <?= htmlspecialchars($order['color_selected'] ?: 'N/A') ?>
                                        <?= $order['size_selected'] ? ' | ' . htmlspecialchars($order['size_selected']) : '' ?>
                                        <?= $order['weight_selected'] ? ' | ' . htmlspecialchars($order['weight_selected']) : '' ?>
                                    </span>
                                </div>
                            </div>

                            <div class="flex items-center justify-between pt-1">
                                <div class="text-left">
                                    <span class="text-[10px] text-slate-400 uppercase block">COD মূল্য</span>
                                    <span class="font-extrabold text-emerald-400 text-sm"><?= number_format($order['cod_amount'], 2) ?> ৳</span>
                                    <?php if ((!empty($order['delivery_charge']) && $order['delivery_charge'] > 0) || (!empty($order['discount_amount']) && $order['discount_amount'] > 0)): ?>
                                        <span class="block text-[10px] text-slate-400 mt-0.5">
                                            <?php if (!empty($order['delivery_charge']) && $order['delivery_charge'] > 0): ?>🚚 +৳<?= number_format($order['delivery_charge']) ?> (<?= htmlspecialchars(delivery_zone_bn($order['delivery_zone'] ?? '')) ?>)<?php endif; ?>
                                            <?php if (!empty($order['discount_amount']) && $order['discount_amount'] > 0): ?> 🎟️ −৳<?= number_format($order['discount_amount']) ?><?= !empty($order['promo_code']) ? ' (' . htmlspecialchars($order['promo_code']) . ')' : '' ?><?php endif; ?>
                                        </span>
                                    <?php endif; ?>
                                </div>
                                <div class="flex items-center gap-2">
                                    <button type="button" onclick="dialCustomer('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>')" class="bg-cyan-600 hover:bg-cyan-500 text-white w-9 h-9 flex items-center justify-center rounded-xl transition" title="ডায়ালার কল">
                                        <i class="fa-solid fa-headset text-sm"></i>
                                    </button>
                                    <a href="tel:<?= $order['phone'] ?>" class="bg-indigo-600 hover:bg-indigo-500 text-white w-9 h-9 flex items-center justify-center rounded-xl transition">
                                        <i class="fa-solid fa-phone text-sm"></i>
                                    </a>
                                    <button type="button" onclick="openWaTemplates('<?= wa_number($order['phone']) ?>', '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars(mb_substr($order['product_title'] ?? '', 0, 40), ENT_QUOTES) ?>', <?= (float)$order['cod_amount'] ?>, '<?= htmlspecialchars($order['tracking_code'] ?? '', ENT_QUOTES) ?>')" class="bg-emerald-600 hover:bg-emerald-500 text-white w-9 h-9 flex items-center justify-center rounded-xl transition" title="হোয়াটসঅ্যাপ মেসেজ">
                                        <i class="fa-brands fa-whatsapp text-base"></i>
                                    </button>
                                    <?php if ($role !== 'agent'): ?>
                                    <button type="button" onclick="addToZoneList(<?= (int)$order['id'] ?>, this)" class="<?= !empty($order['zone_change_flag']) ? 'bg-orange-600 text-white' : 'bg-slate-700 text-orange-400 hover:bg-orange-600 hover:text-white' ?> w-9 h-9 flex items-center justify-center rounded-xl transition" title="জোন চেঞ্জ তালিকায় যোগ করুন">
                                        <i class="fa-solid fa-map-location-dot text-xs"></i>
                                    </button>
                                    <?php endif; ?>
                                    <button type="button" data-oid="<?= $order['id'] ?>" data-note="<?= $note_attr ?>" onclick="openNoteModal(<?= $order['id'] ?>, this)" class="note-icon-btn bg-amber-600/80 hover:bg-amber-500 text-white w-9 h-9 flex items-center justify-center rounded-xl transition" title="নোট">
                                        <i class="fa-solid fa-note-sticky text-xs"></i>
                                    </button>
                                    <a href="?action=order_detail&id=<?= $order['id'] ?>" class="bg-slate-700 hover:bg-slate-600 text-white w-9 h-9 flex items-center justify-center rounded-xl transition" title="সম্পাদনা">
                                        <i class="fa-solid fa-pen-to-square text-xs"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- Bulk Control Options Footer -->
            <div class="p-4 bg-slate-900 border-t border-slate-700 flex flex-wrap gap-4 items-center justify-between">
                <div class="flex items-center gap-3">
                    <?php if ($role === 'admin'): ?>
                        <select name="bulk_op" class="bg-slate-800 text-white text-sm border border-slate-700 rounded px-2 py-1.5 outline-none font-semibold">
                            <option value="">বাল্ক অপশন নির্বাচন করুন</option>
                            <?php if ($status_filter === 'deleted'): ?>
                                <option value="restore">রিস্টোর করুন (পুনরুদ্ধার)</option>
                                <option value="force_delete">স্থায়ীভাবে ডিলিট (Force Delete)</option>
                            <?php else: ?>
                                <option value="book_steadfast">স্টিডফাস্ট বুকিং (নির্বাচিত)</option>
                                <option value="delete">রিসাইকেল বিনে পাঠান (ডিলিট)</option>
                            <?php endif; ?>
                        </select>
                        <button type="submit" id="bulkApplyBtn" class="bg-emerald-600 hover:bg-emerald-500 text-white text-xs px-3 py-2 rounded font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed">প্রয়োগ করুন</button>
                    <?php else: ?>
                        <span class="text-xs text-slate-400 italic">বাল্ক অ্যাকশন শুধুমাত্র অ্যাডমিনদের জন্য উপলব্ধ</span>
                    <?php endif; ?>
                </div>

                <div class="flex items-center gap-2">
                    <button type="button" onclick="printSelected('80mm')" class="bg-indigo-600 hover:bg-indigo-500 text-white text-xs px-3 py-2 rounded font-semibold transition">80mm প্রিন্ট</button>
                    <button type="button" onclick="printSelected('40mm')" class="bg-indigo-600 hover:bg-indigo-500 text-white text-xs px-3 py-2 rounded font-semibold transition">40mm প্রিন্ট</button>
                    <span class="text-slate-500 text-[10px] mx-1">| QR লেবেল:</span>
                    <button type="button" onclick="printSelected('label_50x75')" class="bg-emerald-600 hover:bg-emerald-500 text-white text-xs px-3 py-2 rounded font-semibold transition" title="৫০mm × ৭৫mm — ফোন, পণ্য, কালার/সাইজ, ID, COD + QR">৫০×৭৫</button>
                    <button type="button" onclick="printSelected('label_80x30')" class="bg-emerald-600 hover:bg-emerald-500 text-white text-xs px-3 py-2 rounded font-semibold transition" title="৮০mm × ৩০mm — ফোন, পণ্য, কালার/সাইজ, ID, COD + QR">৮০×৩০</button>
                    <button type="button" onclick="printSelected('label_40x30')" class="bg-emerald-600 hover:bg-emerald-500 text-white text-xs px-3 py-2 rounded font-semibold transition" title="৪০mm × ৩০mm — ফোন, পণ্য, কালার/সাইজ, ID, COD + QR">৪০×৩০</button>
                </div>
            </div>

            <?php render_pagination_bar($page, $per_page, $total_filtered, $total_pages); ?>
        </form>
    </div>
    <?php
}

function render_order_detail_view($order, $all_products_for_order = []) {
    global $status_map;
    $colors = json_decode(get_setting('product_colors'), true) ?: [];
    $size_teen = json_decode(get_setting('size_teen_options'), true) ?: [];
    $size_kids = json_decode(get_setting('size_kids_options'), true) ?: [];
    $weights = json_decode(get_setting('weight_options'), true) ?: [];
    $role = get_user_role();
    ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border-2 border-transparent shadow-xl relative" style="background: linear-gradient(#1e293b, #1e293b) padding-box, linear-gradient(135deg, #10b981, #06b6d4, #8b5cf6, #ec4899) border-box;">
            <a href="?action=dashboard" title="বন্ধ করে অর্ডার তালিকায় ফিরুন" class="absolute top-4 right-4 text-slate-400 hover:text-white text-xl font-bold border border-slate-600 hover:border-rose-500 hover:bg-rose-500/10 rounded-full w-9 h-9 flex items-center justify-center transition">&times;</a>
            <div class="flex flex-wrap items-center gap-3 mb-2">
                <h3 class="text-lg font-extrabold flex items-center gap-2 bg-gradient-to-r from-emerald-400 via-cyan-400 to-fuchsia-400 bg-clip-text text-transparent">
                    <i class="fa-solid fa-pen-to-square text-emerald-400"></i> <span>অর্ডার তথ্য পরিবর্তন করুন</span>
                </h3>
                <a href="?action=dashboard&status_filter=pending" class="text-[11px] font-bold bg-amber-500/15 text-amber-400 border border-amber-600/40 hover:bg-amber-500/30 px-3 py-1.5 rounded-full transition" title="সেভ করার পর এক ক্লিকে সব পেন্ডিং অর্ডার দেখুন">
                    <i class="fa-solid fa-phone-volume"></i> কল বাকি (পেন্ডিং) দেখুন
                </a>
            </div>
            <p class="text-xs text-slate-400 mb-6 flex flex-wrap items-center gap-x-4 gap-y-1">
                <span title="অর্ডার করার তারিখ ও সময়"><i class="fa-regular fa-calendar-plus text-emerald-400"></i> অর্ডারের তারিখ: <b class="text-slate-200 font-mono"><?= date('d M Y, h:i A', strtotime($order['created_at'])) ?></b></span>
                <?php if (!empty($order['updated_at'])): ?>
                <span title="সর্বশেষ আপডেট"><i class="fa-regular fa-clock text-amber-400"></i> শেষ আপডেট: <b class="text-slate-200 font-mono"><?= date('d M Y, h:i A', strtotime($order['updated_at'])) ?></b><?= !empty($order['updated_by']) ? ' (' . htmlspecialchars($order['updated_by']) . ')' : '' ?></span>
                <?php endif; ?>
            </p>

            <form action="" method="POST" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">গ্রাহকের নাম <span class="text-[10px] text-emerald-400">(পরিবর্তনযোগ্য)</span></label>
                        <input type="text" name="customer_name" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none" value="<?= htmlspecialchars($order['customer_name']) ?>">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">মোবাইল নম্বর <span class="text-[10px] text-emerald-400">(পরিবর্তনযোগ্য)</span></label>
                        <div class="flex gap-2">
                            <input type="text" name="phone" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none" value="<?= htmlspecialchars($order['phone']) ?>">
                            <!-- Feature 11: copy phone icon -->
                            <button type="button" onclick="copyText('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" title="নাম্বার কপি করুন" class="bg-slate-700 hover:bg-slate-600 text-slate-300 hover:text-white px-3 rounded-lg border border-slate-600 transition">
                                <i class="fa-regular fa-copy"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <?php if (!empty($order['custom_field_value'])): ?>
                <div class="bg-fuchsia-950/30 border border-fuchsia-800/40 rounded-xl px-4 py-3">
                    <span class="block text-[11px] text-fuchsia-400 font-bold mb-0.5">📝 <?= htmlspecialchars($order['custom_field_label'] ?? 'কাস্টম ফিল্ড') ?></span>
                    <span class="text-sm text-white"><?= nl2br(htmlspecialchars($order['custom_field_value'])) ?></span>
                </div>
                <?php endif; ?>

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-semibold">সম্পূর্ণ ঠিকানা</label>
                    <textarea name="address" rows="3" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none"><?= htmlspecialchars($order['address']) ?></textarea>
                </div>

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-semibold"><i class="fa-solid fa-box-open text-emerald-400"></i> প্রোডাক্ট পরিবর্তন করুন</label>
                    <select name="product_id" onchange="odProductChanged(this)" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                        <?php if (empty($all_products_for_order)): ?>
                            <option value="<?= (int)$order['product_id'] ?>"><?= htmlspecialchars($order['product_title'] ?? 'প্রোডাক্ট নেই') ?></option>
                        <?php else: foreach ($all_products_for_order as $pfo):
                            $eff_price = ($pfo['sale_price'] !== null && $pfo['sale_price'] > 0) ? $pfo['sale_price'] : $pfo['price'];
                        ?>
                            <option value="<?= (int)$pfo['id'] ?>" data-price="<?= htmlspecialchars($eff_price) ?>" <?= (int)$order['product_id'] === (int)$pfo['id'] ? 'selected' : '' ?>>
                                #<?= (int)$pfo['id'] ?> — <?= htmlspecialchars($pfo['title']) ?> (৳<?= number_format((float)$eff_price) ?>)
                            </option>
                        <?php endforeach; endif; ?>
                    </select>
                    <p class="text-[10px] text-slate-500 mt-1">এটি প্রধান পণ্য (কুরিয়ার/রিপোর্টে ব্যবহৃত)। একাধিক পণ্য থাকলে নিচে যোগ করুন।</p>
                </div>

                <!-- মাল্টি-প্রোডাক্ট: অতিরিক্ত পণ্য + কোয়ান্টিটি -->
                <div class="bg-slate-900/40 border border-slate-700 rounded-xl p-4">
                    <div class="flex items-center justify-between mb-3">
                        <label class="text-slate-300 text-sm font-semibold flex items-center gap-2"><i class="fa-solid fa-layer-group text-cyan-400"></i> একাধিক পণ্য (মাল্টি-প্রোডাক্ট)</label>
                        <button type="button" onclick="odAddItemRow()" class="bg-cyan-600 hover:bg-cyan-500 text-white text-xs font-bold px-3 py-1.5 rounded-lg"><i class="fa-solid fa-plus"></i> পণ্য যোগ</button>
                    </div>
                    <div id="odItemsList" class="space-y-2"></div>
                    <input type="hidden" name="order_items_json" id="odItemsJson" value="">
                    <div class="mt-3 pt-3 border-t border-slate-700 flex items-center justify-between">
                        <span class="text-xs text-slate-400">পণ্যের মোট (auto): <b id="odItemsSubtotal" class="text-emerald-400 font-mono">৳0</b></span>
                        <label class="flex items-center gap-2 text-[11px] text-slate-400"><input type="checkbox" id="odAutoCod" checked class="rounded"> মোট COD-তে অটো বসাও</label>
                    </div>
                    <p class="text-[10px] text-slate-500 mt-2">পণ্য+কোয়ান্টিটি অনুযায়ী দাম যোগ হয়ে নিচের COD আপডেট হবে। চেকবক্স তুলে দিলে COD নিজে হাতে বসাতে পারবেন।</p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">সিলেক্টেড কালার</label>
                        <select name="color_selected" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                            <option value="">কালার চয়েস নেই</option>
                            <?php foreach ($colors as $c): ?>
                                <option value="<?= htmlspecialchars($c['en']) ?>" <?= $order['color_selected'] === $c['en'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($c['en']) ?> (<?= htmlspecialchars($c['bn']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">সিলেক্টেড সাইজ</label>
                        <select name="size_selected" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                            <option value="">সাইজ নেই</option>
                            <optgroup label="Teen/Adult">
                                <?php foreach ($size_teen as $s): ?>
                                    <option value="<?= htmlspecialchars($s) ?>" <?= $order['size_selected'] === $s ? 'selected' : '' ?>><?= htmlspecialchars($s) ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                            <optgroup label="Baby/Kids">
                                <?php foreach ($size_kids as $s): ?>
                                    <option value="<?= htmlspecialchars($s) ?>" <?= $order['size_selected'] === $s ? 'selected' : '' ?>><?= htmlspecialchars($s) ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">সিলেক্টেড ওজন</label>
                        <select name="weight_selected" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                            <option value="">ওজন নেই</option>
                            <?php
                            $current_weight = $order['weight_selected'] ?: '';
                            $found_weight = false;
                            foreach ($weights as $w):
                                if ($current_weight === $w) $found_weight = true; ?>
                                <option value="<?= htmlspecialchars($w) ?>" <?= $current_weight === $w ? 'selected' : '' ?>><?= htmlspecialchars($w) ?></option>
                            <?php endforeach;
                            if ($current_weight !== '' && !$found_weight): ?>
                                <option value="<?= htmlspecialchars($current_weight) ?>" selected><?= htmlspecialchars($current_weight) ?> (কাস্টম)</option>
                            <?php endif; ?>
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">ডেলিভারি জোন <?= empty($order['delivery_zone']) ? '<span class="text-[10px] bg-amber-500/20 text-amber-400 px-2 py-0.5 rounded-full">⚠️ Zone not clear</span>' : '' ?></label>
                        <?php
                        $zc_dhaka = (float)(get_setting('courier_charge_dhaka') ?: 60);
                        $zc_sub = (float)(get_setting('courier_charge_sub_dhaka') ?: 100);
                        $zc_out = (float)(get_setting('courier_charge_outside') ?: 130);
                        ?>
                        <select name="delivery_zone" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                            <option value="">— জোন সিলেক্ট হয়নি —</option>
                            <option value="dhaka" <?= ($order['delivery_zone'] ?? '') === 'dhaka' ? 'selected' : '' ?>>ঢাকার মধ্যে (৳<?= $zc_dhaka ?>)</option>
                            <option value="sub_dhaka" <?= ($order['delivery_zone'] ?? '') === 'sub_dhaka' ? 'selected' : '' ?>>সাব ঢাকা (৳<?= $zc_sub ?>)</option>
                            <option value="outside" <?= ($order['delivery_zone'] ?? '') === 'outside' ? 'selected' : '' ?>>সারা বাংলাদেশ (৳<?= $zc_out ?>)</option>
                        </select>
                        <p class="text-[10px] text-slate-500 mt-1">ঠিকানা দেখে জোন সিলেক্ট করুন — জোন বদলালে ডেলিভারি চার্জের পার্থক্য COD-তে অটো সমন্বয় হবে।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">COD পরিমাণ (৳)</label>
                        <input type="number" step="0.01" name="cod_amount" id="odCodInput" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none" value="<?= htmlspecialchars($order['cod_amount']) ?>">
                        <script>
                            function odProductChanged(sel) {
                                const opt = sel.options[sel.selectedIndex];
                                const price = parseFloat(opt.getAttribute('data-price'));
                                if (!isNaN(price) && confirm('নতুন প্রোডাক্টের দাম ৳' + price + ' — COD এমাউন্ট কি এই দামে আপডেট করবেন?')) {
                                    document.getElementById('odCodInput').value = price;
                                }
                            }

                            // ==== মাল্টি-প্রোডাক্ট ম্যানেজমেন্ট ====
                            var OD_PRODUCTS = <?= json_encode(array_map(function($p){ $ep = ($p['sale_price'] !== null && $p['sale_price'] > 0) ? $p['sale_price'] : $p['price']; return ['id'=>(int)$p['id'],'title'=>$p['title'],'price'=>(float)$ep]; }, $all_products_for_order ?? []), JSON_UNESCAPED_UNICODE) ?>;
                            var OD_EXISTING = <?= !empty($order['order_items']) ? $order['order_items'] : '[]' ?>;

                            function odProdOptions(selId) {
                                return OD_PRODUCTS.map(function(p){ return '<option value="'+p.id+'" data-price="'+p.price+'" '+(p.id==selId?'selected':'')+'>'+p.title+' (৳'+p.price+')</option>'; }).join('');
                            }
                            function odAddItemRow(pid, qty) {
                                var list = document.getElementById('odItemsList');
                                var row = document.createElement('div');
                                row.className = 'od-item-row flex items-center gap-2';
                                var firstId = pid || (OD_PRODUCTS[0] ? OD_PRODUCTS[0].id : 0);
                                row.innerHTML = '<select class="od-item-prod flex-1 bg-slate-700 text-white rounded-lg px-2 py-1.5 border border-slate-600 outline-none text-xs" onchange="odRecalc()">'+odProdOptions(firstId)+'</select>'
                                    + '<span class="text-slate-500 text-xs">×</span>'
                                    + '<input type="number" min="1" value="'+(qty||1)+'" class="od-item-qty w-16 bg-slate-700 text-white rounded-lg px-2 py-1.5 border border-slate-600 outline-none text-xs text-center" oninput="odRecalc()">'
                                    + '<button type="button" onclick="this.closest(\'.od-item-row\').remove(); odRecalc();" class="text-rose-400 hover:text-rose-300 px-1"><i class="fa-solid fa-xmark"></i></button>';
                                list.appendChild(row);
                                odRecalc();
                            }
                            function odRecalc() {
                                var rows = document.querySelectorAll('.od-item-row');
                                var items = [], subtotal = 0;
                                rows.forEach(function(r){
                                    var sel = r.querySelector('.od-item-prod');
                                    var qty = parseInt(r.querySelector('.od-item-qty').value) || 1;
                                    var opt = sel.options[sel.selectedIndex];
                                    var price = parseFloat(opt.getAttribute('data-price')) || 0;
                                    var pid = parseInt(sel.value);
                                    var title = opt.textContent.replace(/ \(৳.*$/, '');
                                    items.push({product_id: pid, title: title, qty: qty, price: price});
                                    subtotal += price * qty;
                                });
                                document.getElementById('odItemsJson').value = JSON.stringify(items);
                                document.getElementById('odItemsSubtotal').innerText = '৳' + subtotal.toLocaleString('en-US');
                                if (document.getElementById('odAutoCod').checked && items.length > 0) {
                                    document.getElementById('odCodInput').value = subtotal;
                                }
                            }
                            // বিদ্যমান আইটেম লোড
                            (function(){
                                if (Array.isArray(OD_EXISTING) && OD_EXISTING.length > 0) {
                                    OD_EXISTING.forEach(function(it){ odAddItemRow(it.product_id, it.qty); });
                                }
                            })();
                        </script>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1 font-semibold">স্ট্যাটাস</label>
                        <select name="status" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none">
                            <?php foreach ($status_map as $val => $lbl): ?>
                                <?php if ($val === 'booked' && $role === 'agent' && $order['status'] !== 'booked') continue; ?>
                                <option value="<?= $val ?>" <?= $order['status'] === $val ? 'selected' : '' ?>><?= $lbl ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-semibold flex items-center gap-2">
                        <i class="fa-solid fa-note-sticky text-amber-400"></i> ডেলিভারি নোট / এজেন্ট কল আপডেট
                        <span class="text-[10px] text-slate-500 font-normal">(সবাই দেখতে ও আপডেট করতে পারবে)</span>
                    </label>
                    <textarea name="note" rows="3" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 focus:border-emerald-500 outline-none" placeholder="কাস্টমারের সাথে কী কথা হয়েছে বা কোনো নির্দেশনা দিলে তা এখানে লিখুন..."><?= htmlspecialchars($order['note']) ?></textarea>
                    <?php if (!empty($order['updated_by'])): ?>
                        <span class="text-[10px] text-slate-500 block mt-1">সর্বশেষ আপডেট: <?= htmlspecialchars($order['updated_by']) ?> (<?= htmlspecialchars($order['updated_at'] ?? '') ?>)</span>
                    <?php endif; ?>
                </div>

                <div class="flex gap-4 pt-4 border-t border-slate-700">
                    <button type="submit" class="bg-emerald-600 hover:bg-emerald-500 text-white px-5 py-2.5 rounded-lg font-bold transition">সেভ পরিবর্তন</button>
                    <a href="?action=dashboard" class="bg-slate-700 hover:bg-slate-600 text-white px-5 py-2.5 rounded-lg font-bold transition">পিছনে যান</a>
                </div>
            </form>
        </div>

        <div class="space-y-6">
            <div class="bg-slate-800/50 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h4 class="text-white font-bold mb-4 flex items-center gap-2">
                    <i class="fa-solid fa-phone-volume text-rose-400"></i> ১:১ কাস্টমার কমিউনিকেশন
                </h4>

                <div class="space-y-3">
                    <!-- Feature 8: SIP dialer click-to-call -->
                    <button type="button" onclick="dialCustomer('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>')" class="flex items-center justify-center gap-3 w-full bg-cyan-600 hover:bg-cyan-500 text-white py-3 rounded-xl font-bold transition shadow-lg">
                        <i class="fa-solid fa-headset text-sm"></i> ডায়ালার দিয়ে কল দিন
                    </button>
                    <a href="tel:<?= $order['phone'] ?>" class="flex items-center justify-center gap-3 w-full bg-indigo-600 hover:bg-indigo-500 text-white py-3 rounded-xl font-bold transition shadow-lg">
                        <i class="fa-solid fa-phone text-sm"></i> সরাসরি কল দিন
                    </a>
                    <button type="button" onclick="openWaTemplates('<?= wa_number($order['phone']) ?>', '<?= htmlspecialchars($order['customer_name'], ENT_QUOTES) ?>', <?= (int)$order['id'] ?>, '<?= htmlspecialchars(mb_substr($order['product_title'] ?? '', 0, 40), ENT_QUOTES) ?>', <?= (float)$order['cod_amount'] ?>, '<?= htmlspecialchars($order['tracking_code'] ?? '', ENT_QUOTES) ?>')" class="flex items-center justify-center gap-3 w-full bg-emerald-600 hover:bg-emerald-500 text-white py-3 rounded-xl font-bold transition shadow-lg">
                        <i class="fa-brands fa-whatsapp text-lg"></i> হোয়াটসঅ্যাপ মেসেজ পাঠান
                    </a>
                    <a href="?action=invoice&id=<?= $order['id'] ?>" target="_blank" class="flex items-center justify-center gap-3 w-full bg-indigo-600 hover:bg-indigo-500 text-white py-3 rounded-xl font-bold transition mb-3">
                        <i class="fa-solid fa-file-invoice"></i> ইনভয়েস প্রিন্ট করুন (A4)
                    </a>
                    <button type="button" onclick="showCustomerHistory('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')" class="flex items-center justify-center gap-3 w-full bg-slate-700 hover:bg-slate-600 text-white py-3 rounded-xl font-bold transition">
                        <i class="fa-solid fa-clock-rotate-left"></i> সকল অর্ডার হিস্টোরি দেখুন
                    </button>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h4 class="text-white font-bold mb-4 flex items-center gap-2">
                    <i class="fa-solid fa-shield-halved text-emerald-400"></i> FraudShield ইন্টেলিজেন্স রিপোর্ট
                </h4>
                <?php if ($order['fraud_score'] !== null): ?>
                    <div class="text-center p-4 bg-slate-900 rounded-xl mb-4 border border-slate-700 cursor-pointer hover:opacity-90 transition" onclick="showFraudDetails('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>')">
                        <div class="text-xs text-slate-400 uppercase">ফ্রড রিস্ক লেভেল</div>
                        <div class="text-4xl font-extrabold mt-1 <?= $order['fraud_score'] >= 70 ? 'text-rose-400' : 'text-emerald-400' ?>">
                            <?= $order['fraud_score'] ?>%
                        </div>
                        <span class="text-[9px] text-indigo-400 block mt-1 hover:underline">বিস্তারিত বিশ্লেষণ দেখুন</span>
                    </div>
                <?php else: ?>
                    <div class="text-center mb-3">
                        <button type="button" onclick="triggerFraudCheck('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', this)" class="bg-amber-600/80 hover:bg-amber-500 text-white text-xs font-bold px-4 py-2 rounded-lg transition">ফ্রড চেক করুন</button>
                    </div>
                <?php endif; ?>

                <!-- Feature 10: Auto captured customer IP below fraud check, click & hold to copy -->
                <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-3 mt-2">
                    <span class="text-[10px] text-slate-400 uppercase tracking-wider block mb-1"><i class="fa-solid fa-network-wired"></i> কাস্টমারের আইপি নাম্বার (অটো ক্যাপচার)</span>
                    <?php if (!empty($order['customer_ip'])): ?>
                        <div class="flex items-center justify-between gap-2">
                            <span id="orderCustomerIp" class="font-mono text-sm text-white select-all cursor-pointer" title="ক্লিক করে ধরে রাখলে কপি হবে"><?= htmlspecialchars($order['customer_ip']) ?></span>
                            <button type="button" onclick="copyText('<?= htmlspecialchars($order['customer_ip'], ENT_QUOTES) ?>')" class="bg-slate-700 hover:bg-slate-600 text-slate-300 hover:text-white px-2.5 py-1.5 rounded-lg text-xs transition" title="আইপি কপি করুন">
                                <i class="fa-regular fa-copy"></i>
                            </button>
                        </div>
                        <script>
                            bindLongPressCopy(document.getElementById('orderCustomerIp'), '<?= htmlspecialchars($order['customer_ip'], ENT_QUOTES) ?>');
                        </script>
                    <?php else: ?>
                        <span class="text-xs text-slate-500">এই অর্ডারে আইপি সংরক্ষিত নেই (পুরাতন অর্ডার)।</span>
                    <?php endif; ?>
                </div>

                <?php if (in_array($role, ['admin', 'office_team'])): ?>
                    <button type="button" onclick="showDoubleConfirm('এই কাস্টমারের নাম্বার ও আইপি ব্লক তালিকায় যুক্ত করতে চান?', 'ব্লক করলে এই কাস্টমার আর কোনো অর্ডার করতে পারবে না। নিশ্চিত?', () => { quickBlockCustomer('<?= htmlspecialchars($order['phone'], ENT_QUOTES) ?>', '<?= htmlspecialchars($order['customer_ip'] ?? '', ENT_QUOTES) ?>'); })" class="mt-3 w-full bg-rose-600/80 hover:bg-rose-500 text-white text-xs font-bold py-2.5 rounded-xl transition flex items-center justify-center gap-2">
                        <i class="fa-solid fa-user-slash"></i> এই কাস্টমারকে ব্লক করুন
                    </button>
                    <script>
                        function quickBlockCustomer(phone, ip) {
                            fetch('?action=quick_block&phone=' + encodeURIComponent(phone) + '&ip=' + encodeURIComponent(ip))
                                .then(r => r.json())
                                .then(d => showToast(d.message, d.status === 'success' ? 'success' : 'error'))
                                .catch(() => showToast('নেটওয়ার্ক ত্রুটি!', 'error'));
                        }
                    </script>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php
}

function render_inventory_panel($products) {
    ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 font-semibold">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2">
                <i class="fa-solid fa-rotate-left text-amber-500"></i> রিটার্ন স্টক রিস্টক করুন
            </h3>
            <p class="text-xs text-slate-400 mb-6">কাস্টমারের ফেরত আসা প্রোডাক্ট নির্বাচন করুন এবং তা পুনরায় প্রধান স্টকে যোগ করুন।</p>
            <form action="?action=restock_product" method="POST" class="space-y-4">
                <div>
                    <label class="block text-slate-300 text-xs mb-1">পণ্য নির্বাচন করুন</label>
                    <select name="product_id" id="restockProductSelect" required onchange="showRestockCurrentStock()" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="">পণ্য সিলেক্ট করুন</option>
                        <?php foreach ($products as $p): ?>
                            <option value="<?= $p['id'] ?>" data-stock="<?= $p['stock'] ?>"><?= htmlspecialchars($p['title']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <span id="restockPrevStockBadge" class="hidden inline-block bg-indigo-500/10 text-indigo-400 text-[11px] px-2 py-0.5 rounded mt-2 font-bold font-mono"></span>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">স্টক বৃদ্ধির পরিমাণ (পিস)</label>
                    <input type="number" name="qty" required min="1" placeholder="যেমন: ৫" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                </div>
                <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-2.5 rounded-lg transition duration-200 text-sm flex items-center justify-center gap-2">
                    <i class="fa-solid fa-circle-plus"></i> স্টক আপডেট করুন
                </button>
            </form>
        </div>

        <script>
            function showRestockCurrentStock() {
                const select = document.getElementById('restockProductSelect');
                const badge = document.getElementById('restockPrevStockBadge');
                if (select.value === "") {
                    badge.classList.add('hidden');
                    return;
                }
                const selectedOption = select.options[select.selectedIndex];
                const currentStock = selectedOption.getAttribute('data-stock') || 0;
                badge.innerText = "বর্তমান স্টক: " + currentStock + " পিস";
                badge.classList.remove('hidden');
            }
        </script>

        <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-6">ইনভেন্টরি প্রোডাক্ট লিস্ট</h3>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead>
                        <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs uppercase tracking-wider">
                            <th class="p-3">ইমেজ</th>
                            <th class="p-3">পণ্য টাইটেল</th>
                            <th class="p-3 text-center">ইনভেন্টরি স্টক</th>
                            <th class="p-3">পণ্য মূল্য</th>
                            <th class="p-3 text-right">পদক্ষেপ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700">
                        <?php foreach ($products as $p): ?>
                            <tr class="text-sm">
                                <td class="p-3">
                                    <img src="<?= htmlspecialchars($p['image_url'] ?: 'https://images.unsplash.com/photo-1541643600914-78b084683601?auto=format&fit=crop&w=100&q=80') ?>" class="w-10 h-10 object-cover rounded-lg">
                                </td>
                                <td class="p-3">
                                    <span class="font-bold text-white block"><?= htmlspecialchars($p['title']) ?></span>
                                    <span class="text-[10px] text-slate-400 font-mono">/<?= htmlspecialchars($p['slug']) ?></span>
                                </td>
                                <td class="p-3 text-center">
                                    <span id="stkbadge-<?= (int)$p['id'] ?>" class="px-2.5 py-1 rounded-full text-xs font-bold font-mono <?= $p['stock'] <= 5 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400' ?>">
                                        <?= number_format($p['stock']) ?> পিস
                                    </span>
                                    <button type="button" onclick="editStock(<?= (int)$p['id'] ?>, <?= (int)$p['stock'] ?>, '<?= htmlspecialchars($p['title'], ENT_QUOTES) ?>')" class="ml-1 text-slate-500 hover:text-amber-400 text-[11px]" title="সঠিক স্টক সেট করুন (অডিট)"><i class="fa-solid fa-pen-to-square"></i></button>
                                </td>
                                <td class="p-3 font-mono font-bold text-emerald-400">
                                    <?= number_format($p['sale_price'] ?: $p['price'], 2) ?> ৳
                                </td>
                                <td class="p-3 text-right">
                                    <a href="?action=products" class="text-indigo-400 hover:text-indigo-300 text-xs font-bold">এডিট করুন</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script>
        function editStock(pid, cur, title) {
            const val = prompt('স্টক অডিট — "' + title + '"\n\nবর্তমান স্টক: ' + cur + '\nসঠিক স্টক সংখ্যা লিখুন:', cur);
            if (val === null) return;
            const n = parseInt(val);
            if (isNaN(n) || n < 0) { showToast('সঠিক সংখ্যা দিন', 'error'); return; }
            const fd = new FormData();
            fd.append('product_id', pid);
            fd.append('new_stock', n);
            fetch('?action=set_stock', { method: 'POST', body: fd })
                .then(r => r.json())
                .then(d => {
                    showToast(d.message, d.status === 'success' ? 'success' : 'error');
                    if (d.status === 'success') {
                        const b = document.getElementById('stkbadge-' + pid);
                        if (b) { b.innerText = d.stock + ' পিস'; b.className = 'px-2.5 py-1 rounded-full text-xs font-bold font-mono ' + (d.stock <= 5 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400'); }
                    }
                }).catch(() => showToast('আপডেট ব্যর্থ', 'error'));
        }
    </script>
    <?php
}

function render_user_management($users, $error) {
    ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 font-semibold">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-6" id="userFormTitle">নতুন এজেন্ট/ইউজার যোগ করুন</h3>
            <?php if ($error): ?>
                <div class="bg-rose-500/10 border border-rose-500 text-rose-400 p-3 rounded mb-4 text-xs"><?= $error ?></div>
            <?php endif; ?>

            <form action="" method="POST" id="userForm" class="space-y-4">
                <input type="hidden" name="add_user" id="userFormOp" value="1">
                <input type="hidden" name="user_id" id="userFormId" value="">
                <div>
                    <label class="block text-slate-300 text-xs mb-1">ইউজারনেম</label>
                    <input type="text" name="username" id="userFormUsername" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">পাসওয়ার্ড</label>
                    <div class="relative">
                        <input type="password" name="password" id="userFormPassword" placeholder="নতুন পাসওয়ার্ড লিখুন..." class="w-full bg-slate-700 text-white rounded-lg pl-3 pr-10 py-2 border border-slate-600 outline-none text-sm">
                        <button type="button" onclick="togglePasswordVisibility()" class="absolute right-3 top-2.5 text-slate-400 hover:text-white">
                            <i class="fa-solid fa-eye" id="passwordEyeIcon"></i>
                        </button>
                    </div>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">রোল (অ্যাক্সেস লেভেল)</label>
                    <select name="role" id="userFormRole" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="agent">কলিং এজেন্ট (সীমিত অ্যাক্সেস)</option>
                        <option value="office_team">অফিস টিম মেম্বার (কুরিয়ার অ্যাক্সেস)</option>
                        <option value="admin">সিস্টেম অ্যাডমিনিস্ট্রেটর</option>
                    </select>
                </div>
                <div class="flex gap-2">
                    <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white py-2.5 rounded-lg font-bold transition text-sm">ইউজার সেভ করুন</button>
                    <button type="button" onclick="resetUserForm()" class="bg-slate-700 hover:bg-slate-600 text-white px-4 py-2.5 rounded-lg text-xs">রিসেট</button>
                </div>
            </form>
        </div>

        <script>
            function togglePasswordVisibility() {
                const input = document.getElementById('userFormPassword');
                const icon = document.getElementById('passwordEyeIcon');
                if (input.type === "password") {
                    input.type = "text";
                    icon.classList.remove('fa-eye');
                    icon.classList.add('fa-eye-slash');
                } else {
                    input.type = "password";
                    icon.classList.remove('fa-eye-slash');
                    icon.classList.add('fa-eye');
                }
            }
            function editUser(id, username, role) {
                document.getElementById('userFormTitle').innerText = "ইউজার এডিট ও পাসওয়ার্ড পরিবর্তন";
                document.getElementById('userFormOp').name = "edit_user";
                document.getElementById('userFormId').value = id;
                document.getElementById('userFormUsername').value = username;
                document.getElementById('userFormRole').value = role;
                document.getElementById('userFormPassword').placeholder = "পাসওয়ার্ড অপরিবর্তিত রাখতে খালি রাখুন";
                document.getElementById('userFormPassword').required = false;
            }
            function resetUserForm() {
                document.getElementById('userFormTitle').innerText = "নতুন ইউজার যোগ করুন";
                document.getElementById('userFormOp').name = "add_user";
                document.getElementById('userFormId').value = "";
                document.getElementById('userFormUsername').value = "";
                document.getElementById('userFormPassword').value = "";
                document.getElementById('userFormPassword').placeholder = "নতুন পাসওয়ার্ড লিখুন...";
                document.getElementById('userFormPassword').required = true;
                document.getElementById('userFormRole').value = "agent";
            }
        </script>

        <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-6">সকল সক্রিয় টিম মেম্বার্স</h3>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead>
                        <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs uppercase tracking-wider">
                            <th class="p-3">আইডি</th>
                            <th class="p-3">ইউজারনেম</th>
                            <th class="p-3">রোল</th>
                            <th class="p-3">যোগদানের তারিখ</th>
                            <th class="p-3 text-right">পদক্ষেপ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700">
                        <?php foreach ($users as $u): ?>
                            <tr class="text-sm">
                                <td class="p-3 font-mono font-bold">#<?= $u['id'] ?></td>
                                <td class="p-3 text-white font-semibold"><?= htmlspecialchars($u['username']) ?></td>
                                <td class="p-3">
                                    <span class="px-2 py-0.5 rounded text-xs font-semibold uppercase tracking-widest <?= $u['role'] === 'admin' ? 'bg-amber-500/20 text-amber-300' : ($u['role'] === 'office_team' ? 'bg-indigo-500/20 text-indigo-300' : 'bg-emerald-500/20 text-emerald-300') ?>">
                                        <?= htmlspecialchars($u['role']) ?>
                                    </span>
                                </td>
                                <td class="p-3 text-slate-400"><?= $u['created_at'] ?></td>
                                <td class="p-3 text-right space-x-2">
                                    <button type="button" onclick="editUser(<?= $u['id'] ?>, '<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>', '<?= $u['role'] ?>')" class="text-indigo-400 hover:text-indigo-300 text-xs font-bold">সম্পাদনা</button>
                                    <form action="" method="POST" onsubmit="return confirm('আপনি কি এই ইউজারটি ডিলিট করতে চান?') && confirm('আবারও নিশ্চিত করুন — ইউজারটি ডিলিট করবেন?')" class="inline">
                                        <input type="hidden" name="delete_user" value="1">
                                        <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                        <button type="submit" class="text-rose-400 hover:text-rose-300 text-xs font-bold" <?= $_SESSION['user_id'] == $u['id'] ? 'disabled style="opacity:0.3"' : '' ?>>মুছে ফেলুন</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php
}

function render_settings_panel($msg) {
    $colors = json_decode(get_setting('product_colors'), true) ?: [];
    ?>
    <div class="max-w-4xl mx-auto space-y-8 font-semibold">
        <?php if ($msg): ?>
            <div class="bg-emerald-500/10 border border-emerald-500 text-emerald-400 p-4 rounded-xl font-semibold"><?= $msg ?></div>
        <?php endif; ?>

        <form action="" method="POST" class="space-y-6">
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-signature text-emerald-400"></i> সাইটের নাম ও টাইটেল
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাইটের নাম (লগইন পেজ, ড্যাশবোর্ড, ইনভয়েস — সব জায়গায় দেখাবে)</label>
                        <input type="text" name="site_name" value="<?= htmlspecialchars(branding('site_name', 'SunnahTi')) ?>" placeholder="আপনার ব্র্যান্ড নাম" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাইট টাইটেল (ব্রাউজার ট্যাবে দেখাবে)</label>
                        <input type="text" name="site_title" value="<?= htmlspecialchars(branding('site_title')) ?>" placeholder="যেমন: My Premium Store" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                </div>
                <p class="text-[10px] text-slate-500 mt-2">লোগো, ফেভিকন ও হোম URL বদলাতে চাইলে <a href="?action=branding" class="text-cyan-400 hover:underline">ব্র্যান্ডিং ট্যাব</a> ব্যবহার করুন।</p>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-brands fa-whatsapp text-emerald-400"></i> ল্যান্ডিং পেজ ফ্লোটিং আইকন (WhatsApp ও ফোন)
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">WhatsApp নাম্বার</label>
                        <input type="text" name="contact_whatsapp" value="<?= htmlspecialchars(get_setting('contact_whatsapp')) ?>" placeholder="8801XXXXXXXXX (দেশের কোডসহ, + ছাড়া)" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                        <p class="text-[10px] text-slate-500 mt-1">যেমন: 8801711111111 — এই নাম্বারে wa.me চ্যাট খুলবে।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">ফোন (কল) নাম্বার</label>
                        <input type="text" name="contact_phone" value="<?= htmlspecialchars(get_setting('contact_phone')) ?>" placeholder="01XXXXXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                        <p class="text-[10px] text-slate-500 mt-1">আইকনে ট্যাপ করলে সরাসরি এই নাম্বারে কল যাবে।</p>
                    </div>
                </div>
                <p class="text-[10px] text-amber-400 mt-3"><i class="fa-solid fa-circle-info"></i> আইকন দুটি ল্যান্ডিং পেজের ডান পাশে নিচে ফিক্সড অবস্থায় ভাসবে। কোন পেজে কোনটা দেখাবে তা পেজ এডিটরের "ফ্লোটিং আইকন" অপশন থেকে ঠিক করুন।</p>
            </div>


            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-comment-sms text-lime-400"></i> SMS নোটিফিকেশন (BulkSMSBD)
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">API Key</label>
                        <input type="text" name="sms_api_key" value="<?= htmlspecialchars(get_setting('sms_api_key')) ?>" placeholder="bulksmsbd.net থেকে" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Sender ID</label>
                        <input type="text" name="sms_sender_id" value="<?= htmlspecialchars(get_setting('sms_sender_id')) ?>" placeholder="8809XXXXXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">কনফার্ম SMS টেমপ্লেট <span class="text-[10px] text-slate-500">({name} {order_id} {cod})</span></label>
                        <textarea name="sms_tpl_confirm" rows="2" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs"><?= htmlspecialchars(get_setting('sms_tpl_confirm')) ?></textarea>
                        <label class="flex items-center gap-2 text-xs text-slate-300 mt-1 cursor-pointer"><input type="checkbox" name="sms_on_confirm" <?= get_setting('sms_on_confirm') === '1' ? 'checked' : '' ?> class="rounded text-lime-500"> অর্ডার কনফার্ম হলে SMS যাবে</label>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">কুরিয়ার SMS টেমপ্লেট <span class="text-[10px] text-slate-500">({tracking} সহ)</span></label>
                        <textarea name="sms_tpl_courier" rows="2" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs"><?= htmlspecialchars(get_setting('sms_tpl_courier')) ?></textarea>
                        <label class="flex items-center gap-2 text-xs text-slate-300 mt-1 cursor-pointer"><input type="checkbox" name="sms_on_courier" <?= get_setting('sms_on_courier') === '1' ? 'checked' : '' ?> class="rounded text-lime-500"> কুরিয়ারে বুক হলে SMS যাবে</label>
                    </div>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-truck-fast text-orange-400"></i> কুরিয়ার / ডেলিভারি চার্জ
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">ঢাকার মধ্যে (৳)</label>
                        <input type="number" step="1" min="0" name="courier_charge_dhaka" value="<?= htmlspecialchars(get_setting('courier_charge_dhaka') ?: '60') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাব ঢাকার মধ্যে (৳)</label>
                        <input type="number" step="1" min="0" name="courier_charge_sub_dhaka" value="<?= htmlspecialchars(get_setting('courier_charge_sub_dhaka') ?: '100') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সারা বাংলাদেশের মধ্যে (৳)</label>
                        <input type="number" step="1" min="0" name="courier_charge_outside" value="<?= htmlspecialchars(get_setting('courier_charge_outside') ?: '130') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono">
                    </div>
                </div>
                <p class="text-[10px] text-slate-500 mt-2">কোন ল্যান্ডিং/প্রোডাক্ট পেজে ডেলিভারি চার্জ অপশন থাকবে তা সেই পেজের এডিটরের চেকবক্স থেকে ঠিক করুন — চার্জ নির্বাচন করলে COD-এর সাথে অটো যোগ হবে।</p>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-brands fa-telegram text-sky-400"></i> Telegram দৈনিক রিপোর্ট
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">বট টোকেন (@BotFather থেকে)</label>
                        <input type="text" name="telegram_bot_token" value="<?= htmlspecialchars(get_setting('telegram_bot_token')) ?>" placeholder="123456:ABC-DEF..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">চ্যাট আইডি (@userinfobot থেকে)</label>
                        <input type="text" name="telegram_chat_id" value="<?= htmlspecialchars(get_setting('telegram_chat_id')) ?>" placeholder="123456789" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs">
                    </div>
                </div>
                <div class="flex flex-wrap items-center gap-3 mt-3">
                    <button type="button" onclick="fetch('?action=telegram_report').then(r => r.json()).then(d => showToast(d.message, d.status === 'success' ? 'success' : 'error'))" class="bg-sky-600 hover:bg-sky-500 text-white text-xs font-bold px-4 py-2 rounded-lg"><i class="fa-solid fa-paper-plane"></i> টেস্ট রিপোর্ট পাঠান</button>
                    <p class="text-[10px] text-slate-500">প্রতিদিন অটো পেতে cPanel → Cron Jobs-এ দিন (রাত ১১:৫৫):<br><code class="text-cyan-400 select-all">curl -s "<?= rtrim(base_url(), '/') ?>/?action=telegram_report&key=<?= htmlspecialchars(get_setting('cron_secret')) ?>" > /dev/null</code></p>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-database text-emerald-400"></i> ডাটাবেজ ব্যাকআপ
                </h3>
                <div class="flex flex-wrap items-center gap-4">
                    <a href="?action=db_backup" class="bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-bold px-5 py-2.5 rounded-xl inline-flex items-center gap-2"><i class="fa-solid fa-download"></i> ব্যাকআপ ডাউনলোড (.sql)</a>
                    <p class="text-[10px] text-slate-500">সব টেবিল ও ডেটা এক ফাইলে নামবে — সপ্তাহে অন্তত একবার নামিয়ে নিরাপদে রাখুন। রিস্টোর: phpMyAdmin → Import।</p>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-1 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-palette text-violet-400"></i> ড্যাশবোর্ড থিম (৭টি)
                </h3>
                <p class="text-[10px] text-slate-500 my-3">ক্লিক করা মাত্রই থিম বদলে যাবে — আপনার এই ব্রাউজারে মনে রাখা হবে (প্রতি ইউজার নিজের পছন্দমতো থিম রাখতে পারবে)।</p>
                <div class="grid grid-cols-4 md:grid-cols-7 gap-3">
                    <?php
                    $dash_themes = [
                        'slate'    => ['ডার্ক স্লেট', '#0f172a', '#1e293b', '#10b981'],
                        'midnight' => ['মিডনাইট ব্লু', '#04122e', '#132b5c', '#38bdf8'],
                        'emerald'  => ['ডিপ গ্রিন', '#032118', '#0a4534', '#34d399'],
                        'purple'   => ['রয়্যাল পার্পল', '#180735', '#341a63', '#c084fc'],
                        'crimson'  => ['ক্রিমসন', '#270511', '#4e132b', '#fb7185'],
                        'coffee'   => ['কফি ব্রাউন', '#1f150b', '#3f2d1b', '#fbbf24'],
                        'light'    => ['লাইট মোড', '#ffffff', '#eef2f7', '#059669'],
                    ];
                    ?>
                    <?php foreach ($dash_themes as $tkey => $t): ?>
                    <button type="button" onclick="setDashTheme('<?= $tkey ?>')" data-theme-btn="<?= $tkey ?>" class="theme-swatch group rounded-2xl border-2 border-slate-600 p-2 transition hover:scale-105" title="<?= $t[0] ?>">
                        <div class="h-10 rounded-xl overflow-hidden flex">
                            <div class="w-1/2" style="background: <?= $t[1] ?>;"></div>
                            <div class="w-1/2 flex flex-col">
                                <div class="flex-1" style="background: <?= $t[2] ?>;"></div>
                                <div class="h-2.5" style="background: <?= $t[3] ?>;"></div>
                            </div>
                        </div>
                        <span class="block text-[9px] font-bold text-slate-300 mt-1.5 text-center"><?= $t[0] ?></span>
                    </button>
                    <?php endforeach; ?>
                </div>
                <script>
                    function setDashTheme(name) {
                        try { localStorage.setItem('dashTheme', name); } catch (e) {}
                        if (name === 'slate') document.documentElement.removeAttribute('data-theme');
                        else document.documentElement.setAttribute('data-theme', name);
                        markActiveTheme();
                        showToast('থিম বদলানো হয়েছে!', 'success');
                    }
                    function markActiveTheme() {
                        const cur = localStorage.getItem('dashTheme') || 'slate';
                        document.querySelectorAll('.theme-swatch').forEach(b => {
                            b.classList.toggle('border-emerald-400', b.dataset.themeBtn === cur);
                            b.classList.toggle('border-slate-600', b.dataset.themeBtn !== cur);
                        });
                    }
                    document.addEventListener('DOMContentLoaded', markActiveTheme);
                </script>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-house text-emerald-400"></i> রুট ডোমেইনের হোম পেজ
                </h3>
                <?php
                $hp_pages = [];
                $hp_products = [];
                try {
                    global $db;
                    $hp_pages = $db->query("SELECT title, slug FROM pages ORDER BY id DESC")->fetchAll();
                    $hp_products = $db->query("SELECT title, slug FROM products ORDER BY id DESC")->fetchAll();
                } catch (Exception $e) {}
                $hp_current = get_setting('home_page_slug');
                ?>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সরাসরি ডোমেইনে (<span class="font-mono text-emerald-400"><?= htmlspecialchars(parse_url(base_url(), PHP_URL_HOST) ?: 'আপনার-ডোমেইন.com') ?></span>) ঢুকলে কোন পেজ দেখাবে?</label>
                        <select name="home_page_slug" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                            <option value="">লগইন পেজ (ডিফল্ট — কিছু সিলেক্ট করা নেই)</option>
                            <?php if (!empty($hp_pages)): ?>
                            <optgroup label="📄 ল্যান্ডিং পেজসমূহ">
                                <?php foreach ($hp_pages as $hp): ?>
                                <option value="<?= htmlspecialchars($hp['slug']) ?>" <?= $hp_current === $hp['slug'] ? 'selected' : '' ?>><?= htmlspecialchars($hp['title']) ?> (/<?= htmlspecialchars($hp['slug']) ?>)</option>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                            <?php if (!empty($hp_products)): ?>
                            <optgroup label="📦 প্রোডাক্ট পেজসমূহ">
                                <?php foreach ($hp_products as $hp): ?>
                                <option value="<?= htmlspecialchars($hp['slug']) ?>" <?= $hp_current === $hp['slug'] ? 'selected' : '' ?>><?= htmlspecialchars($hp['title']) ?> (/<?= htmlspecialchars($hp['slug']) ?>)</option>
                                <?php endforeach; ?>
                            </optgroup>
                            <?php endif; ?>
                        </select>
                    </div>
                    <p class="text-[10px] text-slate-500 bg-slate-900/60 border border-slate-700 rounded-lg px-4 py-3">💡 হোম পেজ সেট করলে অ্যাডমিন প্যানেলে ঢুকতে ব্যবহার করুন: <span class="font-mono text-cyan-400"><?= htmlspecialchars(rtrim(base_url(), '/')) ?>/?action=login</span> — এই লিংকটা বুকমার্ক করে রাখুন।</p>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-share-nodes text-sky-400"></i> ডিফল্ট সোশাল শেয়ার ইমেজ (OG Image)
                </h3>
                <div class="flex flex-col md:flex-row gap-4 items-start">
                    <div class="flex-1 w-full">
                        <label class="block text-slate-300 text-sm mb-1">ইমেজ URL</label>
                        <div class="flex gap-2">
                            <input type="text" name="og_default_image" id="og-default-input" value="<?= htmlspecialchars(get_setting('og_default_image')) ?>" placeholder="https://.../uploads/media/img_x.png" class="flex-1 bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm" oninput="document.getElementById('og-default-preview').src = this.value">
                            <button type="button" onclick="openMediaPicker('og-default-input', 'og-default-preview')" class="bg-sky-600 hover:bg-sky-500 text-white text-xs px-3 rounded-lg whitespace-nowrap"><i class="fa-solid fa-images"></i> মিডিয়া থেকে বাছুন</button>
                        </div>
                        <p class="text-[10px] text-slate-500 mt-1">ল্যান্ডিং/প্রোডাক্ট পেজে নিজস্ব শেয়ার ইমেজ সেট না থাকলে এই ইমেজটাই ফেসবুক/হোয়াটসঅ্যাপ শেয়ারে দেখাবে। রেকমেন্ডেড সাইজ: 1200×630।</p>
                    </div>
                    <img id="og-default-preview" src="<?= htmlspecialchars(get_setting('og_default_image')) ?>" onerror="this.style.display='none'" onload="this.style.display='block'" class="w-40 aspect-[1200/630] object-cover rounded-xl border border-slate-600 bg-slate-900">
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-shield-halved text-rose-500"></i> FraudShield ইন্টিগ্রেশন সেটিংস
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Fraud API Key</label>
                        <input type="text" name="fraud_api_key" value="<?= htmlspecialchars(get_setting('fraud_api_key')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Fraud API URL</label>
                        <input type="text" name="fraud_api_url" value="<?= htmlspecialchars(get_setting('fraud_api_url')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-truck text-emerald-500"></i> Steadfast কুরিয়ার API সেটিংস
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Steadfast API Key</label>
                        <input type="text" name="steadfast_api_key" value="<?= htmlspecialchars(get_setting('steadfast_api_key')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Steadfast Secret Key</label>
                        <input type="text" name="steadfast_secret_key" value="<?= htmlspecialchars(get_setting('steadfast_secret_key')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">Steadfast Base URL</label>
                        <input type="text" name="steadfast_base_url" value="<?= htmlspecialchars(get_setting('steadfast_base_url')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">ইনভয়েস নম্বর প্রিফিক্স</label>
                        <div class="flex items-center gap-2">
                            <input type="text" name="invoice_prefix" value="<?= htmlspecialchars(get_setting('invoice_prefix') ?: 'ST-') ?>" placeholder="ST-" class="w-32 bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono">
                            <span class="text-slate-500 text-sm">+ অর্ডার নম্বর = <span class="text-emerald-400 font-mono"><?= htmlspecialchars(get_setting('invoice_prefix') ?: 'ST-') ?>1024</span></span>
                        </div>
                        <p class="text-[10px] text-slate-500 mt-1">কুরিয়ারে বুক করার সময় এই প্রিফিক্স + অর্ডার নম্বর ইনভয়েস হিসেবে যাবে। যেমন: <b>INV-</b>, <b>ORDER-</b>, বা খালি রাখলে শুধু নম্বর।</p>
                    </div>
                </div>
            </div>

            <!-- Feature 3: Google Sheet connection with field-by-field guidance -->
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-table text-green-500"></i> Google Sheet কানেকশন (অটো অর্ডার এক্সপোর্ট)
                </h3>
                <div class="space-y-4">
                    <label class="flex items-center gap-2 text-slate-300 text-sm">
                        <input type="checkbox" name="gsheet_enabled" <?= get_setting('gsheet_enabled') === '1' ? 'checked' : '' ?> class="rounded text-emerald-500">
                        Google Sheet এ অটো অর্ডার পাঠানো চালু করুন
                    </label>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Apps Script Web App URL</label>
                            <input type="text" name="gsheet_webapp_url" value="<?= htmlspecialchars(get_setting('gsheet_webapp_url')) ?>" placeholder="https://script.google.com/macros/s/XXXX/exec" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs">
                            <p class="text-[10px] text-slate-400 mt-1 leading-relaxed">
                                <i class="fa-solid fa-circle-info text-sky-400"></i> কোথায় পাবেন: আপনার Google Sheet খুলুন &rarr; উপরের মেনু থেকে <b>Extensions &rarr; Apps Script</b> &rarr; নিচের কোডটি পেস্ট করুন &rarr; <b>Deploy &rarr; New deployment &rarr; Web app</b> &rarr; Access: <b>Anyone</b> সিলেক্ট করুন &rarr; Deploy চাপুন &rarr; যে URL পাবেন সেটি এখানে দিন।
                            </p>
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Sheet Name (ট্যাবের নাম)</label>
                            <input type="text" name="gsheet_sheet_name" value="<?= htmlspecialchars(get_setting('gsheet_sheet_name') ?: 'Orders') ?>" placeholder="Orders" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs">
                            <p class="text-[10px] text-slate-400 mt-1 leading-relaxed">
                                <i class="fa-solid fa-circle-info text-sky-400"></i> কোথায় পাবেন: Google Sheet এর একদম নিচে বাম পাশে যে ট্যাবের নাম (যেমন: Sheet1 বা Orders) দেখা যায়, সেই নামটি এখানে লিখুন। ট্যাবটি না থাকলে অটো তৈরি হয়ে যাবে।
                            </p>
                        </div>
                    </div>

                    <div class="border border-slate-700 bg-slate-900/60 rounded-xl p-3">
                        <span class="text-[11px] text-amber-400 font-bold block mb-2"><i class="fa-solid fa-code"></i> Apps Script এ এই কোডটি পেস্ট করুন (কপি বাটনে ক্লিক করুন):</span>
                        <pre id="gsheetScriptCode" class="text-[10px] text-slate-300 font-mono whitespace-pre-wrap bg-slate-950/60 p-3 rounded-lg overflow-x-auto">function doPost(e) {
  var d = JSON.parse(e.postData.contents);
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName(d.sheet) || ss.insertSheet(d.sheet);
  if (sh.getLastRow() === 0) {
    sh.appendRow(['Order ID','Date','Name','Phone','Address','Product','Color','Size','Weight','Amount','Status','IP']);
  }
  sh.appendRow([d.order_id, d.date, d.name, d.phone, d.address, d.product, d.color, d.size, d.weight, d.amount, d.status, d.ip]);
  return ContentService.createTextOutput(JSON.stringify({status:'success'})).setMimeType(ContentService.MimeType.JSON);
}</pre>
                        <button type="button" onclick="copyText(document.getElementById('gsheetScriptCode').innerText)" class="mt-2 text-xs bg-slate-700 hover:bg-slate-600 text-white px-3 py-1.5 rounded font-semibold transition"><i class="fa-regular fa-copy"></i> কোড কপি করুন</button>
                    </div>

                    <div class="text-[10px] text-slate-400 bg-slate-900/40 border border-slate-700 rounded-lg p-3 leading-relaxed">
                        <b class="text-slate-300">যে ফিল্ডগুলো সেভ হবে:</b> অর্ডার আইডি, তারিখ ও সময়, গ্রাহকের নাম, মোবাইল নাম্বার, ঠিকানা, পণ্যের নাম, কালার, সাইজ, ওজন, COD এমাউন্ট, স্ট্যাটাস, কাস্টমারের আইপি — প্রতিটি নতুন অর্ডারে অটোমেটিক এক লাইন করে Google Sheet এ যুক্ত হবে।
                    </div>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-brands fa-facebook text-blue-500"></i> গ্লোবাল পিক্সেল এবং কনভার্সন API (CAPI) ট্র্যাকিং সেটিংস
                </h3>
                <div class="space-y-6">
                    <div class="border border-slate-700 p-4 rounded-xl bg-slate-900/40">
                        <h4 class="text-sm font-bold text-white mb-3 flex items-center gap-2">
                            <i class="fa-brands fa-facebook text-indigo-400"></i> Meta / Facebook Pixel &amp; CAPI
                        </h4>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Facebook Pixel ID</label>
                                <input type="text" name="facebook_pixel" value="<?= htmlspecialchars(get_setting('facebook_pixel')) ?>" placeholder="e.g. 1234567890" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Google Analytics G4 ID</label>
                                <input type="text" name="google_tag" value="<?= htmlspecialchars(get_setting('google_tag')) ?>" placeholder="e.g. G-XXXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Facebook Conversion API Access Token</label>
                                <input type="text" name="facebook_access_token" value="<?= htmlspecialchars(get_setting('facebook_access_token')) ?>" placeholder="EAAG..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Facebook Test Event Code (ঐচ্ছিক)</label>
                                <input type="text" name="facebook_test_code" value="<?= htmlspecialchars(get_setting('facebook_test_code')) ?>" placeholder="TESTXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                        </div>
                    </div>

                    <div class="border border-slate-700 p-4 rounded-xl bg-slate-900/40">
                        <h4 class="text-sm font-bold text-white mb-3 flex items-center gap-2">
                            <i class="fa-brands fa-tiktok text-pink-400"></i> TikTok Pixel &amp; CAPI
                        </h4>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Tiktok Pixel ID</label>
                                <input type="text" name="tiktok_pixel" value="<?= htmlspecialchars(get_setting('tiktok_pixel')) ?>" placeholder="e.g. CXXXXXXXXXXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Tiktok Conversion API Access Token</label>
                                <input type="text" name="tiktok_access_token" value="<?= htmlspecialchars(get_setting('tiktok_access_token')) ?>" placeholder="e.g. tiktok_token_..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                            <div>
                                <label class="block text-slate-300 text-xs mb-1">Tiktok Test Event Code (ঐচ্ছিক)</label>
                                <input type="text" name="tiktok_test_code" value="<?= htmlspecialchars(get_setting('tiktok_test_code')) ?>" placeholder="e.g. TEST1234" class="w-full bg-slate-700 text-white rounded-lg px-3 py-1.5 text-xs outline-none border border-slate-600">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-list-check text-indigo-500"></i> গ্লোবাল চেকআউট ফিল্ড কাস্টমাইজেশন (ডিফল্ট)
                </h3>
                <?php $fields = json_decode(get_setting('checkout_fields'), true) ?: []; ?>
                <div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_name" <?= !isset($fields['name']) || $fields['name'] ? 'checked' : '' ?> class="rounded text-emerald-500"> গ্রাহকের নাম
                    </label>
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_phone" <?= !isset($fields['phone']) || $fields['phone'] ? 'checked' : '' ?> class="rounded text-emerald-500"> মোবাইল নম্বর
                    </label>
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_alt_phone" <?= !isset($fields['alt_phone']) || $fields['alt_phone'] ? 'checked' : '' ?> class="rounded text-emerald-500"> অল্টারনেটিভ ফোন
                    </label>
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_address" <?= !isset($fields['address']) || $fields['address'] ? 'checked' : '' ?> class="rounded text-emerald-500"> কাস্টমার ঠিকানা
                    </label>
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_color" <?= !isset($fields['color']) || $fields['color'] ? 'checked' : '' ?> class="rounded text-emerald-500"> কালার নির্বাচন অপশন
                    </label>
                    <label class="flex items-center gap-2 text-slate-300">
                        <input type="checkbox" name="field_note" <?= !isset($fields['note']) || $fields['note'] ? 'checked' : '' ?> class="rounded text-emerald-500"> বিশেষ নির্দেশাবলী (Note)
                    </label>
                </div>
            </div>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-palette text-amber-500"></i> ২০টি মোস্ট ডিমান্ড কালার এবং কাস্টম কালার তালিকা
                </h3>

                <div class="grid grid-cols-2 gap-4 mb-4" id="colorContainer">
                    <?php foreach ($colors as $idx => $c): ?>
                        <div class="flex gap-2 items-center bg-slate-700/40 p-2 rounded-lg border border-slate-700">
                            <input type="text" name="color_en[]" value="<?= htmlspecialchars($c['en']) ?>" placeholder="English Name" class="w-1/2 bg-slate-700 text-white rounded px-2 py-1 text-xs outline-none">
                            <input type="text" name="color_bn[]" value="<?= htmlspecialchars($c['bn'] ?? '') ?>" placeholder="বাংলা নাম" class="w-1/2 bg-slate-700 text-white rounded px-2 py-1 text-xs outline-none">
                            <button type="button" onclick="this.parentElement.remove()" class="text-rose-500 text-xs font-bold px-1">&times;</button>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" onclick="addNewColorField()" class="text-xs bg-indigo-600 hover:bg-indigo-500 px-3 py-1.5 rounded font-semibold text-white">নতুন কালার যোগ করুন +</button>
            </div>

            <div class="flex justify-end">
                <button type="submit" class="bg-emerald-600 hover:bg-emerald-500 text-white px-6 py-2.5 rounded-xl font-bold transition shadow-lg text-sm">কনফিগারেশন সেভ করুন</button>
            </div>
        </form>

        <!-- প্রোমো কোড ম্যানেজার (আলাদা ফর্ম — ওপরের সেভ বাটনের সাথে সম্পর্ক নেই) -->
        <?php
        $promo_list = [];
        try { $promo_list = $db->query("SELECT * FROM promo_codes ORDER BY id DESC")->fetchAll(); } catch (Exception $e) {}
        $pmsg_map = [
            'added' => ['s', 'প্রোমো কোড যোগ হয়েছে!'], 'deleted' => ['s', 'প্রোমো কোড ডিলিট হয়েছে!'],
            'toggled' => ['s', 'প্রোমো কোডের স্ট্যাটাস বদলানো হয়েছে!'], 'exists' => ['e', 'এই কোডটি ইতিমধ্যে আছে!'],
            'invalid' => ['e', 'কোড ও ছাড়ের পরিমাণ সঠিকভাবে দিন!'],
        ];
        ?>
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md mt-6">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                <i class="fa-solid fa-ticket text-pink-400"></i> প্রোমো কোড ম্যানেজার
            </h3>
            <?php if (isset($_GET['pmsg'], $pmsg_map[$_GET['pmsg']])): $pm = $pmsg_map[$_GET['pmsg']]; ?>
                <div class="<?= $pm[0] === 'e' ? 'bg-rose-500/10 border-rose-500 text-rose-400' : 'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-3 rounded-xl text-xs mb-4"><?= $pm[1] ?></div>
            <?php endif; ?>
            <form action="?action=settings" method="POST" class="grid grid-cols-2 md:grid-cols-6 gap-3 items-end mb-5">
                <input type="hidden" name="add_promo" value="1">
                <div class="col-span-2 md:col-span-1">
                    <label class="block text-slate-300 text-xs mb-1">কোড</label>
                    <input type="text" name="promo_code" required placeholder="EID50" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono uppercase">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">ছাড়ের ধরন</label>
                    <select name="promo_type" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                        <option value="flat">টাকা (৳)</option>
                        <option value="percent">পারসেন্ট (%)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">ছাড়ের পরিমাণ</label>
                    <input type="number" step="0.01" min="1" name="promo_value" required placeholder="50" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">ভ্যালিডিটি (শেষ তারিখ)</label>
                    <input type="date" name="promo_until" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">সর্বোচ্চ ব্যবহার (০ = আনলিমিটেড)</label>
                    <input type="number" min="0" name="promo_max" value="0" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <button type="submit" class="bg-pink-600 hover:bg-pink-500 text-white text-sm font-bold px-4 py-2.5 rounded-xl"><i class="fa-solid fa-plus"></i> যোগ করুন</button>
            </form>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-xs">
                    <thead><tr class="text-slate-400 border-b border-slate-700">
                        <th class="py-2 px-2">কোড</th><th class="py-2 px-2">ছাড়</th><th class="py-2 px-2">ভ্যালিডিটি</th><th class="py-2 px-2">ব্যবহার</th><th class="py-2 px-2">স্ট্যাটাস</th><th class="py-2 px-2 text-right">অ্যাকশন</th>
                    </tr></thead>
                    <tbody>
                    <?php if (empty($promo_list)): ?>
                        <tr><td colspan="6" class="py-6 text-center text-slate-500">কোনো প্রোমো কোড নেই — ওপরের ফর্ম থেকে যোগ করুন।</td></tr>
                    <?php else: foreach ($promo_list as $pr):
                        $expired = !empty($pr['valid_until']) && strtotime($pr['valid_until'] . ' 23:59:59') < time();
                    ?>
                        <tr class="border-b border-slate-700/50">
                            <td class="py-2.5 px-2 font-mono font-bold text-white"><?= htmlspecialchars($pr['code']) ?></td>
                            <td class="py-2.5 px-2 text-emerald-400 font-bold"><?= $pr['discount_type'] === 'percent' ? (float)$pr['discount_value'] . '%' : '৳' . (float)$pr['discount_value'] ?></td>
                            <td class="py-2.5 px-2 <?= $expired ? 'text-rose-400' : 'text-slate-300' ?>"><?= $pr['valid_until'] ? date('d M Y', strtotime($pr['valid_until'])) . ($expired ? ' (মেয়াদ শেষ)' : '') : 'আনলিমিটেড' ?></td>
                            <td class="py-2.5 px-2 font-mono text-slate-300"><?= (int)$pr['used_count'] ?><?= (int)$pr['max_uses'] > 0 ? ' / ' . (int)$pr['max_uses'] : '' ?></td>
                            <td class="py-2.5 px-2">
                                <form action="?action=settings" method="POST" class="inline">
                                    <input type="hidden" name="toggle_promo" value="1">
                                    <input type="hidden" name="promo_id" value="<?= (int)$pr['id'] ?>">
                                    <button type="submit" class="text-[10px] font-bold px-2.5 py-1 rounded-full <?= $pr['active'] ? 'bg-emerald-600/20 text-emerald-400' : 'bg-slate-600/40 text-slate-400' ?>" title="ক্লিক করে চালু/বন্ধ করুন"><?= $pr['active'] ? 'চালু ✓' : 'বন্ধ' ?></button>
                                </form>
                            </td>
                            <td class="py-2.5 px-2 text-right">
                                <form action="?action=settings" method="POST" class="inline" onsubmit="return confirm('প্রোমো কোডটি ডিলিট করবেন?');">
                                    <input type="hidden" name="delete_promo" value="1">
                                    <input type="hidden" name="promo_id" value="<?= (int)$pr['id'] ?>">
                                    <button type="submit" class="text-rose-400 hover:text-rose-300 p-1"><i class="fa-solid fa-trash"></i></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function addNewColorField() {
            const container = document.getElementById('colorContainer');
            const div = document.createElement('div');
            div.className = "flex gap-2 items-center bg-slate-700/40 p-2 rounded-lg border border-slate-700";
            div.innerHTML = `
                <input type="text" name="color_en[]" placeholder="English Name" class="w-1/2 bg-slate-700 text-white rounded px-2 py-1 text-xs outline-none">
                <input type="text" name="color_bn[]" placeholder="বাংলা নাম" class="w-1/2 bg-slate-700 text-white rounded px-2 py-1 text-xs outline-none">
                <button type="button" onclick="this.parentElement.remove()" class="text-rose-500 text-xs font-bold px-1">&times;</button>
            `;
            container.appendChild(div);
        }
    </script>
    <?php
}

function render_products_panel($products, $all_categories = [], $cat_filter = 0) {
    ?>
    <!-- ক্যাটাগরি বার: লিংকে ক্লিক = ফিল্টার; আইকনে এডিট / কপি / ডিলিট; + নতুন -->
    <div class="bg-slate-800 border border-slate-700 rounded-2xl px-4 py-3 mb-6 flex items-center gap-2 flex-wrap font-semibold">
        <span class="text-[11px] text-slate-400 font-bold uppercase mr-1"><i class="fa-solid fa-tags text-amber-400"></i> ক্যাটাগরি:</span>
        <a href="?action=products" class="text-xs px-3 py-1.5 rounded-full border transition <?= $cat_filter === 0 ? 'bg-emerald-600 border-emerald-500 text-white' : 'bg-slate-900 border-slate-700 text-slate-300 hover:border-emerald-500' ?>">সব প্রোডাক্ট</a>
        <a href="?action=products&cat=-1" class="text-xs px-3 py-1.5 rounded-full border transition <?= $cat_filter === -1 ? 'bg-slate-600 border-slate-500 text-white' : 'bg-slate-900 border-slate-700 text-slate-300 hover:border-slate-500' ?>">ক্যাটাগরিহীন</a>
        <?php foreach ($all_categories as $cat): ?>
        <span class="inline-flex items-center gap-1 rounded-full border transition <?= $cat_filter === (int)$cat['id'] ? 'bg-amber-600/30 border-amber-500' : 'bg-slate-900 border-slate-700 hover:border-amber-500' ?>">
            <a href="?action=products&cat=<?= (int)$cat['id'] ?>" class="text-xs pl-3 py-1.5 <?= $cat_filter === (int)$cat['id'] ? 'text-amber-300 font-bold' : 'text-slate-300' ?>" title="এই ক্যাটাগরির প্রোডাক্ট দেখুন"><?= htmlspecialchars($cat['name']) ?></a>
            <span class="flex items-center pr-2 gap-0.5 text-[10px]">
                <button type="button" onclick="editCategory(<?= (int)$cat['id'] ?>, '<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>')" title="এডিট" class="text-indigo-400 hover:text-indigo-300 p-1"><i class="fa-solid fa-pen"></i></button>
                <button type="button" onclick="duplicateCategory(<?= (int)$cat['id'] ?>)" title="কপি" class="text-amber-400 hover:text-amber-300 p-1"><i class="fa-solid fa-copy"></i></button>
                <button type="button" onclick="deleteCategoryConfirm(<?= (int)$cat['id'] ?>, '<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>')" title="ডিলিট" class="text-rose-400 hover:text-rose-300 p-1"><i class="fa-solid fa-trash"></i></button>
            </span>
        </span>
        <?php endforeach; ?>
        <button type="button" onclick="var ci=document.getElementById('cat-edit-name'); if(ci){ci.scrollIntoView({behavior:'smooth', block:'center'}); ci.focus();}" class="text-xs px-3 py-1.5 rounded-full bg-emerald-600/20 border border-emerald-600/50 text-emerald-400 hover:bg-emerald-600/40 transition" title="নতুন ক্যাটাগরি তৈরি করুন"><i class="fa-solid fa-plus"></i> নতুন ক্যাটাগরি</button>
    </div>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 font-semibold">
        <div class="space-y-6">
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
                <h3 class="text-lg font-bold text-white mb-6" id="form-title" data-i18n="নতুন প্রোডাক্ট তৈরি করুন">নতুন প্রোডাক্ট তৈরি করুন</h3>
                <form action="" method="POST" class="space-y-4">
                    <input type="hidden" name="save_product" value="1">
                    <input type="hidden" name="product_id" id="prod-id" value="0">

                    <div>
                        <label class="block text-slate-300 text-sm mb-1">প্রোডাক্ট টাইটেল (Title)</label>
                        <input type="text" name="title" id="prod-title" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">কাস্টম স্লাগ (Slug - Optional)</label>
                        <input type="text" name="slug" id="prod-slug" placeholder="e.g. organic-honey" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1"><i class="fa-solid fa-tags text-amber-400"></i> ক্যাটাগরি</label>
                        <select name="category_id" id="prod-category" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                            <option value="0">— কোনো ক্যাটাগরি নেই —</option>
                            <?php foreach ($all_categories as $cat): ?>
                                <option value="<?= (int)$cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <p class="text-[10px] text-slate-500 mt-1">নতুন ক্যাটাগরি বানাতে ডান পাশের "ক্যাটাগরি ম্যানেজার" ব্যবহার করুন।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1"><i class="fa-solid fa-share-nodes text-sky-400"></i> সোশাল শেয়ার ইমেজ (OG)</label>
                        <div class="flex gap-2">
                            <input type="text" name="og_image" id="prod-og-image" placeholder="খালি রাখলে ডিফল্ট ইমেজ" oninput="document.getElementById('prod-og-preview').src = this.value" class="flex-1 bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs">
                            <button type="button" onclick="openMediaPicker('prod-og-image', 'prod-og-preview')" class="bg-sky-600 hover:bg-sky-500 text-white text-xs px-2.5 rounded-lg whitespace-nowrap"><i class="fa-solid fa-images"></i></button>
                        </div>
                        <img id="prod-og-preview" src="" onerror="this.style.display='none'" onload="this.style.display='block'" class="w-36 aspect-[1200/630] object-cover rounded-lg border border-slate-600 bg-slate-900 mt-2" style="display:none">
                        <p class="text-[10px] text-slate-500 mt-1">প্রোডাক্ট ল্যান্ডিং পেজের লিংক ফেসবুক/হোয়াটসঅ্যাপে শেয়ার করলে এই ছবিটা প্রিভিউ হবে।</p>
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="block text-slate-300 text-sm mb-1">মূল প্রাইস (৳)</label>
                            <input type="number" step="0.01" name="price" id="prod-price" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-sm mb-1">ডিসকাউন্ট প্রাইস (৳)</label>
                            <input type="number" step="0.01" name="sale_price" id="prod-sale" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-sm mb-1">কেনা দাম (৳) <span class="text-[9px] text-amber-400">লাভ-ক্ষতি হিসাবের জন্য</span></label>
                            <input type="number" step="0.01" name="cost_price" id="prod-cost" placeholder="যেমন: ৩৫০" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        </div>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">স্টক পরিমাণ (পিস)</label>
                        <input type="number" name="stock" id="prod-stock" required min="0" placeholder="যেমন: ১০০" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">প্রোডাক্ট ইমেজ ইউআরএল (URL)</label>
                        <input type="text" name="image_url" id="prod-image" placeholder="https://... (মিডিয়া ম্যানেজার থেকে লিংক কপি করে দিতে পারেন)" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">প্রোডাক্ট বর্ণনা (Description)</label>
                        <textarea name="description" id="prod-desc" rows="4" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none"></textarea>
                    </div>

                    <div class="border border-slate-700 p-3 rounded-lg bg-slate-900/40 space-y-2">
                        <span class="text-xs text-emerald-400 font-bold block mb-1">এই প্রোডাক্টের জন্য নির্দিষ্ট কাস্টম চেকআউট ফিল্ডস:</span>
                        <div class="grid grid-cols-2 gap-2 text-xs">
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_name" id="p-field-name" checked class="rounded text-emerald-500"> নাম
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_phone" id="p-field-phone" checked class="rounded text-emerald-500"> মোবাইল
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_alt_phone" id="p-field-alt-phone" checked class="rounded text-emerald-500"> অল্টারনেটিভ ফোন
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_address" id="p-field-address" checked class="rounded text-emerald-500"> ঠিকানা
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_color" id="p-field-color" checked class="rounded text-emerald-500"> কালার সিলেক্টর
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_field_note" id="p-field-note" checked class="rounded text-emerald-500"> নোট ফিল্ড
                            </label>
                        </div>
                        <div class="mt-2 pt-2 border-t border-slate-700/60">
                            <label class="flex items-center gap-1.5 text-fuchsia-300 text-xs cursor-pointer">
                                <input type="checkbox" name="p_custom_field" id="p-custom-field" onchange="document.getElementById('p-custom-field-label-wrap').classList.toggle('hidden', !this.checked)" class="rounded text-fuchsia-500"> চেকআউটে এক্সট্রা কাস্টম ফিল্ড (আবশ্যক) থাকবে
                            </label>
                            <div id="p-custom-field-label-wrap" class="hidden mt-1.5">
                                <input type="text" name="p_custom_field_label" id="p-custom-field-label" placeholder="ফিল্ডের প্রশ্ন — যেমন: পছন্দের ডেলিভারি সময়?" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs">
                            </div>
                            <label class="flex items-center gap-1.5 text-orange-300 text-xs cursor-pointer mt-1.5">
                                <input type="checkbox" name="p_courier_charge" id="p-courier-charge" class="rounded text-orange-500"> কুরিয়ার চার্জ অপশন (ঢাকা/সাব/সারাদেশ)
                            </label>
                            <label class="flex items-center gap-1.5 text-orange-300 text-xs cursor-pointer mt-1">
                                <input type="checkbox" name="p_promo_code" id="p-promo-code" class="rounded text-orange-500"> প্রোমো কোড অপশন
                            </label>
                        </div>
                    </div>

                    <div class="border border-indigo-500/30 p-3 rounded-lg bg-indigo-950/30 space-y-2">
                        <span class="text-xs text-indigo-400 font-bold block mb-1"><i class="fa-solid fa-shirt"></i> ভ্যারিয়েন্ট অপশন (চেকআউট পেজে কোনগুলো দেখাবে):</span>
                        <div class="grid grid-cols-1 gap-2 text-xs">
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_variant_size_teen" id="p-variant-teen" class="rounded text-indigo-500"> Teen/Adult সাইজ (XXS - 8XL)
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_variant_size_kids" id="p-variant-kids" class="rounded text-indigo-500"> Baby/Kids সাইজ (0-6 Months - 12-14 years)
                            </label>
                            <label class="flex items-center gap-1.5 text-slate-300">
                                <input type="checkbox" name="p_variant_weight" id="p-variant-weight" class="rounded text-indigo-500"> ওজন অপশন (200g - 20kg + Custom)
                            </label>
                        </div>
                        <p class="text-[10px] text-slate-400">একই প্রোডাক্টের কালার, সাইজ, ওজন এক হয় না — তাই প্রতিটি প্রোডাক্টের জন্য আলাদাভাবে সিলেক্ট করুন।</p>
                    </div>

                    <div class="flex gap-3">
                        <button type="submit" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded-lg font-semibold transition w-full" data-i18n="সেভ প্রোডাক্ট">সেভ প্রোডাক্ট</button>
                        <button type="button" onclick="resetProductForm()" class="bg-slate-700 hover:bg-slate-600 text-white px-4 py-2 rounded-lg text-xs" data-i18n="রিসেট">রিসেট</button>
                    </div>
                </form>
            </div>

            <!-- ক্যাটাগরি ম্যানেজার -->
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
                <h3 class="text-base font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-tags text-amber-400"></i> <span data-i18n="ক্যাটাগরি ম্যানেজার">ক্যাটাগরি ম্যানেজার</span>
                </h3>
                <form action="?action=products" method="POST" class="flex gap-2 mb-4">
                    <input type="hidden" name="save_category" value="1">
                    <input type="hidden" name="category_id" id="cat-edit-id" value="0">
                    <input type="text" name="category_name" id="cat-edit-name" required placeholder="ক্যাটাগরির নাম লিখুন" class="flex-1 bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    <button type="submit" id="cat-save-btn" class="bg-amber-600 hover:bg-amber-500 text-white px-4 py-2 rounded-lg text-xs font-bold whitespace-nowrap">+ যোগ করুন</button>
                    <button type="button" id="cat-cancel-btn" onclick="resetCategoryForm()" class="hidden bg-slate-700 hover:bg-slate-600 text-white px-3 py-2 rounded-lg text-xs">বাতিল</button>
                </form>
                <div class="space-y-1.5 max-h-64 overflow-y-auto pr-1">
                    <?php if (empty($all_categories)): ?>
                        <p class="text-xs text-slate-500 text-center py-3">কোনো ক্যাটাগরি নেই — ওপরে নাম লিখে যোগ করুন।</p>
                    <?php else: foreach ($all_categories as $cat): ?>
                        <div class="flex items-center gap-2 bg-slate-900/60 border border-slate-700/60 rounded-lg px-3 py-2 text-xs">
                            <span class="flex-1 text-white"><?= htmlspecialchars($cat['name']) ?></span>
                            <a href="?action=products&cat=<?= (int)$cat['id'] ?>" title="এই ক্যাটাগরির প্রোডাক্ট দেখুন" class="text-sky-400 hover:text-sky-300 px-1"><i class="fa-solid fa-filter"></i></a>
                            <button type="button" onclick="editCategory(<?= (int)$cat['id'] ?>, '<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>')" title="এডিট" class="text-indigo-400 hover:text-indigo-300 px-1"><i class="fa-solid fa-pen"></i></button>
                            <button type="button" onclick="duplicateCategory(<?= (int)$cat['id'] ?>)" title="ডুপ্লিকেট" class="text-amber-400 hover:text-amber-300 px-1"><i class="fa-solid fa-copy"></i></button>
                            <button type="button" onclick="deleteCategoryConfirm(<?= (int)$cat['id'] ?>, '<?= htmlspecialchars($cat['name'], ENT_QUOTES) ?>')" title="ডিলিট" class="text-rose-400 hover:text-rose-300 px-1"><i class="fa-solid fa-trash"></i></button>
                        </div>
                    <?php endforeach; endif; ?>
                </div>
                <form id="catActionForm" action="?action=products" method="POST" class="hidden">
                    <input type="hidden" name="category_id" id="cat-action-id" value="0">
                    <input type="hidden" name="" id="cat-action-type" value="1">
                </form>
            </div>
        </div>

        <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <div class="flex flex-wrap items-center gap-3 mb-6">
                <h3 class="text-lg font-bold text-white" data-i18n="সকল প্রোডাক্টের তালিকা">সকল প্রোডাক্টের তালিকা</h3>
                <div class="ml-auto flex items-center gap-2">
                    <label class="text-xs text-slate-400"><i class="fa-solid fa-filter text-amber-400"></i> ক্যাটাগরি ফিল্টার:</label>
                    <select onchange="location.href = '?action=products' + (this.value !== '0' ? '&cat=' + this.value : '')" class="bg-slate-700 text-white text-xs rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        <option value="0" <?= $cat_filter === 0 ? 'selected' : '' ?>>সব ক্যাটাগরি</option>
                        <option value="-1" <?= $cat_filter === -1 ? 'selected' : '' ?>>ক্যাটাগরি ছাড়া</option>
                        <?php foreach ($all_categories as $cat): ?>
                            <option value="<?= (int)$cat['id'] ?>" <?= $cat_filter === (int)$cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead>
                        <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs">
                            <th class="p-3" data-i18n="ইমেজ">ইমেজ</th>
                            <th class="p-3" data-i18n="টাইটেল">টাইটেল</th>
                            <th class="p-3" data-i18n="মূল্য (৳)">মূল্য (৳)</th>
                            <th class="p-3" data-i18n="ক্যাটাগরি">ক্যাটাগরি</th>
                            <th class="p-3 text-center" data-i18n="স্টক পিস">স্টক পিস</th>
                            <th class="p-3" data-i18n="অটো-লিঙ্ক">অটো-লিঙ্ক</th>
                            <th class="p-3 text-right" data-i18n="অ্যাকশন">অ্যাকশন</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700">
                        <?php foreach ($products as $p): ?>
                            <tr class="text-sm">
                                <td class="p-3">
                                    <img src="<?= htmlspecialchars($p['image_url'] ?: 'https://images.unsplash.com/photo-1541643600914-78b084683601?auto=format&fit=crop&w=100&q=80') ?>" class="w-10 h-10 object-cover rounded-lg">
                                </td>
                                <td class="p-3">
                                    <div class="font-semibold text-white"><?= htmlspecialchars($p['title']) ?></div>
                                    <div class="text-[10px] text-slate-400 font-mono">/<?= htmlspecialchars($p['slug']) ?></div>
                                </td>
                                <td class="p-3">
                                    <span class="text-white font-bold"><?= number_format($p['sale_price'] ?: $p['price']) ?> ৳</span>
                                    <?php if ($p['sale_price']): ?>
                                        <span class="text-xs text-rose-400 line-through block"><?= number_format($p['price']) ?> ৳</span>
                                    <?php endif; ?>
                                </td>
                                <td class="p-3">
                                    <?php if (!empty($p['category_name'])): ?>
                                        <span class="px-2 py-0.5 rounded-full text-[10px] font-bold bg-amber-500/20 text-amber-400"><?= htmlspecialchars($p['category_name']) ?></span>
                                    <?php else: ?>
                                        <span class="text-slate-600 text-[10px]">—</span>
                                    <?php endif; ?>
                                </td>

                                <td class="p-3 text-center">
                                    <span id="stkbadge-<?= (int)$p['id'] ?>" class="px-2.5 py-1 rounded-full text-xs font-bold font-mono <?= $p['stock'] <= 5 ? 'bg-rose-500/20 text-rose-400' : 'bg-emerald-500/20 text-emerald-400' ?>">
                                        <?= number_format($p['stock']) ?> পিস
                                    </span>
                                    <button type="button" onclick="editStock(<?= (int)$p['id'] ?>, <?= (int)$p['stock'] ?>, '<?= htmlspecialchars($p['title'], ENT_QUOTES) ?>')" class="ml-1 text-slate-500 hover:text-amber-400 text-[11px]" title="সঠিক স্টক সেট করুন (অডিট)"><i class="fa-solid fa-pen-to-square"></i></button>
                                </td>

                                <td class="p-3">
                                    <a href="?action=view&slug=<?= urlencode($p['slug']) ?>" target="_blank" class="text-emerald-400 hover:underline text-xs font-semibold flex items-center gap-1">
                                        <i class="fa-solid fa-arrow-up-right-from-square"></i> <span data-i18n="প্রিভিউ লিংক">প্রিভিউ লিংক</span>
                                    </a>
                                </td>
                                <td class="p-3 text-right space-x-1 whitespace-nowrap">
                                    <button onclick='editProduct(<?= json_encode($p, JSON_UNESCAPED_UNICODE | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_TAG) ?>)' class="text-indigo-400 hover:text-indigo-300 text-xs font-semibold" data-i18n="সম্পাদনা">সম্পাদনা</button>
                                    <a href="?action=duplicate_product&id=<?= $p['id'] ?>" class="text-amber-400 hover:text-amber-300 text-xs font-semibold" title="প্রোডাক্ট ডুপ্লিকেট করুন"><i class="fa-solid fa-copy"></i> <span data-i18n="ডুপ্লিকেট">ডুপ্লিকেট</span></a>
                                    <button type="button" onclick="deleteProductConfirm(<?= $p['id'] ?>)" class="text-rose-400 hover:text-rose-300 text-xs font-semibold" data-i18n="মুছে ফেলুন">মুছে ফেলুন</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <form id="deleteProductForm" action="" method="POST" class="hidden">
        <input type="hidden" name="delete_product" value="1">
        <input type="hidden" name="product_id" id="deleteProductId" value="">
    </form>

    <script>
        function deleteProductConfirm(pid) {
            showDoubleConfirm(
                'এই প্রোডাক্টটি মুছে ফেলতে চান?',
                'সর্বশেষ নিশ্চিতকরণ: প্রোডাক্টটি স্থায়ীভাবে মুছে যাবে, আর ফেরত আনা যাবে না। আপনি কি ১০০% নিশ্চিত?',
                () => {
                    document.getElementById('deleteProductId').value = pid;
                    document.getElementById('deleteProductForm').submit();
                }
            );
        }
        function editProduct(p) {
            document.getElementById('form-title').innerText = 'প্রোডাক্ট তথ্য সম্পাদনা';
            document.getElementById('prod-id').value = p.id;
            document.getElementById('prod-title').value = p.title;
            document.getElementById('prod-slug').value = p.slug;
            document.getElementById('prod-category').value = p.category_id || '0';
            document.getElementById('prod-price').value = p.price;
            document.getElementById('prod-sale').value = p.sale_price;
            document.getElementById('prod-cost').value = p.cost_price || '';
            document.getElementById('prod-stock').value = p.stock || 0;
            document.getElementById('prod-image').value = p.image_url;
            document.getElementById('prod-desc').value = p.description;
            const pOg = document.getElementById('prod-og-image');
            pOg.value = p.og_image || '';
            pOg.dispatchEvent(new Event('input'));

            if (p.checkout_fields) {
                try {
                    const fields = JSON.parse(p.checkout_fields);
                    document.getElementById('p-field-name').checked = fields.name;
                    document.getElementById('p-field-phone').checked = fields.phone;
                    document.getElementById('p-field-alt-phone').checked = fields.alt_phone;
                    document.getElementById('p-field-address').checked = fields.address;
                    document.getElementById('p-field-color').checked = fields.color;
                    document.getElementById('p-field-note').checked = fields.note;
                    const pCf = document.getElementById('p-custom-field');
                    pCf.checked = !!fields.custom_field;
                    pCf.dispatchEvent(new Event('change'));
                    document.getElementById('p-custom-field-label').value = fields.custom_field_label || '';
                    document.getElementById('p-courier-charge').checked = !!fields.courier_charge;
                    document.getElementById('p-promo-code').checked = !!fields.promo_code;
                } catch (e) {}
            }

            let variants = {size_teen: false, size_kids: false, weight: false};
            if (p.variant_options) {
                try {
                    const v = JSON.parse(p.variant_options);
                    variants.size_teen = !!v.size_teen;
                    variants.size_kids = !!v.size_kids;
                    variants.weight = !!v.weight;
                } catch (e) {}
            }
            document.getElementById('p-variant-teen').checked = variants.size_teen;
            document.getElementById('p-variant-kids').checked = variants.size_kids;
            document.getElementById('p-variant-weight').checked = variants.weight;
            window.scrollTo({top: 0, behavior: 'smooth'});
        }
        function resetProductForm() {
            const pOgR = document.getElementById('prod-og-image');
            if (pOgR) { pOgR.value = ''; pOgR.dispatchEvent(new Event('input')); }
            const pCfR = document.getElementById('p-custom-field');
            if (pCfR) { pCfR.checked = false; pCfR.dispatchEvent(new Event('change')); document.getElementById('p-custom-field-label').value = ''; }
            const pCcR = document.getElementById('p-courier-charge'); if (pCcR) pCcR.checked = false;
            const pPcR = document.getElementById('p-promo-code'); if (pPcR) pPcR.checked = false;
            document.getElementById('form-title').innerText = 'নতুন প্রোডাক্ট তৈরি করুন';
            document.getElementById('prod-id').value = 0;
            document.getElementById('prod-title').value = '';
            document.getElementById('prod-slug').value = '';
            document.getElementById('prod-category').value = '0';
            document.getElementById('prod-price').value = '';
            document.getElementById('prod-sale').value = '';
            document.getElementById('prod-stock').value = '';
            document.getElementById('prod-image').value = '';
            document.getElementById('prod-desc').value = '';
            document.getElementById('p-field-name').checked = true;
            document.getElementById('p-field-phone').checked = true;
            document.getElementById('p-field-alt-phone').checked = true;
            document.getElementById('p-field-address').checked = true;
            document.getElementById('p-field-color').checked = true;
            document.getElementById('p-field-note').checked = true;
            document.getElementById('p-variant-teen').checked = false;
            document.getElementById('p-variant-kids').checked = false;
            document.getElementById('p-variant-weight').checked = false;
        }

        // ---- ক্যাটাগরি ম্যানেজার ----
        function editCategory(id, name) {
            document.getElementById('cat-edit-id').value = id;
            document.getElementById('cat-edit-name').value = name;
            document.getElementById('cat-save-btn').innerText = 'আপডেট করুন';
            document.getElementById('cat-cancel-btn').classList.remove('hidden');
            document.getElementById('cat-edit-name').focus();
        }
        function resetCategoryForm() {
            document.getElementById('cat-edit-id').value = 0;
            document.getElementById('cat-edit-name').value = '';
            document.getElementById('cat-save-btn').innerText = '+ যোগ করুন';
            document.getElementById('cat-cancel-btn').classList.add('hidden');
        }
        function submitCatAction(id, actionField) {
            document.getElementById('cat-action-id').value = id;
            document.getElementById('cat-action-type').name = actionField;
            document.getElementById('catActionForm').submit();
        }
        function duplicateCategory(id) {
            showConfirmModal('এই ক্যাটাগরিটির একটি কপি তৈরি হবে। এগিয়ে যাবেন?', () => submitCatAction(id, 'duplicate_category'));
        }
        function deleteCategoryConfirm(id, name) {
            showDoubleConfirm(
                '"' + name + '" ক্যাটাগরিটি ডিলিট করতে চান? (এই ক্যাটাগরির প্রোডাক্টগুলো ডিলিট হবে না — শুধু ক্যাটাগরি-মুক্ত হবে)',
                'সত্যিই নিশ্চিত? ক্যাটাগরিটি স্থায়ীভাবে মুছে যাবে!',
                () => submitCatAction(id, 'delete_category')
            );
        }
    </script>
    <?php
}

function render_pages_panel($pages, $all_products_list) {
    $vc_size_teen = json_decode(get_setting('size_teen_options'), true) ?: [];
    $vc_size_kids = json_decode(get_setting('size_kids_options'), true) ?: [];
    $vc_weights   = json_decode(get_setting('weight_options'), true) ?: [];
    $vc_colors    = json_decode(get_setting('product_colors'), true) ?: [];
    ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <h3 class="text-lg font-bold text-white mb-6" id="page-form-title" data-i18n="নতুন ল্যান্ডিং পেজ তৈরি করুন">নতুন ল্যান্ডিং পেজ তৈরি করুন</h3>
            <form action="" method="POST" class="space-y-4">
                <input type="hidden" name="save_page" value="1">
                <input type="hidden" name="page_id" id="page-id" value="0">

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-semibold">পেজ টাইটেল (Title)</label>
                    <input type="text" name="title" id="page-title" required class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                </div>
                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-semibold">কাস্টম স্লাগ (Slug)</label>
                    <input type="text" name="slug" id="page-slug" placeholder="e.g. premium-landing" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                </div>

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-bold text-emerald-400">১ম ধাপ: ১ম HTML কন্টেন্ট (টপ কন্টেন্ট / সেলস কপি)</label>
                    <div class="flex items-center gap-2 mb-2">
                        <button type="button" onclick="openPageBuilder()" class="bg-gradient-to-r from-violet-600 to-fuchsia-600 hover:from-violet-500 hover:to-fuchsia-500 text-white text-xs font-bold px-4 py-2 rounded-lg shadow flex items-center gap-2">
                            <i class="fa-solid fa-wand-magic-sparkles"></i> ড্র্যাগ এন্ড ড্রপ বিল্ডার খুলুন (Elementor স্টাইল)
                        </button>
                        <span class="text-[10px] text-slate-500">বিল্ডারে বানালে HTML নিজে থেকেই নিচের বক্সে চলে আসবে — চাইলে ম্যানুয়ালিও HTML লিখতে পারবেন।</span>
                    </div>
                    <input type="hidden" name="builder_json" id="builder-json-input" value="">
                    <textarea name="content" id="page-content" rows="6" placeholder="এখানে আপনার ল্যান্ডিং পেজের ১ম অংশের (চেকআউট ফর্মের ওপরের) HTML বা এলিমেন্টর স্টাইল কোড দিন..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs"></textarea>
                </div>

                <div class="border border-slate-700 p-3 rounded-lg bg-slate-900/60 space-y-2">
                    <span class="text-xs text-amber-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-solid fa-basket-shopping text-amber-500"></i> ২য় ধাপ: ল্যান্ডিং পেজে প্রদর্শনযোগ্য প্রোডাক্টস
                    </span>
                    <p class="text-[10px] text-slate-400">এই ল্যান্ডিং পেজে কোন পণ্যগুলো বিক্রি করা হবে তা সিলেক্ট করুন (একের অধিক সিলেক্ট করা যাবে)। <i class="fa-solid fa-up-down text-amber-400"></i> আইকন ধরে টেনে ওপর-নিচ করলে ল্যান্ডিং পেজে প্রোডাক্ট সেই ক্রমেই দেখাবে।</p>
                    <div class="max-h-48 overflow-y-auto space-y-1.5 pr-1" id="page-products-container">
                        <?php foreach ($all_products_list as $prod_item): ?>
                            <div class="pg-prod-row flex items-center gap-2 text-xs text-slate-300 hover:text-white bg-slate-800/60 border border-slate-700/60 rounded-lg px-2 py-1.5 select-none" draggable="true" data-pid="<?= $prod_item['id'] ?>">
                                <span class="pg-drag-handle cursor-grab active:cursor-grabbing text-slate-500 hover:text-amber-400 px-1" title="টেনে ওপর-নিচ করুন"><i class="fa-solid fa-grip-vertical"></i></span>
                                <label class="flex items-center gap-2 cursor-pointer flex-1">
                                    <input type="checkbox" name="page_products[]" value="<?= $prod_item['id'] ?>" class="pg-prod-item rounded text-emerald-500">
                                    <span><?= htmlspecialchars($prod_item['title']) ?> (৳<?= number_format($prod_item['sale_price'] ?: $prod_item['price']) ?>)</span>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <label class="flex items-center gap-2 mt-3 pt-3 border-t border-slate-700 cursor-pointer">
                        <input type="checkbox" name="multi_product" id="pg-multi-product" class="rounded text-cyan-500">
                        <span class="text-xs text-cyan-400 font-bold"><i class="fa-solid fa-layer-group"></i> মাল্টি-প্রোডাক্ট অর্ডার চালু করুন</span>
                    </label>
                    <p class="text-[10px] text-slate-400">চালু করলে কাস্টমার এই পেজে <b>একাধিক পণ্য + কোয়ান্টিটি</b> সিলেক্ট করে একসাথে অর্ডার দিতে পারবে। বন্ধ থাকলে আগের মতো একটি পণ্যই অর্ডার হবে।</p>
                </div>

                <div class="border border-slate-700 p-3 rounded-lg bg-slate-900/40 space-y-2">
                    <span class="text-xs text-emerald-400 font-bold block flex items-center gap-1.5">
                        <i class="fa-solid fa-list-check text-emerald-500"></i> ৩য় ধাপ: এই পেজের জন্য নির্দিষ্ট কাস্টম চেকআউট ফিল্ডস:
                    </span>
                    <div class="grid grid-cols-2 gap-2 text-xs">
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_name" id="pg-field-name" checked class="rounded text-emerald-500"> নাম
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_phone" id="pg-field-phone" checked class="rounded text-emerald-500"> মোবাইল
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_alt_phone" id="pg-field-alt-phone" checked class="rounded text-emerald-500"> অল্টারনেটিভ ফোন
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_address" id="pg-field-address" checked class="rounded text-emerald-500"> ঠিকানা
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_color" id="pg-field-color" checked class="rounded text-emerald-500"> কালার সিলেক্টর
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_field_note" id="pg-field-note" checked class="rounded text-emerald-500"> নোট ফিল্ড
                        </label>
                    </div>
                </div>

                <div class="border border-emerald-800/50 p-3 rounded-lg bg-emerald-950/20 space-y-2">
                    <span class="text-xs text-emerald-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-brands fa-whatsapp"></i> এই ল্যান্ডিং পেজে ফ্লোটিং আইকন অ্যাড হবে কি? (ডান পাশে নিচে ফিক্সড ভাসবে)
                    </span>
                    <div class="grid grid-cols-2 gap-2 text-xs">
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_wa_icon" id="pg-wa-icon" checked class="rounded text-emerald-500"> WhatsApp আইকন
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300">
                            <input type="checkbox" name="pg_call_icon" id="pg-call-icon" checked class="rounded text-emerald-500"> ফোন (কল) আইকন
                        </label>
                    </div>
                    <p class="text-[10px] text-slate-500">নাম্বার দুটি <a href="?action=settings" class="text-cyan-400 hover:underline">সেটিংস → ফ্লোটিং আইকন</a> সেকশনে ম্যানুয়ালি সেভ করুন — নাম্বার সেভ না থাকলে আইকন দেখাবে না।</p>
                </div>

                <div class="border border-fuchsia-800/50 p-3 rounded-lg bg-fuchsia-950/20 space-y-2">
                    <span class="text-xs text-fuchsia-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-solid fa-pen-nib"></i> চেকআউটে এক্সট্রা কাস্টম ফিল্ড (আবশ্যক) থাকবে কি?
                    </span>
                    <label class="flex items-center gap-2 text-xs text-slate-300 cursor-pointer">
                        <input type="checkbox" name="pg_custom_field" id="pg-custom-field" onchange="document.getElementById('pg-custom-field-label-wrap').classList.toggle('hidden', !this.checked)" class="rounded text-fuchsia-500"> হ্যাঁ, এই পেজের চেকআউটে এক্সট্রা ফিল্ড থাকবে
                    </label>
                    <div id="pg-custom-field-label-wrap" class="hidden">
                        <label class="block text-[10px] text-slate-400 mb-1">ফিল্ডের প্রশ্ন / লেবেল (কাস্টম লেখা যাবে)</label>
                        <input type="text" name="pg_custom_field_label" id="pg-custom-field-label" placeholder="যেমন: আপনার পছন্দের ডেলিভারি সময় কখন?" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs">
                        <p class="text-[10px] text-slate-500 mt-1">কাস্টমার যা লিখবে তা অর্ডার তালিকা ও অর্ডার ডিটেইলে এই লেবেলসহ দেখা যাবে।</p>
                    </div>
                </div>

                <div class="border border-orange-800/50 p-3 rounded-lg bg-orange-950/20 space-y-2">
                    <span class="text-xs text-orange-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-solid fa-truck-fast"></i> কুরিয়ার চার্জ ও প্রোমো কোড অ্যাড হবে কি?
                    </span>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
                        <label class="flex items-center gap-1.5 text-slate-300 cursor-pointer">
                            <input type="checkbox" name="pg_courier_charge" id="pg-courier-charge" class="rounded text-orange-500"> কুরিয়ার চার্জ অপশন (ঢাকা / সাব ঢাকা / সারা বাংলাদেশ)
                        </label>
                        <label class="flex items-center gap-1.5 text-slate-300 cursor-pointer">
                            <input type="checkbox" name="pg_promo_code" id="pg-promo-code" class="rounded text-orange-500"> প্রোমো কোড অপশন
                        </label>
                    </div>
                    <p class="text-[10px] text-slate-500">চার্জের হার <a href="?action=settings" class="text-cyan-400 hover:underline">সেটিংস → কুরিয়ার চার্জ</a> থেকে আর প্রোমো কোডগুলো <a href="?action=settings" class="text-cyan-400 hover:underline">সেটিংস → প্রোমো কোড ম্যানেজার</a> থেকে সেট করুন।</p>
                </div>

                <div class="border border-sky-800/50 p-3 rounded-lg bg-sky-950/20 space-y-2">
                    <span class="text-xs text-sky-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-solid fa-share-nodes"></i> সোশাল শেয়ার ইমেজ (ফেসবুক/হোয়াটসঅ্যাপে লিংক শেয়ার করলে এই ছবি দেখাবে)
                    </span>
                    <div class="flex gap-2">
                        <input type="text" name="og_image" id="page-og-image" placeholder="খালি রাখলে সেটিংসের ডিফল্ট ইমেজ ব্যবহৃত হবে" oninput="document.getElementById('page-og-preview').src = this.value" class="flex-1 bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs">
                        <button type="button" onclick="openMediaPicker('page-og-image', 'page-og-preview')" class="bg-sky-600 hover:bg-sky-500 text-white text-xs px-3 rounded-lg whitespace-nowrap"><i class="fa-solid fa-images"></i> মিডিয়া থেকে বাছুন</button>
                    </div>
                    <img id="page-og-preview" src="" onerror="this.style.display='none'" onload="this.style.display='block'" class="w-44 aspect-[1200/630] object-cover rounded-lg border border-slate-600 bg-slate-900" style="display:none">
                </div>

                <div class="border border-violet-800/50 p-3 rounded-lg bg-violet-950/20 space-y-3">
                    <span class="text-xs text-violet-400 font-bold tracking-wider block uppercase flex items-center gap-1.5">
                        <i class="fa-solid fa-sliders text-violet-400"></i> ৩.৫ ধাপ: এই ল্যান্ডিং পেজে চেকআউট ভ্যারিয়েন্ট অপশন কী কী থাকবে?
                    </span>
                    <select name="vc_mode" id="vc-mode" onchange="document.getElementById('vc-custom-box').classList.toggle('hidden', this.value !== 'custom')" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-xs">
                        <option value="default">প্রোডাক্ট অনুযায়ী (ডিফল্ট — প্রতিটি প্রোডাক্টের নিজস্ব ভ্যারিয়েন্ট সেটিং অনুসরণ করবে)</option>
                        <option value="custom">এই পেজের জন্য কাস্টম — নিচ থেকে নিজে বেছে দিন</option>
                    </select>

                    <div id="vc-custom-box" class="hidden space-y-3">
                        <!-- Teen/Adult সাইজ -->
                        <div class="border border-slate-700 rounded-lg p-2.5 bg-slate-900/50">
                            <label class="flex items-center gap-2 text-xs text-white font-bold cursor-pointer">
                                <input type="checkbox" name="vc_size_teen" id="vc-size-teen" onchange="document.getElementById('vc-teen-opts').classList.toggle('hidden', !this.checked)" class="rounded text-violet-500">
                                Teen/Adult সাইজ (XXS – 8XL)
                            </label>
                            <div id="vc-teen-opts" class="hidden flex flex-wrap gap-1.5 mt-2">
                                <?php foreach ($vc_size_teen as $sz): ?>
                                <label class="flex items-center gap-1 text-[11px] text-slate-300 bg-slate-800 border border-slate-700 rounded px-2 py-1 cursor-pointer hover:border-violet-500">
                                    <input type="checkbox" name="vc_size_teen_opts[]" value="<?= htmlspecialchars($sz) ?>" class="vc-teen-opt rounded text-violet-500" checked> <?= htmlspecialchars($sz) ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <!-- Baby/Kids সাইজ -->
                        <div class="border border-slate-700 rounded-lg p-2.5 bg-slate-900/50">
                            <label class="flex items-center gap-2 text-xs text-white font-bold cursor-pointer">
                                <input type="checkbox" name="vc_size_kids" id="vc-size-kids" onchange="document.getElementById('vc-kids-opts').classList.toggle('hidden', !this.checked)" class="rounded text-violet-500">
                                Baby/Kids সাইজ (0-6 Months – 12-14 years)
                            </label>
                            <div id="vc-kids-opts" class="hidden flex flex-wrap gap-1.5 mt-2">
                                <?php foreach ($vc_size_kids as $sz): ?>
                                <label class="flex items-center gap-1 text-[11px] text-slate-300 bg-slate-800 border border-slate-700 rounded px-2 py-1 cursor-pointer hover:border-violet-500">
                                    <input type="checkbox" name="vc_size_kids_opts[]" value="<?= htmlspecialchars($sz) ?>" class="vc-kids-opt rounded text-violet-500" checked> <?= htmlspecialchars($sz) ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <!-- ওজন -->
                        <div class="border border-slate-700 rounded-lg p-2.5 bg-slate-900/50">
                            <label class="flex items-center gap-2 text-xs text-white font-bold cursor-pointer">
                                <input type="checkbox" name="vc_weight" id="vc-weight" onchange="document.getElementById('vc-weight-opts').classList.toggle('hidden', !this.checked)" class="rounded text-violet-500">
                                ওজন অপশন (200g – 20kg + Custom)
                            </label>
                            <div id="vc-weight-opts" class="hidden mt-2 space-y-2">
                                <div class="flex flex-wrap gap-1.5">
                                    <?php foreach ($vc_weights as $w): ?>
                                    <label class="flex items-center gap-1 text-[11px] text-slate-300 bg-slate-800 border border-slate-700 rounded px-2 py-1 cursor-pointer hover:border-violet-500">
                                        <input type="checkbox" name="vc_weight_opts[]" value="<?= htmlspecialchars($w) ?>" class="vc-weight-opt rounded text-violet-500" checked> <?= htmlspecialchars($w) ?>
                                    </label>
                                    <?php endforeach; ?>
                                </div>
                                <label class="flex items-center gap-1.5 text-[11px] text-amber-300 cursor-pointer">
                                    <input type="checkbox" name="vc_weight_custom" id="vc-weight-custom" checked class="rounded text-amber-500"> Custom (kg) অপশন থাকবে — কাস্টমার নিজে ওজন লিখতে পারবে
                                </label>
                            </div>
                        </div>
                        <!-- কালার -->
                        <div class="border border-slate-700 rounded-lg p-2.5 bg-slate-900/50">
                            <label class="flex items-center gap-2 text-xs text-white font-bold cursor-pointer">
                                <input type="checkbox" name="vc_colors" id="vc-colors" onchange="document.getElementById('vc-color-opts').classList.toggle('hidden', !this.checked)" class="rounded text-violet-500">
                                কালার সিলেক্টর — <?= count($vc_colors) ?>টার মধ্যে যেকয়টা ইচ্ছা বেছে দিন (২টা, ৩টা, ৫টা...)
                            </label>
                            <div id="vc-color-opts" class="hidden flex flex-wrap gap-1.5 mt-2">
                                <?php foreach ($vc_colors as $c): ?>
                                <label class="flex items-center gap-1.5 text-[11px] text-slate-300 bg-slate-800 border border-slate-700 rounded px-2 py-1 cursor-pointer hover:border-violet-500">
                                    <input type="checkbox" name="vc_color_opts[]" value="<?= htmlspecialchars($c['en']) ?>" class="vc-color-opt rounded text-violet-500">
                                    <span class="inline-block w-3 h-3 rounded-full border border-slate-600" style="background: <?= htmlspecialchars(color_hex($c['en'])) ?>;"></span>
                                    <?= htmlspecialchars($c['bn'] ?: $c['en']) ?>
                                </label>
                                <?php endforeach; ?>
                            </div>
                            <p class="text-[10px] text-slate-500 mt-1.5">টিক দেওয়া কালারগুলোই শুধু এই ল্যান্ডিং পেজের চেকআউটে দেখাবে। কালার বন্ধ রাখতে চাইলে ওপরের "কালার সিলেক্টর" আনটিক রাখুন।</p>
                        </div>
                    </div>
                </div>

                <div>
                    <label class="block text-slate-300 text-sm mb-1 font-bold text-emerald-400">৪র্থ ধাপ: ৪র্থ HTML কন্টেন্ট (বটম কন্টেন্ট / এফএকিউ / রিভিউসমূহ)</label>
                    <textarea name="bottom_content" id="page-bottom-content" rows="6" placeholder="এখানে আপনার ল্যান্ডিং পেজের ৪র্থ অংশের (চেকআউট ফর্মের নিচের) HTML বা স্টাইল কোড দিন..." class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-xs"></textarea>
                </div>

                <div class="border border-slate-700 p-3 rounded-lg bg-slate-900/60 space-y-3">
                    <span class="text-xs text-amber-400 font-bold tracking-wider block uppercase"><i class="fa-solid fa-chart-line text-amber-500"></i> RankMath SEO Pro প্যানেল</span>
                    <div>
                        <label class="block text-slate-400 text-xs mb-1">SEO Title Tag</label>
                        <input type="text" name="seo_title" id="page-seo-title" placeholder="Google Search-এ প্রদর্শিত টাইটেল" class="w-full bg-slate-700 text-white rounded px-2.5 py-1.5 text-xs outline-none border border-slate-600">
                    </div>
                    <div>
                        <label class="block text-slate-400 text-xs mb-1">SEO Description</label>
                        <textarea name="seo_desc" id="page-seo-desc" rows="2" placeholder="সার্চ রেজাল্ট স্নিপেট ডেসক্রিপশন..." class="w-full bg-slate-700 text-white rounded px-2.5 py-1.5 text-xs outline-none border border-slate-600"></textarea>
                    </div>
                </div>

                <div class="flex gap-3">
                    <button type="submit" class="bg-emerald-600 hover:bg-emerald-500 text-white px-4 py-2 rounded-lg font-semibold transition w-full" data-i18n="সেভ পেজ">সেভ পেজ</button>
                    <button type="button" onclick="resetPageForm()" class="bg-slate-700 hover:bg-slate-600 text-white px-4 py-2 rounded-lg text-xs" data-i18n="রিসেট">রিসেট</button>
                </div>
            </form>
        </div>

        <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border border-slate-700">
            <h3 class="text-lg font-bold text-white mb-6" data-i18n="সকল লাইভ পেজ ও ল্যান্ডিং সোর্স">সকল লাইভ পেজ ও ল্যান্ডিং সোর্স</h3>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead>
                        <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs">
                            <th class="p-3" data-i18n="পেজ টাইটেল">পেজ টাইটেল</th>
                            <th class="p-3" data-i18n="স্লাগ">স্লাগ</th>
                            <th class="p-3" data-i18n="অটো লিংক">অটো লিংক</th>
                            <th class="p-3 text-right" data-i18n="পদক্ষেপ">পদক্ষেপ</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-700">
                        <?php foreach ($pages as $pg): ?>
                            <tr class="text-sm">
                                <td class="p-3 text-white font-semibold"><?= htmlspecialchars($pg['title']) ?></td>
                                <td class="p-3 font-mono text-xs text-indigo-400">/<?= htmlspecialchars($pg['slug']) ?></td>
                                <td class="p-3">
                                    <a href="?action=view&slug=<?= urlencode($pg['slug']) ?>" target="_blank" class="text-emerald-400 hover:underline text-xs flex items-center gap-1">
                                        <i class="fa-solid fa-arrow-up-right-from-square"></i> <span data-i18n="ভিজিট ল্যান্ডিং পেজ">ভিজিট ল্যান্ডিং পেজ</span>
                                    </a>
                                </td>
                                <td class="p-3 text-right space-x-1 whitespace-nowrap">
                                    <button onclick='editPage(<?= json_encode($pg, JSON_UNESCAPED_UNICODE | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_TAG) ?>)' class="text-indigo-400 hover:text-indigo-300 text-xs font-semibold" data-i18n="সম্পাদনা">সম্পাদনা</button>
                                    <a href="?action=duplicate_page&id=<?= $pg['id'] ?>" class="text-amber-400 hover:text-amber-300 text-xs font-semibold" title="পেজ ডুপ্লিকেট করুন"><i class="fa-solid fa-copy"></i> <span data-i18n="ডুপ্লিকেট">ডুপ্লিকেট</span></a>
                                    <button type="button" onclick="deletePageConfirm(<?= $pg['id'] ?>)" class="text-rose-400 hover:text-rose-300 text-xs font-semibold" data-i18n="মুছে ফেলুন">মুছে ফেলুন</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <form id="deletePageForm" action="" method="POST" class="hidden">
        <input type="hidden" name="delete_page" value="1">
        <input type="hidden" name="page_id" id="deletePageId" value="">
    </form>

    <script>
        function deletePageConfirm(pgid) {
            showDoubleConfirm(
                'এই পেজটি ডিলিট করতে চান?',
                'সর্বশেষ নিশ্চিতকরণ: পেজটি স্থায়ীভাবে মুছে যাবে, আর ফেরত আনা যাবে না। আপনি কি ১০০% নিশ্চিত?',
                () => {
                    document.getElementById('deletePageId').value = pgid;
                    document.getElementById('deletePageForm').submit();
                }
            );
        }
        function editPage(pg) {
            document.getElementById('page-form-title').innerText = 'ল্যান্ডিং পেজ সম্পাদনা';
            document.getElementById('page-id').value = pg.id;
            document.getElementById('page-title').value = pg.title;
            document.getElementById('page-slug').value = pg.slug;
            document.getElementById('page-content').value = pg.content || '';
            document.getElementById('page-bottom-content').value = pg.bottom_content || '';
            document.getElementById('page-seo-title').value = pg.seo_title || '';
            document.getElementById('page-seo-desc').value = pg.seo_desc || '';

            let prodIds = [];
            if (pg.product_ids) {
                try {
                    prodIds = JSON.parse(pg.product_ids);
                    if (!Array.isArray(prodIds)) {
                        prodIds = [];
                    }
                } catch (e) {
                    prodIds = [];
                }
            }
            const prodCheckboxes = document.querySelectorAll('.pg-prod-item');
            prodCheckboxes.forEach(cb => {
                cb.checked = prodIds.includes(parseInt(cb.value)) || prodIds.includes(cb.value.toString());
            });
            reorderPgProductRows(prodIds.map(x => parseInt(x)));
            document.getElementById('pg-multi-product').checked = (parseInt(pg.multi_product) === 1);
            applyVcConfig(pg.variant_config || null);
            const pgOg = document.getElementById('page-og-image');
            pgOg.value = pg.og_image || '';
            pgOg.dispatchEvent(new Event('input'));
            document.getElementById('builder-json-input').value = pg.builder_json || '';

            if (pg.checkout_fields) {
                try {
                    const fields = JSON.parse(pg.checkout_fields);
                    document.getElementById('pg-field-name').checked = fields.name !== undefined ? fields.name : true;
                    document.getElementById('pg-field-phone').checked = fields.phone !== undefined ? fields.phone : true;
                    document.getElementById('pg-field-alt-phone').checked = fields.alt_phone !== undefined ? fields.alt_phone : true;
                    document.getElementById('pg-field-address').checked = fields.address !== undefined ? fields.address : true;
                    document.getElementById('pg-field-color').checked = fields.color !== undefined ? fields.color : true;
                    document.getElementById('pg-field-note').checked = fields.note !== undefined ? fields.note : true;
                    document.getElementById('pg-wa-icon').checked = fields.wa_icon !== undefined ? fields.wa_icon : true;
                    document.getElementById('pg-call-icon').checked = fields.call_icon !== undefined ? fields.call_icon : true;
                    const pgCf = document.getElementById('pg-custom-field');
                    pgCf.checked = !!fields.custom_field;
                    pgCf.dispatchEvent(new Event('change'));
                    document.getElementById('pg-custom-field-label').value = fields.custom_field_label || '';
                    document.getElementById('pg-courier-charge').checked = !!fields.courier_charge;
                    document.getElementById('pg-promo-code').checked = !!fields.promo_code;
                } catch (e) {
                    setPgFieldsDefault();
                }
            } else {
                setPgFieldsDefault();
            }
            window.scrollTo({top: 0, behavior: 'smooth'});
        }

        // ---- প্রোডাক্ট ড্র্যাগ এন্ড ড্রপ রিঅর্ডারিং ----
        (function initPgProductDrag() {
            const container = document.getElementById('page-products-container');
            if (!container) return;
            let dragging = null;
            container.querySelectorAll('.pg-prod-row').forEach(row => {
                row.addEventListener('dragstart', (e) => {
                    dragging = row;
                    row.classList.add('opacity-40');
                    e.dataTransfer.effectAllowed = 'move';
                });
                row.addEventListener('dragend', () => {
                    if (dragging) dragging.classList.remove('opacity-40');
                    dragging = null;
                });
            });
            container.addEventListener('dragover', (e) => {
                e.preventDefault();
                if (!dragging) return;
                const after = Array.from(container.querySelectorAll('.pg-prod-row:not(.opacity-40)')).find(row => {
                    const rect = row.getBoundingClientRect();
                    return e.clientY < rect.top + rect.height / 2;
                });
                if (after) container.insertBefore(dragging, after);
                else container.appendChild(dragging);
            });
        })();

        function reorderPgProductRows(orderedIds) {
            // সেভ করা ক্রম অনুযায়ী রোগুলো সাজানো (সিলেক্টেডগুলো ওপরে, সেই ক্রমে)
            const container = document.getElementById('page-products-container');
            if (!container || !orderedIds || !orderedIds.length) return;
            orderedIds.slice().reverse().forEach(pid => {
                const row = container.querySelector('.pg-prod-row[data-pid="' + pid + '"]');
                if (row) container.insertBefore(row, container.firstChild);
            });
        }

        function setVcDefaults() {
            document.getElementById('vc-mode').value = 'default';
            document.getElementById('vc-custom-box').classList.add('hidden');
            ['vc-size-teen', 'vc-size-kids', 'vc-weight', 'vc-colors'].forEach(id => {
                const el = document.getElementById(id);
                el.checked = false;
                el.dispatchEvent(new Event('change'));
            });
            document.querySelectorAll('.vc-teen-opt, .vc-kids-opt, .vc-weight-opt').forEach(cb => cb.checked = true);
            document.querySelectorAll('.vc-color-opt').forEach(cb => cb.checked = false);
            document.getElementById('vc-weight-custom').checked = true;
        }

        function applyVcConfig(vcJson) {
            setVcDefaults();
            if (!vcJson) return;
            let vc;
            try { vc = JSON.parse(vcJson); } catch (e) { return; }
            if (!vc || typeof vc !== 'object') return;
            document.getElementById('vc-mode').value = 'custom';
            document.getElementById('vc-custom-box').classList.remove('hidden');
            const groups = [
                ['size_teen', 'vc-size-teen', '.vc-teen-opt'],
                ['size_kids', 'vc-size-kids', '.vc-kids-opt'],
                ['weight', 'vc-weight', '.vc-weight-opt'],
                ['colors', 'vc-colors', '.vc-color-opt']
            ];
            groups.forEach(([key, masterId, optSel]) => {
                const g = vc[key] || {};
                const master = document.getElementById(masterId);
                master.checked = !!g.enabled;
                master.dispatchEvent(new Event('change'));
                const opts = Array.isArray(g.options) ? g.options : [];
                document.querySelectorAll(optSel).forEach(cb => {
                    cb.checked = g.enabled ? opts.includes(cb.value) : (optSel === '.vc-color-opt' ? false : true);
                });
            });
            document.getElementById('vc-weight-custom').checked = !(vc.weight && vc.weight.custom === false);
        }

        function setPgFieldsDefault() {
            document.getElementById('pg-wa-icon').checked = true;
            document.getElementById('pg-call-icon').checked = true;
            const pgCfD = document.getElementById('pg-custom-field');
            pgCfD.checked = false;
            pgCfD.dispatchEvent(new Event('change'));
            document.getElementById('pg-custom-field-label').value = '';
            document.getElementById('pg-courier-charge').checked = false;
            document.getElementById('pg-promo-code').checked = false;
            document.getElementById('pg-field-name').checked = true;
            document.getElementById('pg-field-phone').checked = true;
            document.getElementById('pg-field-alt-phone').checked = true;
            document.getElementById('pg-field-address').checked = true;
            document.getElementById('pg-field-color').checked = true;
            document.getElementById('pg-field-note').checked = true;
        }

        function resetPageForm() {
            document.getElementById('page-form-title').innerText = 'নতুন ল্যান্ডিং পেজ তৈরি করুন';
            document.getElementById('page-id').value = 0;
            document.getElementById('page-title').value = '';
            document.getElementById('page-slug').value = '';
            document.getElementById('page-content').value = '';
            document.getElementById('page-bottom-content').value = '';
            document.getElementById('page-seo-title').value = '';
            document.getElementById('page-seo-desc').value = '';

            const prodCheckboxes = document.querySelectorAll('.pg-prod-item');
            prodCheckboxes.forEach(cb => cb.checked = false);
            var pgm = document.getElementById('pg-multi-product'); if (pgm) pgm.checked = false;

            setPgFieldsDefault();
            setVcDefaults();
            const pgOgR = document.getElementById('page-og-image');
            pgOgR.value = '';
            pgOgR.dispatchEvent(new Event('input'));
            document.getElementById('builder-json-input').value = '';
        }
    </script>
    <?php render_page_builder_modal(); render_page_builder_js(); ?>
    <?php
}

function render_media_panel() {
    // সার্ভারের আসল আপলোড লিমিট বের করা (cPanel-এ অনেক সময় মাত্র 2M থাকে)
    $to_bytes = function ($v) {
        $v = trim($v); $n = (float)$v; $u = strtoupper(substr($v, -1));
        if ($u === 'G') return $n * 1073741824; if ($u === 'M') return $n * 1048576; if ($u === 'K') return $n * 1024; return $n;
    };
    $srv_limit_bytes = min($to_bytes(ini_get('upload_max_filesize') ?: '2M'), $to_bytes(ini_get('post_max_size') ?: '8M'), 10 * 1048576);
    $srv_limit_mb = round($srv_limit_bytes / 1048576, 1);
    ?>
    <div class="space-y-6 font-semibold">
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                <i class="fa-solid fa-images text-sky-400"></i> <span data-i18n="মিডিয়া ফাইল ম্যানেজার">মিডিয়া ফাইল ম্যানেজার</span>
            </h3>
            <div class="flex flex-col md:flex-row gap-4 items-start md:items-center">
                <label class="flex-1 w-full border-2 border-dashed border-slate-600 hover:border-sky-500 rounded-2xl p-6 text-center cursor-pointer transition bg-slate-900/40 block">
                    <input type="file" id="mediaFileInput" accept="image/*" class="hidden" multiple>
                    <i class="fa-solid fa-cloud-arrow-up text-3xl text-sky-400 mb-2 block"></i>
                    <span class="text-sm text-slate-300 block" data-i18n="ছবি আপলোড করতে এখানে ক্লিক করুন">ছবি আপলোড করতে এখানে ক্লিক করুন</span>
                    <span class="text-[10px] text-slate-500 block mt-1">JPG, PNG, GIF, WEBP — সর্বোচ্চ <?= $srv_limit_mb ?>MB (আপনার সার্ভারের লিমিট)</span>
                    <?php if ($srv_limit_mb < 5): ?>
                    <span class="text-[10px] text-amber-400 block mt-1">⚠️ সার্ভারের আপলোড লিমিট মাত্র <?= $srv_limit_mb ?>MB! বড় ছবি আপলোড করতে cPanel → <b>MultiPHP INI Editor</b> → upload_max_filesize = <b>20M</b> ও post_max_size = <b>25M</b> সেট করুন।</span>
                    <?php endif; ?>
                </label>
                <div id="mediaUploadStatus" class="text-xs text-slate-400"></div>
            </div>
        </div>

        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <div class="flex items-center justify-between mb-4">
                <h4 class="text-sm font-bold text-white" data-i18n="আপলোড করা ছবিসমূহ">আপলোড করা ছবিসমূহ</h4>
                <span id="mediaTotalCount" class="text-xs text-slate-400"></span>
            </div>
            <div id="mediaGrid" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4"></div>
            <div class="text-center mt-6">
                <button id="mediaLoadMoreBtn" onclick="loadMediaFiles(false)" class="hidden bg-sky-600 hover:bg-sky-500 text-white text-xs px-6 py-2.5 rounded-xl font-bold transition">
                    <i class="fa-solid fa-arrow-down"></i> <span data-i18n="লোড মোর">লোড মোর</span>
                </button>
                <p id="mediaEmptyMsg" class="hidden text-xs text-slate-400 py-6">কোনো ছবি আপলোড করা হয়নি।</p>
            </div>
        </div>
    </div>

    <!-- Crop Modal -->
    <div id="cropModal" class="hidden fixed inset-0 z-[160] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm">
        <div class="bg-slate-800 border border-slate-700 rounded-3xl max-w-2xl w-full p-6 text-slate-100 shadow-2xl relative">
            <button onclick="closeCropModal()" class="absolute top-4 right-4 text-slate-400 hover:text-white text-2xl font-bold border border-slate-600 rounded-full w-8 h-8 flex items-center justify-center transition">&times;</button>
            <h3 class="text-base font-bold text-white mb-4 flex items-center gap-2">
                <i class="fa-solid fa-crop-simple text-sky-400"></i> ছবি ক্রপ করুন
            </h3>
            <div class="max-h-[50vh] overflow-hidden bg-slate-950 rounded-xl mb-4">
                <img id="cropImage" src="" style="max-width:100%; display:block;">
            </div>
            <div class="flex flex-wrap gap-2 mb-4">
                <button onclick="setCropRatio(1)" class="crop-ratio-btn bg-slate-700 hover:bg-sky-600 text-white text-xs px-4 py-2 rounded-lg font-bold transition">1:1</button>
                <button onclick="setCropRatio(3/4)" class="crop-ratio-btn bg-slate-700 hover:bg-sky-600 text-white text-xs px-4 py-2 rounded-lg font-bold transition">3:4</button>
                <button onclick="setCropRatio(9/16)" class="crop-ratio-btn bg-slate-700 hover:bg-sky-600 text-white text-xs px-4 py-2 rounded-lg font-bold transition">9:16</button>
                <button onclick="setCropRatio(16/9)" class="crop-ratio-btn bg-slate-700 hover:bg-sky-600 text-white text-xs px-4 py-2 rounded-lg font-bold transition">16:9</button>
                <button onclick="setCropRatio(NaN)" class="crop-ratio-btn bg-slate-700 hover:bg-sky-600 text-white text-xs px-4 py-2 rounded-lg font-bold transition">ফ্রি</button>
            </div>
            <button onclick="saveCroppedImage()" id="cropSaveBtn" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-sm py-3 rounded-xl transition shadow-lg flex items-center justify-center gap-2">
                <i class="fa-solid fa-floppy-disk"></i> ক্রপ করা ছবি সেভ করুন (নতুন কপি হবে)
            </button>
        </div>
    </div>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>

    <script>
        let mediaOffset = 0;
        const mediaLimit = 20;
        let cropper = null;

        function loadMediaFiles(reset) {
            if (reset) {
                mediaOffset = 0;
                document.getElementById('mediaGrid').innerHTML = '';
            }
            fetch('?action=media_list&offset=' + mediaOffset)
                .then(r => r.json())
                .then(d => {
                    const grid = document.getElementById('mediaGrid');
                    const emptyMsg = document.getElementById('mediaEmptyMsg');
                    const loadBtn = document.getElementById('mediaLoadMoreBtn');
                    const countEl = document.getElementById('mediaTotalCount');

                    if (d.status !== 'success') {
                        showToast(d.message || 'মিডিয়া লোড করতে সমস্যা হয়েছে', 'error');
                        return;
                    }
                    countEl.innerText = 'মোট ' + d.total + ' টি ছবি';

                    if (d.files.length === 0 && mediaOffset === 0) {
                        emptyMsg.classList.remove('hidden');
                        loadBtn.classList.add('hidden');
                        return;
                    }
                    emptyMsg.classList.add('hidden');

                    d.files.forEach(f => {
                        const card = document.createElement('div');
                        card.className = 'bg-slate-900 border border-slate-700 rounded-2xl overflow-hidden group relative';
                        card.id = 'media-card-' + f.id;
                        card.innerHTML = `
                            <div class="aspect-square bg-slate-950 overflow-hidden flex items-center justify-center">
                                <img src="${f.rel_url}" loading="lazy" onerror="this.onerror=null; this.src='${f.file_url}';" class="w-full h-full object-cover group-hover:scale-105 transition duration-300">
                            </div>
                            <div class="p-2 space-y-1.5">
                                <p class="text-[10px] text-slate-400 font-mono truncate" title="${f.file_name}">${f.file_name}</p>
                                <div class="flex items-center justify-between gap-1">
                                    <button onclick="copyText('${f.file_url}')" title="লিংক কপি করুন" class="flex-1 bg-slate-700 hover:bg-emerald-600 text-white text-[10px] py-1.5 rounded-lg transition"><i class="fa-solid fa-link"></i></button>
                                    <button onclick="openCropModal(${f.id}, '${f.file_url}')" title="ক্রপ করুন" class="flex-1 bg-slate-700 hover:bg-sky-600 text-white text-[10px] py-1.5 rounded-lg transition"><i class="fa-solid fa-crop-simple"></i></button>
                                    <button onclick="deleteMediaFile(${f.id})" title="পারমানেন্ট ডিলিট" class="flex-1 bg-slate-700 hover:bg-rose-600 text-white text-[10px] py-1.5 rounded-lg transition"><i class="fa-solid fa-trash"></i></button>
                                </div>
                            </div>
                        `;
                        grid.appendChild(card);
                    });

                    mediaOffset += d.files.length;
                    if (mediaOffset < d.total) {
                        loadBtn.classList.remove('hidden');
                    } else {
                        loadBtn.classList.add('hidden');
                    }
                })
                .catch(() => showToast('নেটওয়ার্ক ত্রুটি! মিডিয়া লোড হয়নি।', 'error'));
        }

        const SRV_UPLOAD_LIMIT = <?= (int)$srv_limit_bytes ?>;
        document.getElementById('mediaFileInput').addEventListener('change', function() {
            const files = Array.from(this.files);
            if (files.length === 0) return;
            const statusEl = document.getElementById('mediaUploadStatus');
            let done = 0, okCount = 0;
            statusEl.innerText = 'আপলোড হচ্ছে... (0/' + files.length + ')';
            files.forEach(file => {
                if (file.size > SRV_UPLOAD_LIMIT) {
                    done++;
                    showToast(file.name + ' — ফাইলটি সার্ভার লিমিটের (' + (SRV_UPLOAD_LIMIT / 1048576).toFixed(1) + 'MB) চেয়ে বড়!', 'error');
                    if (done === files.length) { statusEl.innerText = ''; loadMediaFiles(true); }
                    return;
                }
                const fd = new FormData();
                fd.append('media_file', file);
                fetch('?action=media_upload', { method: 'POST', body: fd })
                    .then(r => r.text().then(t => { try { return JSON.parse(t); } catch (e) { return { status: 'error', message: 'সার্ভার এরর (HTTP ' + r.status + ') — ' + file.name }; } }))
                    .then(d => {
                        done++;
                        statusEl.innerText = 'আপলোড হচ্ছে... (' + done + '/' + files.length + ')';
                        if (d.status !== 'success') {
                            showToast(d.message || 'আপলোড ব্যর্থ: ' + file.name, 'error');
                        } else { okCount++; }
                        if (done === files.length) {
                            statusEl.innerText = '';
                            if (okCount > 0) showToast(okCount + 'টি ছবি সফলভাবে আপলোড হয়েছে!', 'success');
                            loadMediaFiles(true);
                        }
                    })
                    .catch(() => {
                        done++;
                        showToast('নেটওয়ার্ক ত্রুটি — আপলোড ব্যর্থ: ' + file.name, 'error');
                        if (done === files.length) { statusEl.innerText = ''; loadMediaFiles(true); }
                    });
            });
            this.value = '';
        });

        function openCropModal(id, url) {
            const modal = document.getElementById('cropModal');
            const img = document.getElementById('cropImage');
            modal.classList.remove('hidden');
            if (cropper) { cropper.destroy(); cropper = null; }
            img.src = url + (url.includes('?') ? '&' : '?') + 'cb=' + Date.now();
            img.onload = function() {
                cropper = new Cropper(img, { aspectRatio: 1, viewMode: 1, autoCropArea: 0.9 });
            };
        }
        function setCropRatio(ratio) {
            if (cropper) cropper.setAspectRatio(ratio);
        }
        function closeCropModal() {
            document.getElementById('cropModal').classList.add('hidden');
            if (cropper) { cropper.destroy(); cropper = null; }
        }
        function saveCroppedImage() {
            if (!cropper) return;
            const btn = document.getElementById('cropSaveBtn');
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-spinner animate-spin"></i> সেভ হচ্ছে...';
            cropper.getCroppedCanvas({ maxWidth: 2500, maxHeight: 2500 }).toBlob(function(blob) {
                const fd = new FormData();
                fd.append('media_file', blob, 'crop_' + Date.now() + '.png');
                fd.append('cropped', '1');
                fetch('?action=media_upload', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(d => {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> ক্রপ করা ছবি সেভ করুন (নতুন কপি হবে)';
                        if (d.status === 'success') {
                            showToast('ক্রপ করা ছবি সেভ হয়েছে!', 'success');
                            closeCropModal();
                            loadMediaFiles(true);
                        } else {
                            showToast(d.message || 'সেভ ব্যর্থ হয়েছে', 'error');
                        }
                    })
                    .catch(() => {
                        btn.disabled = false;
                        btn.innerHTML = '<i class="fa-solid fa-floppy-disk"></i> ক্রপ করা ছবি সেভ করুন (নতুন কপি হবে)';
                        showToast('নেটওয়ার্ক ত্রুটি!', 'error');
                    });
            }, 'image/png');
        }
        function deleteMediaFile(id) {
            showDoubleConfirm(
                'এই ছবিটি পারমানেন্ট ডিলিট করতে চান?',
                'সর্বশেষ নিশ্চিতকরণ: ছবিটি সার্ভার থেকে স্থায়ীভাবে মুছে যাবে এবং এই লিংক ব্যবহার করা সব জায়গায় ছবি ভেঙে যাবে। ১০০% নিশ্চিত?',
                () => {
                    fetch('?action=media_delete&id=' + id)
                        .then(r => r.json())
                        .then(d => {
                            if (d.status === 'success') {
                                const card = document.getElementById('media-card-' + id);
                                if (card) card.remove();
                                showToast('ছবি স্থায়ীভাবে ডিলিট হয়েছে!', 'success');
                            } else {
                                showToast(d.message || 'ডিলিট ব্যর্থ হয়েছে', 'error');
                            }
                        })
                        .catch(() => showToast('নেটওয়ার্ক ত্রুটি!', 'error'));
                }
            );
        }

        loadMediaFiles(true);
    </script>
    <?php
}

function render_fraud_detection_panel($blocked_list, $fd_msg) {
    ?>
    <div class="space-y-6 font-semibold">
        <?php if ($fd_msg):
            $fdm_text = is_array($fd_msg) ? ($fd_msg['text'] ?? '') : $fd_msg;
            $fdm_err = is_array($fd_msg) && ($fd_msg['type'] ?? '') === 'error';
        ?>
            <div class="<?= $fdm_err ? 'bg-rose-500/10 border-rose-500 text-rose-400' : 'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= htmlspecialchars($fdm_text) ?></div>
        <?php endif; ?>

        <!-- ফ্রড রিস্ক থ্রেশহোল্ড + এডভান্স পেমেন্ট সেটিংস -->
        <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
            <h3 class="text-lg font-bold text-white mb-1 flex items-center gap-2 border-b border-slate-700 pb-3">
                <i class="fa-solid fa-gauge-high text-amber-400"></i> ফ্রড রিস্ক লিমিট ও এডভান্স পেমেন্ট
            </h3>
            <p class="text-xs text-slate-400 my-3">রিস্ক এই পারসেন্টের সমান বা বেশি হলে কাস্টমার সরাসরি অর্ডার করতে পারবে না — তাকে এডভান্স টাকা বিকাশ/নগদ করে ট্রানজেকশন আইডি বা স্ক্রিনশট দিয়ে অর্ডার কনফার্ম করতে হবে। <b class="text-amber-400">০ দিলে এই সিস্টেম বন্ধ থাকবে।</b></p>
            <form action="?action=fraud_detection" method="POST" class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                <input type="hidden" name="save_fraud_settings" value="1">
                <div>
                    <label class="block text-slate-300 text-xs mb-1">রিস্ক লিমিট (%) — এর বেশি হলে ব্লক</label>
                    <input type="number" name="fraud_block_threshold" min="0" max="100" value="<?= htmlspecialchars(get_setting('fraud_block_threshold') ?: '0') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">এডভান্স এমাউন্ট (৳)</label>
                    <input type="number" name="advance_amount" min="1" value="<?= htmlspecialchars(get_setting('advance_amount') ?: '150') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">বিকাশ নাম্বার (পার্সোনাল)</label>
                    <input type="text" name="advance_bkash" placeholder="01XXXXXXXXX" value="<?= htmlspecialchars(get_setting('advance_bkash')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">নগদ নাম্বার (পার্সোনাল)</label>
                    <input type="text" name="advance_nagad" placeholder="01XXXXXXXXX" value="<?= htmlspecialchars(get_setting('advance_nagad')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1"><i class="fa-brands fa-whatsapp text-emerald-400"></i> সাপোর্ট WhatsApp নাম্বার</label>
                    <input type="text" name="support_whatsapp" placeholder="01XXXXXXXXX" value="<?= htmlspecialchars(get_setting('support_whatsapp')) ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    <p class="text-[10px] text-slate-500 mt-1">অর্ডার সাকসেস স্ক্রিনে "WhatsApp-এ স্ক্রিনশট পাঠান" বাটন ও রিপিট-অর্ডারের ক্ষেত্রে এই নাম্বারে লিংক যাবে।</p>
                </div>
                <div>
                    <label class="block text-slate-300 text-xs mb-1">রিপিট-অর্ডার ব্লক (ঘণ্টা)</label>
                    <input type="number" name="block_repeat_hours" min="0" value="<?= htmlspecialchars(get_setting('block_repeat_hours') ?: '24') ?>" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    <p class="text-[10px] text-slate-500 mt-1">একই ফোন/IP দিয়ে এই কত ঘণ্টার মধ্যে আবার অর্ডার করা যাবে না। <b class="text-amber-400">০ দিলে বন্ধ।</b> (ডিফল্ট ২৪ = ১ দিন)</p>
                </div>
                <div class="md:col-span-4">
                    <button type="submit" class="bg-amber-600 hover:bg-amber-500 text-white text-sm font-bold px-6 py-2.5 rounded-xl"><i class="fa-solid fa-floppy-disk"></i> সেটিংস সেভ করুন</button>
                </div>
            </form>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-user-slash text-rose-500"></i> <span data-i18n="নতুন ব্লক যোগ করুন">নতুন ব্লক যোগ করুন</span>
                </h3>
                <p class="text-xs text-slate-400 mb-4">মোবাইল নাম্বার অথবা আইপি — যেকোনো একটি অথবা দুটোই দিতে পারবেন। ব্লক করা কাস্টমার আর অর্ডার করতে পারবে না।</p>
                <form action="?action=fraud_detection" method="POST" class="space-y-4">
                    <input type="hidden" name="add_block" value="1">
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">মোবাইল নাম্বার</label>
                        <input type="text" name="block_phone" placeholder="01XXXXXXXXX" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">আইপি অ্যাড্রেস</label>
                        <input type="text" name="block_ip" placeholder="103.129.202.202" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">ব্লকের কারণ (ঐচ্ছিক)</label>
                        <input type="text" name="block_reason" placeholder="যেমন: বারবার ফেক অর্ডার" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                    </div>
                    <button type="submit" class="w-full bg-rose-600 hover:bg-rose-500 text-white font-bold py-2.5 rounded-lg transition text-sm flex items-center justify-center gap-2">
                        <i class="fa-solid fa-ban"></i> ব্লক করুন
                    </button>
                </form>
            </div>

            <div class="lg:col-span-2 bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
                <h3 class="text-lg font-bold text-white mb-6 flex items-center gap-2">
                    <i class="fa-solid fa-shield-halved text-rose-400"></i> <span data-i18n="ব্লক করা কাস্টমার লিস্ট">ব্লক করা কাস্টমার লিস্ট</span>
                    <span class="text-xs bg-rose-500/20 text-rose-400 px-2 py-0.5 rounded-full font-mono"><?= count($blocked_list) ?></span>
                </h3>
                <div class="overflow-x-auto">
                    <table class="w-full text-left">
                        <thead>
                            <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs uppercase tracking-wider">
                                <th class="p-3" data-i18n="মোবাইল নাম্বার">মোবাইল নাম্বার</th>
                                <th class="p-3" data-i18n="আইপি">আইপি</th>
                                <th class="p-3" data-i18n="কারণ">কারণ</th>
                                <th class="p-3" data-i18n="ব্লক করেছেন">ব্লক করেছেন</th>
                                <th class="p-3" data-i18n="তারিখ">তারিখ</th>
                                <th class="p-3 text-right" data-i18n="পদক্ষেপ">পদক্ষেপ</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-700">
                            <?php if (empty($blocked_list)): ?>
                                <tr><td colspan="6" class="p-8 text-center text-slate-400 text-sm">কোনো ব্লক করা কাস্টমার নেই।</td></tr>
                            <?php else: ?>
                                <?php foreach ($blocked_list as $b): ?>
                                    <tr class="text-sm">
                                        <td class="p-3 font-mono text-white">
                                            <?php if ($b['phone']): ?>
                                                <?= htmlspecialchars($b['phone']) ?>
                                                <button onclick="copyText('<?= htmlspecialchars($b['phone']) ?>')" class="text-slate-400 hover:text-emerald-400 ml-1" title="কপি করুন"><i class="fa-regular fa-copy text-xs"></i></button>
                                            <?php else: ?>
                                                <span class="text-slate-500">—</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="p-3 font-mono text-slate-300"><?= $b['ip_address'] ? htmlspecialchars($b['ip_address']) : '—' ?></td>
                                        <td class="p-3 text-slate-300 text-xs max-w-[200px] break-words"><?= htmlspecialchars($b['reason'] ?: '—') ?></td>
                                        <td class="p-3 text-slate-400 text-xs"><?= htmlspecialchars($b['blocked_by'] ?: '—') ?></td>
                                        <td class="p-3 text-slate-400 text-xs font-mono"><?= $b['created_at'] ?></td>
                                        <td class="p-3 text-right">
                                            <button type="button" onclick="removeBlockConfirm(<?= $b['id'] ?>)" class="bg-emerald-600/20 hover:bg-emerald-600 text-emerald-400 hover:text-white text-xs px-3 py-1.5 rounded-lg font-bold transition border border-emerald-500/30" data-i18n="আনব্লক করুন">আনব্লক করুন</button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <form id="removeBlockForm" action="?action=fraud_detection" method="POST" class="hidden">
        <input type="hidden" name="remove_block" value="1">
        <input type="hidden" name="block_id" id="removeBlockId" value="">
    </form>

    <script>
        function removeBlockConfirm(bid) {
            showConfirmModal('এই ব্লকটি রিমুভ করতে চান? কাস্টমার আবার অর্ডার করতে পারবে।', () => {
                document.getElementById('removeBlockId').value = bid;
                document.getElementById('removeBlockForm').submit();
            });
        }
    </script>
    <?php
}

function render_incomplete_panel($incompletes, $matched_orders = []) {
    global $status_map;
    $role = get_user_role();
    $norm_ph = function ($ph) { $c = preg_replace('/\D/', '', bnToEnNumber((string)$ph)); return strlen($c) > 11 ? substr($c, -11) : $c; };
    $matched_count = 0;
    foreach ($incompletes as $tmp_inc) {
        if (isset($matched_orders[$norm_ph($tmp_inc['phone'] ?? '')])) $matched_count++;
    }
    ?>
    <?php if (isset($_GET['bulk_done'])): $bd = (int)$_GET['bulk_done']; $ba = $_GET['bulk_act'] ?? ''; ?>
        <div class="bg-emerald-500/10 border border-emerald-500 text-emerald-400 p-4 rounded-xl text-sm font-semibold mb-4">
            ✅ <?= $bd ?> টি এন্ট্রি সফলভাবে <?= $ba === 'delete' ? 'ডিলিট' : 'অর্ডারে শিফট' ?> করা হয়েছে!
            <?= $ba === 'shift' && $bd > 0 ? '<a href="?action=dashboard&status_filter=pending" class="underline hover:text-emerald-300 ml-1">পেন্ডিং অর্ডারে দেখুন →</a>' : '' ?>
        </div>
    <?php endif; ?>
    <div class="bg-slate-800 rounded-2xl border border-slate-700 overflow-hidden shadow-lg font-semibold">
        <div class="p-6 border-b border-slate-700 flex items-center justify-between">
            <h3 class="text-lg font-bold text-white flex items-center gap-2">
                <i class="fa-solid fa-hourglass-half text-amber-400"></i> <span data-i18n="ইনকমপ্লিট অর্ডার ট্র্যাকিং">ইনকমপ্লিট অর্ডার ট্র্যাকিং</span>
                <span class="text-xs bg-amber-500/20 text-amber-400 px-2 py-0.5 rounded-full font-mono"><?= count($incompletes) ?></span>
                <?php if ($matched_count > 0): ?>
                <span class="text-xs bg-emerald-500/20 text-emerald-400 px-2 py-0.5 rounded-full font-mono" title="এই নাম্বারগুলো দিয়ে পরে সফল অর্ডার হয়েছে">✅ <?= $matched_count ?> অর্ডার সফল</span>
                <?php endif; ?>
            </h3>
            <p class="text-[11px] text-slate-400 hidden md:block">কাস্টমার নাম/নাম্বার/ঠিকানা দিয়েছে কিন্তু অর্ডার বাটনে ক্লিক করেনি — <span class="text-emerald-400">সবুজ সারি = এই নাম্বারে পরে সফল অর্ডার পাওয়া গেছে</span></p>
            <?php if ($role !== 'agent' && $matched_count > 0): ?>
            <form action="?action=incomplete_orders" method="POST" onsubmit="return confirm('সফল অর্ডার পাওয়া গেছে এমন <?= $matched_count ?> টি এন্ট্রি (সবুজ সারি) একসাথে ডিলিট হবে। নিশ্চিত?');" class="inline">
                <input type="hidden" name="delete_matched_incomplete" value="1">
                <button type="submit" class="text-[11px] font-bold bg-emerald-600/20 text-emerald-400 border border-emerald-600/50 hover:bg-emerald-600/40 px-3 py-1.5 rounded-full transition" title="যেসব এন্ট্রির নাম্বারে পরে সফল অর্ডার হয়েছে — সবগুলো এক ক্লিকে ডিলিট">
                    <i class="fa-solid fa-broom"></i> সফল অর্ডারের <?= $matched_count ?> টি এন্ট্রি ডিলিট করুন
                </button>
            </form>
            <?php endif; ?>
        </div>
        <!-- Bulk অ্যাকশন বার -->
        <div id="incBulkBar" class="hidden items-center gap-3 px-6 py-2.5 bg-violet-950/40 border-b border-violet-800/40 flex-wrap">
            <span class="text-xs text-violet-300 font-bold"><span id="incBulkCount">0</span> টি সিলেক্টেড</span>
            <button type="button" onclick="incBulkAction('shift')" class="text-[11px] font-bold bg-emerald-600 hover:bg-emerald-500 text-white px-3 py-1.5 rounded-lg"><i class="fa-solid fa-arrow-right-arrow-left"></i> সবগুলো অর্ডারে শিফট</button>
            <?php if ($role !== 'agent'): ?>
            <button type="button" onclick="incBulkAction('delete')" class="text-[11px] font-bold bg-rose-600 hover:bg-rose-500 text-white px-3 py-1.5 rounded-lg"><i class="fa-solid fa-trash"></i> সবগুলো ডিলিট</button>
            <?php endif; ?>
        </div>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead>
                    <tr class="bg-slate-900 border-b border-slate-700 text-slate-400 text-xs uppercase tracking-wider">
                        <th class="p-3 w-10 text-center"><input type="checkbox" id="incCheckAll" onchange="incToggleAll(this)" class="rounded text-violet-500 cursor-pointer" title="সব সিলেক্ট করুন"></th>
                        <th class="p-3" data-i18n="সময়">সময়</th>
                        <th class="p-3" data-i18n="নাম">নাম</th>
                        <th class="p-3" data-i18n="মোবাইল">মোবাইল</th>
                        <th class="p-3" data-i18n="ঠিকানা">ঠিকানা</th>
                        <th class="p-3" data-i18n="পণ্য">পণ্য</th>
                        <th class="p-3" data-i18n="আইপি">আইপি</th>
                        <th class="p-3" data-i18n="পেজ">পেজ</th>
                        <th class="p-3 text-center" data-i18n="ফ্রড চেক">ফ্রড চেক</th>
                        <th class="p-3 text-right" data-i18n="পদক্ষেপ">পদক্ষেপ</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-700">
                    <?php if (empty($incompletes)): ?>
                        <tr><td colspan="10" class="p-8 text-center text-slate-400 text-sm">কোনো ইনকমপ্লিট অর্ডার নেই।</td></tr>
                    <?php else: ?>
                        <?php foreach ($incompletes as $inc):
                            $inc_match = $matched_orders[$norm_ph($inc['phone'] ?? '')] ?? null;
                        ?>
                            <tr class="text-sm transition <?= $inc_match ? 'bg-emerald-500/10 hover:bg-emerald-500/20 border-l-4 border-emerald-500' : 'hover:bg-slate-750' ?>">
                                <td class="p-3 text-center"><input type="checkbox" value="<?= (int)$inc['id'] ?>" onchange="incUpdateBulkBar()" class="inc-check rounded text-violet-500 cursor-pointer"></td>
                                <td class="p-3 text-slate-400 text-xs font-mono whitespace-nowrap"><?= date('d M, h:i A', strtotime($inc['updated_at'])) ?></td>
                                <td class="p-3 text-white font-bold">
                                    <?= $inc['customer_name'] !== '' && $inc['customer_name'] !== null ? htmlspecialchars($inc['customer_name']) : '<span class="text-slate-500 font-normal">—</span>' ?>
                                    <?php if ($inc_match): ?>
                                        <a href="?action=order_detail&id=<?= (int)$inc_match['id'] ?>" class="block mt-1 text-[10px] font-bold bg-emerald-500/20 text-emerald-400 px-2 py-0.5 rounded-full w-fit hover:bg-emerald-500/30" title="এই নাম্বারে সফল অর্ডার পাওয়া গেছে — ক্লিক করে দেখুন">
                                            ✅ অর্ডার সফল #<?= (int)$inc_match['id'] ?> (<?= htmlspecialchars($status_map[$inc_match['status']] ?? $inc_match['status']) ?>)
                                        </a>
                                    <?php endif; ?>
                                </td>
                                <td class="p-3">
                                    <?php if (!empty($inc['phone'])): ?>
                                        <span class="font-mono text-emerald-400"><?= htmlspecialchars($inc['phone']) ?></span>
                                        <button onclick="copyText('<?= htmlspecialchars($inc['phone']) ?>')" class="text-slate-400 hover:text-emerald-400 ml-1" title="কপি করুন"><i class="fa-regular fa-copy text-xs"></i></button>
                                        <button onclick="dialCustomer('<?= htmlspecialchars($inc['phone'], ENT_QUOTES) ?>', 0, '<?= htmlspecialchars($inc['customer_name'] ?? '', ENT_QUOTES) ?>')" class="text-cyan-400 hover:text-cyan-300 ml-1" title="ডায়ালার দিয়ে কল দিন"><i class="fa-solid fa-headset text-xs"></i></button>
                                    <?php else: ?>
                                        <span class="text-slate-500">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="p-3 text-slate-300 text-xs max-w-[220px] break-words"><?= !empty($inc['address']) ? htmlspecialchars($inc['address']) : '—' ?></td>
                                <td class="p-3 text-slate-300 text-xs"><?= !empty($inc['product_title']) ? htmlspecialchars($inc['product_title']) : '—' ?></td>
                                <td class="p-3 font-mono text-[11px] text-sky-400 cursor-pointer" onclick="copyText(this.innerText)" title="ক্লিক করে কপি করুন"><?= !empty($inc['customer_ip']) ? htmlspecialchars($inc['customer_ip']) : '—' ?></td>
                                <td class="p-3 font-mono text-[11px] text-indigo-400">/<?= htmlspecialchars($inc['page_slug'] ?? '') ?></td>
                                <td class="p-3 text-center">
                                    <?php if (!empty($inc['phone'])): ?>
                                    <button type="button" onclick="triggerFraudCheck('<?= htmlspecialchars($inc['phone'], ENT_QUOTES) ?>', this)" class="mx-auto px-2.5 py-1 rounded text-[11px] font-bold bg-slate-700 text-slate-300 hover:bg-rose-600/30 hover:text-rose-300 transition block" data-i18n="রিস্ক চেক">রিস্ক চেক</button>
                                    <?php else: ?><span class="text-slate-600 text-[10px]">—</span><?php endif; ?>
                                </td>
                                <?php if ($role !== 'agent'): ?>
                                    <td class="p-3 text-right whitespace-nowrap">
                                        <button type="button" onclick="shiftIncompleteConfirm(<?= $inc['id'] ?>)" class="text-emerald-400 hover:text-emerald-300 text-xs font-bold mr-3" title="এই এন্ট্রিটি নতুন অর্ডার হিসেবে অর্ডার তালিকায় যোগ হবে"><i class="fa-solid fa-arrow-right-arrow-left"></i> <span data-i18n="অর্ডারে শিফট">অর্ডারে শিফট</span></button>
                                        <button type="button" onclick="deleteIncompleteConfirm(<?= $inc['id'] ?>)" class="text-rose-400 hover:text-rose-300 text-xs font-bold" data-i18n="মুছে ফেলুন">মুছে ফেলুন</button>
                                    </td>
                                <?php else: ?>
                                    <td class="p-3 text-right whitespace-nowrap">
                                        <button type="button" onclick="shiftIncompleteConfirm(<?= $inc['id'] ?>)" class="text-emerald-400 hover:text-emerald-300 text-xs font-bold" title="এই এন্ট্রিটি নতুন অর্ডার হিসেবে অর্ডার তালিকায় যোগ হবে"><i class="fa-solid fa-arrow-right-arrow-left"></i> <span data-i18n="অর্ডারে শিফট">অর্ডারে শিফট</span></button>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($role !== 'agent'): ?>
    <form id="incBulkForm" action="?action=incomplete_orders" method="POST" class="hidden">
        <input type="hidden" name="bulk_incomplete" value="1">
        <input type="hidden" name="bulk_action" id="inc-bulk-action" value="">
        <input type="hidden" name="bulk_ids" id="inc-bulk-ids" value="">
    </form>
    <form id="shiftIncompleteForm" action="?action=incomplete_orders" method="POST" class="hidden">
        <input type="hidden" name="shift_to_order" value="1">
        <input type="hidden" name="incomplete_id" id="shift-incomplete-id" value="0">
    </form>
    <form id="deleteIncompleteForm" action="?action=incomplete_orders" method="POST" class="hidden">
        <input type="hidden" name="delete_incomplete" value="1">
        <input type="hidden" name="incomplete_id" id="deleteIncompleteId" value="">
    </form>
    <script>
        function incSelectedIds() {
            return Array.from(document.querySelectorAll('.inc-check:checked')).map(cb => cb.value);
        }
        function incUpdateBulkBar() {
            const ids = incSelectedIds();
            const bar = document.getElementById('incBulkBar');
            document.getElementById('incBulkCount').innerText = ids.length;
            bar.classList.toggle('hidden', ids.length === 0);
            bar.classList.toggle('flex', ids.length > 0);
        }
        function incToggleAll(master) {
            document.querySelectorAll('.inc-check').forEach(cb => cb.checked = master.checked);
            incUpdateBulkBar();
        }
        function incBulkAction(act) {
            const ids = incSelectedIds();
            if (!ids.length) { showToast('আগে অন্তত একটা এন্ট্রি সিলেক্ট করুন', 'error'); return; }
            const doSubmit = () => {
                document.getElementById('inc-bulk-action').value = act;
                document.getElementById('inc-bulk-ids').value = ids.join(',');
                document.getElementById('incBulkForm').submit();
            };
            if (act === 'delete') {
                showDoubleConfirm(ids.length + ' টি ইনকমপ্লিট এন্ট্রি স্থায়ীভাবে ডিলিট হবে!', doSubmit);
            } else {
                showConfirmModal(ids.length + ' টি এন্ট্রি নতুন অর্ডার হিসেবে অর্ডার তালিকায় যোগ হবে। এগিয়ে যাবেন?', doSubmit);
            }
        }

        function shiftIncompleteConfirm(iid) {
            showConfirmModal('এই ইনকমপ্লিট এন্ট্রিটি নতুন অর্ডার হিসেবে অর্ডার তালিকায় যোগ হবে এবং এখান থেকে সরে যাবে। এগিয়ে যাবেন?', () => {
                document.getElementById('shift-incomplete-id').value = iid;
                document.getElementById('shiftIncompleteForm').submit();
            });
        }

        function deleteIncompleteConfirm(iid) {
            showConfirmModal('এই ইনকমপ্লিট রেকর্ডটি মুছে ফেলতে চান?', () => {
                document.getElementById('deleteIncompleteId').value = iid;
                document.getElementById('deleteIncompleteForm').submit();
            });
        }
    </script>
    <?php endif; ?>
    <?php
}

function render_sip_dialer_panel($sip_msg) {
    $role = get_user_role();
    $is_admin_or_office = ($role === 'admin' || $role === 'office_team');
    $ro = $is_admin_or_office ? '' : 'disabled';
    $sip = [
        'dialer_mode'   => get_setting('dialer_mode') ?: 'tel',
        'wss_url'       => get_setting('sip_wss_url'),
        'username'      => get_setting('sip_username'),
        'password'      => get_setting('sip_password'),
        'domain'        => get_setting('sip_domain'),
        'port'          => get_setting('sip_port') ?: '5060',
        'transport'     => get_setting('sip_transport') ?: 'UDP',
        'proxy'         => get_setting('sip_proxy'),
        'dtmf'          => get_setting('sip_dtmf') ?: 'RFC2833',
        'stun'          => get_setting('sip_stun') ?: 'stun.l.google.com:19302',
        'reg_interval'  => get_setting('sip_reg_interval') ?: '60',
        'portal_url'    => get_setting('sip_portal_url') ?: 'https://webvoice.net',
        'balance_code'  => get_setting('sip_balance_code') ?: '123',
    ];
    ?>
    <div class="space-y-6 font-semibold">
        <?php if ($sip_msg):
            $m_text = is_array($sip_msg) ? ($sip_msg['text'] ?? '') : $sip_msg;
            $m_err  = is_array($sip_msg) && ($sip_msg['type'] ?? '') === 'error';
        ?>
            <div class="<?= $m_err ? 'bg-rose-500/10 border-rose-500 text-rose-400' : 'bg-emerald-500/10 border-emerald-500 text-emerald-400' ?> border p-4 rounded-xl text-sm"><?= htmlspecialchars($m_text) ?></div>
        <?php endif; ?>

        <?php render_webrtc_dialer_pad($sip); ?>

        <div class="grid grid-cols-1 <?= get_user_role() === 'admin' ? 'lg:grid-cols-2' : '' ?> gap-8">
            <?php if (get_user_role() === 'admin'): // SIP কনফিগারেশন শুধু অ্যাডমিন প্যানেলে ?>
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-headset text-cyan-400"></i> <span data-i18n="SIP ডায়ালার কনফিগারেশন">SIP ডায়ালার কনফিগারেশন</span>
                </h3>
                <form action="?action=sip_dialer" method="POST" class="space-y-4">
                    <input type="hidden" name="save_sip" value="1">
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">ডায়ালার মোড (কল বাটনে ক্লিক করলে কোনটা দিয়ে কল হবে)</label>
                        <select name="dialer_mode" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                            <option value="webrtc" <?= $sip['dialer_mode'] === 'webrtc' ? 'selected' : '' ?>>ওয়েব ডায়ালার (ব্রাউজারেই কল + অটো রেকর্ডিং) — Recommended</option>
                            <option value="tel" <?= $sip['dialer_mode'] === 'tel' ? 'selected' : '' ?>>ফোন ডায়ালার (tel:)</option>
                            <option value="sip" <?= $sip['dialer_mode'] === 'sip' ? 'selected' : '' ?>>SIP ডায়ালার (sip:number@domain)</option>
                            <option value="callto" <?= $sip['dialer_mode'] === 'callto' ? 'selected' : '' ?>>Callto প্রোটোকল (callto:)</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">WebSocket (WSS) URL — ওয়েব ডায়ালারের জন্য আবশ্যক</label>
                        <input type="text" name="sip_wss_url" value="<?= htmlspecialchars($sip['wss_url']) ?>" <?= $ro ?> placeholder="wss://sip.rafusoft.com:7443/ws" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        <p class="text-[10px] text-slate-500 mt-1">ব্রাউজার থেকে সরাসরি UDP/5060-এ কল করা যায় না — আপনার SIP প্রোভাইডারের কাছ থেকে WebSocket (WSS) URL নিয়ে এখানে দিন। যেমন: <span class="font-mono">wss://sip.rafusoft.com:7443/ws</span> বা <span class="font-mono">wss://103.129.202.202:8089/ws</span></p>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Username (আইপি নাম্বার)</label>
                            <input type="text" name="sip_username" value="<?= htmlspecialchars($sip['username']) ?>" <?= $ro ?> placeholder="09647933949" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Password</label>
                            <input type="text" name="sip_password" value="<?= htmlspecialchars($sip['password']) ?>" <?= $ro ?> placeholder="rafu#949" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">SIP/Domain ID</label>
                            <input type="text" name="sip_domain" value="<?= htmlspecialchars($sip['domain']) ?>" <?= $ro ?> placeholder="sip.rafusoft.com" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Port</label>
                            <input type="text" name="sip_port" value="<?= htmlspecialchars($sip['port']) ?>" <?= $ro ?> placeholder="5060" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Transport Protocol</label>
                            <select name="sip_transport" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                                <option value="UDP" <?= $sip['transport'] === 'UDP' ? 'selected' : '' ?>>UDP (Recommended)</option>
                                <option value="TCP" <?= $sip['transport'] === 'TCP' ? 'selected' : '' ?>>TCP</option>
                                <option value="TLS" <?= $sip['transport'] === 'TLS' ? 'selected' : '' ?>>TLS</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Outbound Proxy</label>
                            <input type="text" name="sip_proxy" value="<?= htmlspecialchars($sip['proxy']) ?>" <?= $ro ?> placeholder="103.129.202.202" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">DTMF Mode</label>
                            <select name="sip_dtmf" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm">
                                <option value="RFC2833" <?= $sip['dtmf'] === 'RFC2833' ? 'selected' : '' ?>>RFC2833</option>
                                <option value="INBAND" <?= $sip['dtmf'] === 'INBAND' ? 'selected' : '' ?>>INBAND</option>
                                <option value="SIP-INFO" <?= $sip['dtmf'] === 'SIP-INFO' ? 'selected' : '' ?>>SIP-INFO</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">STUN Server (NAT সমস্যার জন্য)</label>
                            <input type="text" name="sip_stun" value="<?= htmlspecialchars($sip['stun']) ?>" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">Registration Interval (সেকেন্ড)</label>
                            <input type="text" name="sip_reg_interval" value="<?= htmlspecialchars($sip['reg_interval']) ?>" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                        <div>
                            <label class="block text-slate-300 text-xs mb-1">ব্যালেন্স চেক ডায়াল কোড</label>
                            <input type="text" name="sip_balance_code" value="<?= htmlspecialchars($sip['balance_code']) ?>" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                        </div>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-xs mb-1">পোর্টাল / রিচার্জ URL</label>
                        <input type="text" name="sip_portal_url" value="<?= htmlspecialchars($sip['portal_url']) ?>" <?= $ro ?> class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none text-sm font-mono">
                    </div>
                    <?php if ($is_admin_or_office): ?>
                        <div class="flex gap-3 pt-2">
                            <button type="submit" class="flex-1 bg-cyan-600 hover:bg-cyan-500 text-white font-bold py-2.5 rounded-lg transition text-sm"><i class="fa-solid fa-floppy-disk"></i> সেভ ও চেঞ্জ করুন</button>
                            <button type="button" onclick="resetSipConfirm()" class="bg-rose-600/20 hover:bg-rose-600 text-rose-400 hover:text-white border border-rose-500/30 font-bold px-4 py-2.5 rounded-lg transition text-sm"><i class="fa-solid fa-rotate-left"></i> রিসেট</button>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
            <?php endif; ?>

            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-circle-info text-emerald-400"></i> IP Phone কনফিগারেশন গাইড
                </h3>
                <div class="space-y-3 text-xs text-slate-300 leading-relaxed">
                    <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 space-y-2">
                        <p>🚀 <b>Check Your Logs & Recharge</b></p>
                        <p>📌 Portal: 🌐 <a href="<?= htmlspecialchars($sip['portal_url']) ?>" target="_blank" class="text-cyan-400 hover:underline font-mono"><?= htmlspecialchars($sip['portal_url']) ?></a></p>
                        <p>🔑 Login: আপনার IP নাম্বারটি username হিসেবে ব্যবহার করুন, এবং নিচের password দিন।</p>
                    </div>
                    <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 space-y-1.5">
                        <p class="font-bold text-white mb-2">🔐 IP Phone Configuration Details:</p>
                        <p>1️⃣ আপনার SIP Dialer অ্যাপটি ওপেন করুন</p>
                        <p>2️⃣ Account Settings-এ গিয়ে নিচের তথ্যগুলো দিন:</p>
                        <div class="pl-2 pt-2 space-y-1 font-mono text-[11px]">
                            <p>🔹 Username: <b class="text-cyan-400"><?= htmlspecialchars($sip['username'] ?: '—') ?></b></p>
                            <p>🔹 Password: <b class="text-cyan-400"><?= htmlspecialchars($sip['password'] ?: '—') ?></b></p>
                            <p>🔹 SIP/Domain ID: <b class="text-cyan-400"><?= htmlspecialchars($sip['domain'] ?: '—') ?></b></p>
                            <p>🔹 Port: <b class="text-cyan-400"><?= htmlspecialchars($sip['port']) ?></b> (Default SIP Port)</p>
                            <p>🔹 Transport Protocol: <b class="text-cyan-400"><?= htmlspecialchars($sip['transport']) ?></b> (Recommended)</p>
                            <p>🔹 Outbound Proxy: <b class="text-cyan-400"><?= htmlspecialchars($sip['proxy'] ?: '—') ?></b> (if required)</p>
                        </div>
                    </div>
                    <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 space-y-1.5 font-mono text-[11px]">
                        <p class="font-bold text-white font-sans text-xs mb-1">🛠️ Additional Settings (if needed):</p>
                        <p>✅ DTMF Mode: <b class="text-cyan-400"><?= htmlspecialchars($sip['dtmf']) ?></b></p>
                        <p>✅ STUN Server: <b class="text-cyan-400"><?= htmlspecialchars($sip['stun']) ?></b> (Optional, for NAT issues)</p>
                        <p>✅ Registration Interval: <b class="text-cyan-400"><?= htmlspecialchars($sip['reg_interval']) ?></b> Seconds</p>
                    </div>
                    <div class="bg-emerald-950/30 border border-emerald-900/40 rounded-xl p-4">
                        <p>🎯 ব্যালেন্স চেক করতে ডায়াল করুন: <b class="text-emerald-400 font-mono text-sm"><?= htmlspecialchars($sip['balance_code']) ?></b></p>
                    </div>
                </div>
            </div>
        </div>

        <?php render_call_history_section(); ?>
    </div>

    <?php if ($is_admin_or_office): ?>
    <form id="resetSipForm" action="?action=sip_dialer" method="POST" class="hidden">
        <input type="hidden" name="reset_sip" value="1">
    </form>
    <script>
        function resetSipConfirm() {
            showConfirmModal('SIP কনফিগারেশন রিসেট করলে সব তথ্য ডিফল্টে ফিরে যাবে। আপনি কি নিশ্চিত?', () => {
                document.getElementById('resetSipForm').submit();
            });
        }
    </script>
    <?php endif; ?>
    <?php
}

function render_branding_panel($br_msg) {
    ?>
    <div class="max-w-3xl mx-auto space-y-6 font-semibold">
        <?php if ($br_msg): ?>
            <div class="bg-emerald-500/10 border border-emerald-500 text-emerald-400 p-4 rounded-xl text-sm"><?= htmlspecialchars($br_msg) ?></div>
        <?php endif; ?>

        <form action="?action=branding" method="POST" class="space-y-6">
            <input type="hidden" name="save_branding" value="1">
            <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-md">
                <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
                    <i class="fa-solid fa-palette text-fuchsia-400"></i> <span data-i18n="সাইট ব্র্যান্ডিং সেটিংস">সাইট ব্র্যান্ডিং সেটিংস</span>
                </h3>
                <p class="text-xs text-slate-400 mb-6">এখানে পরিবর্তন করলে ড্যাশবোর্ড, লগইন পেজ, ল্যান্ডিং পেজ, ইনভয়েস — সব জায়গায় একসাথে পরিবর্তন হবে।</p>
                <div class="space-y-4">
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাইটের নাম</label>
                        <input type="text" name="brand_site_name" value="<?= htmlspecialchars(branding('site_name')) ?>" placeholder="SunnahTi" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        <p class="text-[10px] text-slate-500 mt-1">সাইডবার, লগইন পেজ, ইনভয়েসের হেডারে দেখাবে।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাইট টাইটেল (ব্রাউজার ট্যাবে)</label>
                        <input type="text" name="brand_site_title" value="<?= htmlspecialchars(branding('site_title')) ?>" placeholder="SunnahTi Premium Store" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none">
                        <p class="text-[10px] text-slate-500 mt-1">ব্রাউজারের ট্যাবের টাইটেলে দেখাবে।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">হোম পেজ লিংক</label>
                        <input type="text" name="brand_home_url" value="<?= htmlspecialchars(branding('home_url')) ?>" placeholder="https://example.com" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                        <p class="text-[10px] text-slate-500 mt-1">ল্যান্ডিং পেজে লোগো/নামে ক্লিক করলে এই লিংকে নিয়ে যাবে।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">ফেভিকন আইকন URL</label>
                        <input type="text" name="brand_favicon_url" value="<?= htmlspecialchars(branding('favicon_url')) ?>" placeholder="https://.../favicon.png" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                        <p class="text-[10px] text-slate-500 mt-1">মিডিয়া ম্যানেজারে ছবি আপলোড করে সেই লিংক এখানে পেস্ট করতে পারেন।</p>
                    </div>
                    <div>
                        <label class="block text-slate-300 text-sm mb-1">সাইট লোগো URL</label>
                        <input type="text" name="brand_logo_url" value="<?= htmlspecialchars(branding('logo_url')) ?>" placeholder="https://.../logo.png" class="w-full bg-slate-700 text-white rounded-lg px-3 py-2 border border-slate-600 outline-none font-mono text-sm">
                        <p class="text-[10px] text-slate-500 mt-1">লোগো দিলে সাইডবার ও লগইন পেজে নামের বদলে লোগো দেখাবে।</p>
                    </div>
                    <?php if (branding('logo_url')): ?>
                        <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 flex items-center gap-4">
                            <img src="<?= htmlspecialchars(branding('logo_url')) ?>" class="h-12 object-contain rounded">
                            <span class="text-xs text-slate-400">বর্তমান লোগো প্রিভিউ</span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <div class="flex justify-end">
                <button type="submit" class="bg-fuchsia-600 hover:bg-fuchsia-500 text-white px-6 py-2.5 rounded-xl font-bold transition shadow-lg text-sm"><i class="fa-solid fa-floppy-disk"></i> ব্র্যান্ডিং সেভ করুন</button>
            </div>
        </form>
    </div>
    <?php
}

// Thermal Printer Template Design System with Dynamic Output configuration Toggles
function render_invoice_thermal($orders, $type) {
    $show_name = ($_GET['show_name'] ?? '1') === '1';
    $show_phone = ($_GET['show_phone'] ?? '1') === '1';
    $show_address = ($_GET['show_address'] ?? '1') === '1';
    $show_product = ($_GET['show_product'] ?? '1') === '1';
    $show_color = ($_GET['show_color'] ?? '1') === '1';
    $show_consignment = ($_GET['show_consignment'] ?? '1') === '1';
    $show_cod = ($_GET['show_cod'] ?? '1') === '1';
    $show_footer = ($_GET['show_footer'] ?? '1') === '1';
    $brand_name = branding('site_name') ?: 'SUNNAHTI STORE';
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <title>Thermal Invoice Printing Mode</title>
        <?= render_favicon_tag() ?>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 0;
                background-color: #f3f4f6;
                color: #000;
            }
            .invoice-box {
                background: #fff;
                margin: 0 auto;
                padding: 15px;
                border: 1px dashed #bbb;
                box-sizing: border-box;
                page-break-after: always;
            }
            .width-80mm {
                width: 80mm;
                min-height: 30mm;
            }
            .width-40mm {
                width: 40mm;
                min-height: 30mm;
                font-size: 9px;
                padding: 5px;
            }
            /* ==== কম্প্যাক্ট লেবেল (৩ সাইজ) — শুধু জরুরি তথ্য + QR + COD, টাইটেল/ধন্যবাদ ছাড়া ==== */
            .clabel { box-sizing: border-box; page-break-after: always; overflow: hidden; }
            .clabel .lbl-row { margin: 1px 0; line-height: 1.25; word-break: break-word; }
            .clabel .lbl-phone { font-weight: bold; }
            .clabel .lbl-cons { font-weight: bold; letter-spacing: 0.3px; }
            .clabel .lbl-cod { font-weight: bold; }
            .clabel .lbl-flex { display: flex; gap: 2mm; align-items: flex-start; }
            .clabel .lbl-info { flex: 1; min-width: 0; }
            .clabel .lbl-qr { flex-shrink: 0; text-align: center; }
            .clabel .lbl-qr canvas, .clabel .lbl-qr img { display: block; }

            /* 50mm × 75mm — বড়, খাড়া (QR উপরে/আলাদা) */
            .lbl-50x75 { width: 50mm; min-height: 75mm; padding: 3mm; font-size: 12px; }
            .lbl-50x75 .lbl-phone { font-size: 15px; }
            .lbl-50x75 .lbl-cons { font-size: 15px; }
            .lbl-50x75 .lbl-cod { font-size: 15px; }
            .lbl-50x75 .lbl-qr { margin: 2mm auto 0; }

            /* 80mm × 30mm — চওড়া, QR ডানে */
            .lbl-80x30 { width: 80mm; min-height: 30mm; padding: 2mm; font-size: 11px; }
            .lbl-80x30 .lbl-phone { font-size: 13px; }
            .lbl-80x30 .lbl-cons { font-size: 13px; }
            .lbl-80x30 .lbl-cod { font-size: 13px; }

            /* 40mm × 30mm — ছোট, QR ডানে ছোট */
            .lbl-40x30 { width: 40mm; min-height: 30mm; padding: 1.5mm; font-size: 9px; }
            .lbl-40x30 .lbl-phone { font-size: 11px; }
            .lbl-40x30 .lbl-cons { font-size: 11px; }
            .lbl-40x30 .lbl-cod { font-size: 11px; }
            .title {
                font-size: 14px;
                font-weight: bold;
                text-align: center;
                margin-bottom: 5px;
            }
            .width-40mm .title {
                font-size: 11px;
            }
            .meta-line {
                margin: 4px 0;
                line-height: 1.2;
            }
            .divider {
                border-top: 1px dashed #000;
                margin: 6px 0;
            }
            .price-total {
                font-weight: bold;
                font-size: 13px;
                text-align: right;
            }
            .width-40mm .price-total {
                font-size: 10px;
            }
            @media print {
                body { background: none; }
                .invoice-box { border: none; margin: 0; padding: 5px; }
            }
        </style>
    </head>
    <body>
        <?php
        // কম্প্যাক্ট লেবেল সাইজ ম্যাপ
        $clabel_sizes = ['label_50x75' => 'lbl-50x75', 'label_80x30' => 'lbl-80x30', 'label_40x30' => 'lbl-40x30'];
        $is_clabel = isset($clabel_sizes[$type]);
        // পুরোনো label30 = নতুন 40x30
        if ($type === 'label30') { $is_clabel = true; $type = 'label_40x30'; }
        ?>
        <?php if ($is_clabel): $size_cls = $clabel_sizes[$type] ?? 'lbl-40x30'; $qr_px = $type === 'label_50x75' ? 130 : ($type === 'label_80x30' ? 90 : 70); ?>
            <?php foreach ($orders as $idx => $order):
                $qr_phone = preg_replace('/[^0-9+]/', '', $order['phone']);
                $cons = $order['consignment_id'] ?: ($order['tracking_code'] ?: '');
            ?>
            <div class="invoice-box clabel <?= $size_cls ?>">
                <div class="lbl-flex">
                    <div class="lbl-info">
                        <div class="lbl-row lbl-phone"><?= htmlspecialchars($order['phone']) ?></div>
                        <?php if (!empty($order['product_title'])): ?>
                            <div class="lbl-row"><?= htmlspecialchars($order['product_title']) ?></div>
                        <?php endif; ?>
                        <?php
                            $vbits = [];
                            if (!empty($order['color_selected'])) $vbits[] = 'কালার: ' . $order['color_selected'];
                            if (!empty($order['size_selected'])) $vbits[] = 'সাইজ: ' . $order['size_selected'];
                            if (!empty($vbits)):
                        ?>
                            <div class="lbl-row"><?= htmlspecialchars(implode(' | ', $vbits)) ?></div>
                        <?php endif; ?>
                        <?php if ($cons !== ''): ?>
                            <div class="lbl-row lbl-cons">ID: <?= htmlspecialchars($cons) ?></div>
                        <?php endif; ?>
                        <div class="lbl-row lbl-cod">COD: <?= number_format($order['cod_amount']) ?>৳</div>
                    </div>
                    <div class="lbl-qr">
                        <div class="qrbox" data-qr="<?= htmlspecialchars($qr_phone, ENT_QUOTES) ?>" data-size="<?= $qr_px ?>"></div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
            <script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
            <script>
                // প্রতিটি লেবেলের ফোন নম্বরের QR তৈরি; লাইব্রেরি লোড না হলে নম্বর টেক্সটে দেখাও
                (function() {
                    function makeQRs() {
                        var boxes = document.querySelectorAll('.qrbox');
                        var ok = (typeof QRCode !== 'undefined');
                        boxes.forEach(function(b) {
                            var val = b.getAttribute('data-qr') || '';
                            var sz = parseInt(b.getAttribute('data-size')) || 70;
                            if (!val) return;
                            if (ok) {
                                try { new QRCode(b, { text: val, width: sz, height: sz, correctLevel: QRCode.CorrectLevel.M }); }
                                catch(e) { b.innerHTML = '<div style="font-size:9px;word-break:break-all;">' + val + '</div>'; }
                            } else {
                                // CDN ব্লক হলে অন্তত নম্বরটা দেখাও
                                b.innerHTML = '<div style="font-size:9px;word-break:break-all;">' + val + '</div>';
                            }
                        });
                        setTimeout(function() { window.print(); }, 250);
                    }
                    if (document.readyState === 'complete') setTimeout(makeQRs, 300);
                    else window.addEventListener('load', function() { setTimeout(makeQRs, 300); });
                })();
            </script>
        <?php else: ?>
        <?php foreach ($orders as $order): ?>
            <div class="invoice-box <?= $type === '40mm' ? 'width-40mm' : 'width-80mm' ?>">
                <div class="divider"></div>
                <div class="meta-line"><strong>অর্ডার আইডি:</strong> #<?= $order['id'] ?></div>

                <?php if ($show_name): ?>
                    <div class="meta-line"><strong>গ্রাহক:</strong> <?= htmlspecialchars($order['customer_name']) ?></div>
                <?php endif; ?>

                <?php if ($show_phone): ?>
                    <div class="meta-line"><strong>ফোন:</strong> <?= htmlspecialchars($order['phone']) ?></div>
                <?php endif; ?>

                <?php if ($show_address): ?>
                    <div class="meta-line"><strong>ঠিকানা:</strong> <?= htmlspecialchars($order['address']) ?></div>
                <?php endif; ?>

                <?php if ($show_product && $order['product_title']): ?>
                    <div class="meta-line"><strong>পণ্য:</strong> <?= htmlspecialchars($order['product_title']) ?></div>
                <?php endif; ?>

                <?php if ($show_color && $order['color_selected']): ?>
                    <div class="meta-line"><strong>কালার:</strong> <?= htmlspecialchars($order['color_selected']) ?></div>
                <?php endif; ?>

                <?php if ($show_color && !empty($order['size_selected'])): ?>
                    <div class="meta-line"><strong>সাইজ:</strong> <?= htmlspecialchars($order['size_selected']) ?></div>
                <?php endif; ?>

                <?php if ($show_color && !empty($order['weight_selected'])): ?>
                    <div class="meta-line"><strong>ওজন:</strong> <?= htmlspecialchars($order['weight_selected']) ?></div>
                <?php endif; ?>

                <?php if ($show_consignment && $order['consignment_id']): ?>
                    <div class="meta-line"><strong>কনসাইনমেন্ট আইডি:</strong> <?= htmlspecialchars($order['consignment_id']) ?></div>
                <?php endif; ?>

                <div class="divider"></div>

                <?php if ($show_cod): ?>
                    <div class="price-total">COD পরিমাণ: <?= number_format($order['cod_amount'], 2) ?> ৳</div>
                <?php endif; ?>

                <?php if ($show_footer): ?>
                    <div style="text-align: center; font-size: 9px; margin-top: 8px;">ধন্যবাদ আমাদের সাথে থাকার জন্য!</div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        <script>window.print();</script>
        <?php endif; ?>
    </body>
    </html>
    <?php
}

// -------------------------------------------------------------
// 7. PUBLIC FRONTEND RENDERERS (LANDING PAGES)
// -------------------------------------------------------------

function render_variant_blocks_html($products, $size_teen, $size_kids, $weights, $vc = null, $first_active = true) {
    // Renders one hidden/visible variant block per product. Inputs inside hidden blocks are disabled.
    // $vc: পেজ-লেভেল কাস্টম ভ্যারিয়েন্ট কনফিগ — দিলে প্রোডাক্টের নিজস্ব সেটিং অভাররাইড হয়
    $vc_weight_custom = true;
    if (is_array($vc)) {
        $size_teen = (!empty($vc['size_teen']['enabled'])) ? array_values(array_intersect($size_teen, $vc['size_teen']['options'] ?? [])) : [];
        $size_kids = (!empty($vc['size_kids']['enabled'])) ? array_values(array_intersect($size_kids, $vc['size_kids']['options'] ?? [])) : [];
        $weights   = (!empty($vc['weight']['enabled'])) ? array_values(array_intersect($weights, $vc['weight']['options'] ?? [])) : [];
        $vc_weight_custom = !empty($vc['weight']['enabled']) && !isset($vc['weight']['custom']) ? true : !empty($vc['weight']['custom']);
    }
    $html = '';
    foreach ($products as $bidx => $prod) {
        if (is_array($vc)) {
            // পেজ কনফিগ সব প্রোডাক্টের জন্য একইভাবে প্রযোজ্য
            $has_teen = !empty($size_teen);
            $has_kids = !empty($size_kids);
            $has_weight = !empty($weights) || (!empty($vc['weight']['enabled']) && $vc_weight_custom);
        } else {
            $v = json_decode($prod['variant_options'] ?? '', true) ?: [];
            $has_teen = !empty($v['size_teen']);
            $has_kids = !empty($v['size_kids']);
            $has_weight = !empty($v['weight']);
        }
        if (!$has_teen && !$has_kids && !$has_weight) continue;

        $active = ($bidx === 0 && $first_active);
        $html .= '<div class="variant-block ' . ($active ? '' : 'hidden') . '" data-for="' . (int)$prod['id'] . '">';

        if ($has_teen || $has_kids) {
            $html .= '<div class="mt-4"><label class="block text-slate-700 text-sm font-semibold mb-2"><i class="fa-solid fa-ruler text-emerald-500"></i> সাইজ নির্বাচন করুন</label>';
            $first_size = true;
            if ($has_teen) {
                $html .= '<span class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5">Teen/Adult সাইজ</span><div class="flex flex-wrap gap-2 mb-3">';
                foreach ($size_teen as $sz) {
                    $checked = ''; // কোনো ডিফল্ট সাইজ সিলেক্ট থাকবে না
                    $html .= '<label class="pill-btn size-pill"><input type="radio" name="size_selected" value="' . htmlspecialchars($sz) . '" ' . $checked . ' ' . ($active ? '' : 'disabled') . ' class="hidden-radio"><span>' . htmlspecialchars($sz) . '</span></label>';
                    $first_size = false;
                }
                $html .= '</div>';
            }
            if ($has_kids) {
                $html .= '<span class="block text-[10px] font-bold text-slate-400 uppercase tracking-widest mb-1.5">Baby/Kids সাইজ</span><div class="flex flex-wrap gap-2 mb-3">';
                foreach ($size_kids as $sz) {
                    $checked = ''; // কোনো ডিফল্ট সাইজ সিলেক্ট থাকবে না
                    $html .= '<label class="pill-btn size-pill"><input type="radio" name="size_selected" value="' . htmlspecialchars($sz) . '" ' . $checked . ' ' . ($active ? '' : 'disabled') . ' class="hidden-radio"><span>' . htmlspecialchars($sz) . '</span></label>';
                    $first_size = false;
                }
                $html .= '</div>';
            }
            $html .= '</div>';
        }

        if ($has_weight) {
            $html .= '<div class="mt-4"><label class="block text-slate-700 text-sm font-semibold mb-2"><i class="fa-solid fa-weight-hanging text-emerald-500"></i> ওজন নির্বাচন করুন</label><div class="flex flex-wrap gap-2">';
            $first_w = true;
            foreach ($weights as $w) {
                $checked = ''; // কোনো ডিফল্ট ওজন সিলেক্ট থাকবে না
                $html .= '<label class="pill-btn weight-pill"><input type="radio" name="weight_selected" value="' . htmlspecialchars($w) . '" ' . $checked . ' ' . ($active ? '' : 'disabled') . ' class="hidden-radio" onchange="toggleCustomWeight(this)"><span>' . htmlspecialchars($w) . '</span></label>';
                $first_w = false;
            }
            if ($vc_weight_custom) {
                $html .= '<label class="pill-btn weight-pill"><input type="radio" name="weight_selected" value="custom" ' . ($active ? '' : 'disabled') . ' class="hidden-radio" onchange="toggleCustomWeight(this)"><span>Custom (kg)</span></label>';
            }
            $html .= '</div>';
            $html .= '<div class="weight-custom-wrap hidden mt-3"><input type="number" step="0.01" min="0" name="weight_custom" ' . ($active ? '' : 'disabled') . ' placeholder="কাস্টম ওজন লিখুন (kg)" class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:border-emerald-500 transition text-sm"></div>';
            $html .= '</div>';
        }

        $html .= '</div>';
    }
    return $html;
}

function render_landing_shared_css() {
    ?>
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .animate-fade-in {
            animation: fadeIn 0.3s ease-out forwards;
        }
        .hidden-radio { position: absolute; opacity: 0; pointer-events: none; }
        .pill-btn {
            display: inline-flex; align-items: center; gap: 6px;
            background: #ffffff; color: #111827;
            border: 2px solid #d1d5db; border-radius: 9999px;
            padding: 7px 16px; font-size: 12px; font-weight: 700;
            cursor: pointer; user-select: none;
            transition: all .18s ease; position: relative;
        }
        .pill-btn:hover { border-color: #10b981; }
        .pill-btn.active { background: #059669; color: #ffffff; border-color: #059669; box-shadow: 0 4px 10px rgba(5,150,105,.3); }
        .color-btn .color-dot {
            width: 14px; height: 14px; border-radius: 9999px;
            border: 1px solid rgba(0,0,0,.2); display: inline-block; flex-shrink: 0;
        }
        .color-btn.active { color: #ffffff; box-shadow: 0 4px 12px rgba(0,0,0,.25); }
        .color-btn.active.light-color { color: #111827; }
    </style>
    <?php
}

function render_landing_shared_variant_js() {
    ?>
    <script>
        function refreshPillButtons() {
            document.querySelectorAll('.pill-btn').forEach(function(lbl) {
                const inp = lbl.querySelector('input[type="radio"]');
                if (!inp) return;
                if (inp.checked && !inp.disabled) {
                    lbl.classList.add('active');
                    if (lbl.classList.contains('color-btn')) {
                        const hex = lbl.dataset.hex || '#059669';
                        lbl.style.background = hex;
                        lbl.style.borderColor = hex;
                        if (isLightHex(hex)) { lbl.classList.add('light-color'); } else { lbl.classList.remove('light-color'); }
                    }
                } else {
                    lbl.classList.remove('active', 'light-color');
                    if (lbl.classList.contains('color-btn')) {
                        lbl.style.background = '#ffffff';
                        lbl.style.borderColor = '#d1d5db';
                    }
                }
            });
        }
        function isLightHex(hex) {
            try {
                hex = hex.replace('#','');
                if (hex.length === 3) hex = hex.split('').map(c => c + c).join('');
                const r = parseInt(hex.substr(0,2),16), g = parseInt(hex.substr(2,2),16), b = parseInt(hex.substr(4,2),16);
                return ((r*299 + g*587 + b*114) / 1000) > 165;
            } catch (e) { return false; }
        }
        function toggleCustomWeight(radio) {
            const block = radio.closest('.variant-block') || document;
            const wrap = block.querySelector('.weight-custom-wrap');
            if (!wrap) return;
            if (radio.value === 'custom' && radio.checked) {
                wrap.classList.remove('hidden');
            } else {
                wrap.classList.add('hidden');
            }
        }
        document.addEventListener('change', function(e) {
            if (e.target && e.target.classList && e.target.classList.contains('hidden-radio')) {
                refreshPillButtons();
            }
        });
    </script>
    <?php
}

function render_dynamic_landing_page($page) {
    global $db;

    $fb_pixel = get_setting('facebook_pixel');
    $tt_pixel = get_setting('tiktok_pixel');
    $gtag = get_setting('google_tag');

    $fields = json_decode($page['checkout_fields'] ?? '', true);
    if (empty($fields)) {
        $fields = json_decode(get_setting('checkout_fields'), true) ?: [];
    }

    $colors = json_decode(get_setting('product_colors'), true) ?: [];
    $size_teen = json_decode(get_setting('size_teen_options'), true) ?: [];
    $size_kids = json_decode(get_setting('size_kids_options'), true) ?: [];
    $weights = json_decode(get_setting('weight_options'), true) ?: [];

    // এই পেজের কাস্টম ভ্যারিয়েন্ট কনফিগ (থাকলে)
    $vc = json_decode($page['variant_config'] ?? '', true);
    if (!is_array($vc)) $vc = null;
    if ($vc) {
        if (empty($vc['colors']['enabled'])) {
            $fields['color'] = false; // এই পেজে কালার সিলেক্টর বন্ধ
        } else {
            $allowed_colors = $vc['colors']['options'] ?? [];
            $colors = array_values(array_filter($colors, function ($c) use ($allowed_colors) {
                return in_array($c['en'], $allowed_colors);
            }));
            if (empty($colors)) $fields['color'] = false;
        }
    }

    $product_ids = json_decode($page['product_ids'] ?? '[]', true);
    $products = [];
    if (!empty($product_ids)) {
        $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
        $stmt = $db->prepare("SELECT * FROM products WHERE id IN ($placeholders)");
        $stmt->execute(array_values($product_ids));
        $fetched = $stmt->fetchAll();
        // সেভ করা ক্রম (ড্র্যাগ এন্ড ড্রপ অর্ডার) অনুযায়ী প্রোডাক্ট সাজানো
        $by_id = [];
        foreach ($fetched as $fp) { $by_id[(int)$fp['id']] = $fp; }
        $products = [];
        foreach ($product_ids as $pid) {
            if (isset($by_id[(int)$pid])) $products[] = $by_id[(int)$pid];
        }
    } else {
        $products = $db->query("SELECT * FROM products ORDER BY id DESC LIMIT 3")->fetchAll();
    }

    $brand_name = branding('site_name') ?: 'SunnahTi';
    $brand_home = branding('home_url') ?: '#';
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($page['seo_title'] ?: ($page['title'] . ' - ' . (branding('site_title') ?: $brand_name))) ?></title>
        <meta name="description" content="<?= htmlspecialchars($page['seo_desc']) ?>">
        <?php
        // সোশাল শেয়ার (OG) মেটা — পেজের নিজস্ব ইমেজ, না থাকলে সেটিংসের ডিফল্ট
        $og_img = trim((string)($page['og_image'] ?? '')) ?: trim((string)get_setting('og_default_image'));
        $og_url = base_url() . '/?action=view&slug=' . urlencode($page['slug']);
        ?>
        <meta property="og:type" content="website">
        <meta property="og:title" content="<?= htmlspecialchars($page['seo_title'] ?: $page['title']) ?>">
        <meta property="og:description" content="<?= htmlspecialchars($page['seo_desc'] ?: ('অর্ডার করুন — ' . $brand_name)) ?>">
        <meta property="og:url" content="<?= htmlspecialchars($og_url) ?>">
        <meta property="og:site_name" content="<?= htmlspecialchars($brand_name) ?>">
        <?php if ($og_img): ?>
        <meta property="og:image" content="<?= htmlspecialchars($og_img) ?>">
        <meta property="og:image:width" content="1200">
        <meta property="og:image:height" content="630">
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:image" content="<?= htmlspecialchars($og_img) ?>">
        <?php endif; ?>
        <?= render_favicon_tag() ?>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php render_landing_shared_css(); ?>

        <?php if ($fb_pixel): ?>
        <script>
            !function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
            if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
            n.queue=[];t=b.createElement(e);t.async=!0;
            t.src=v;s=b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t,s)}(window, document,'script',
            'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', '<?= $fb_pixel ?>');
            fbq('track', 'PageView');
        </script>
        <?php endif; ?>

        <?php if ($tt_pixel): ?>
        <script>
            !function (w, d, t) {
              w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","trackWithSegment","setAndTrack","load","unset","trackLocal"],ttq.setAndTrack=function(t,e,n){t[e]=n},ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndTrack(e,ttq.methods[n],e[t+"."+ttq.methods[n]]);return e},ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=d.createElement("script");o.type="text/javascript",o.async=!0,o.src=r+"?sdkid="+e+"&lib="+t;var a=d.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
              ttq.load('<?= $tt_pixel ?>');
              ttq.page();
            }(window, document, 'ttq');
        </script>
        <?php endif; ?>

        <?php if ($gtag): ?>
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?= $gtag ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?= $gtag ?>');
        </script>
        <?php endif; ?>
    </head>
    <body class="bg-gray-50 text-gray-800">

        <div class="landing-main-content">
            <?= $page['content'] ?>
        </div>

        <section id="landingCheckoutSec" class="py-12 bg-slate-100 border-t border-slate-200">
            <div class="max-w-2xl mx-auto px-4">
                <div class="bg-white p-6 lg:p-8 rounded-3xl shadow-xl border border-gray-100">
                    <div class="text-center mb-6 border-b border-gray-100 pb-4">
                        <span class="text-xs bg-emerald-100 text-emerald-800 px-3 py-1 rounded-full font-bold uppercase tracking-wide">সীমিত সময়ের অফার</span>
                        <h3 class="text-xl lg:text-2xl font-bold text-slate-900 flex items-center justify-center gap-2 mt-2">
                            <i class="fa-solid fa-credit-card text-emerald-500"></i>  ডেলিভারি পেতে নিচের ফর্মটি পূরণ করুন
                        </h3>
                        <p class="text-xs text-gray-500 mt-1">সরাসরি ক্যাশ অন ডেলিভারি সুবিধা (পণ্য হাতে পেয়ে টাকা পরিশোধ করবেন)।</p>
                    </div>

                    <form id="landingCheckout" class="space-y-6">
                        <input type="hidden" name="incomplete_token" id="incompleteToken" value="">
                        <input type="hidden" name="page_slug" value="<?= htmlspecialchars($page['slug']) ?>">
                        <?php $is_multi = !empty($page['multi_product']); ?>
                        <div>
                            <label class="block text-slate-900 text-sm font-extrabold mb-3 flex items-center gap-2">
                                <i class="fa-solid fa-basket-shopping text-emerald-500"></i> <?= $is_multi ? 'আপনার পছন্দের পণ্যগুলো বাছুন ও পরিমাণ দিন:' : 'আপনার পছন্দের পণ্যটি নির্বাচন করুন:' ?>
                            </label>

                            <?php if ($is_multi): // ==== মাল্টি-প্রোডাক্ট মোড: চেকবক্স + কোয়ান্টিটি ==== ?>
                            <div class="space-y-3" id="multiProductList">
                                <?php foreach ($products as $idx => $prod): $price_display = $prod['sale_price'] ?: $prod['price']; ?>
                                    <div class="mp-item border-2 border-gray-200 bg-white rounded-2xl p-4 flex items-center gap-3 transition" data-pid="<?= $prod['id'] ?>" data-price="<?= $price_display ?>">
                                        <input type="checkbox" class="mp-check h-5 w-5 text-emerald-500 rounded" onchange="mpRecalc()">
                                        <?php if ($prod['image_url']): ?><img src="<?= htmlspecialchars($prod['image_url']) ?>" class="w-12 h-12 object-cover rounded-lg flex-shrink-0" alt="product"><?php endif; ?>
                                        <div class="flex-grow min-w-0">
                                            <span class="block text-sm font-bold text-slate-800 leading-tight"><?= htmlspecialchars($prod['title']) ?></span>
                                            <span class="block text-sm font-extrabold text-emerald-600 mt-0.5"><?= number_format($price_display) ?> ৳</span>
                                        </div>
                                        <div class="flex items-center gap-1 flex-shrink-0">
                                            <button type="button" onclick="mpQty(this,-1)" class="w-7 h-7 rounded-lg bg-gray-100 text-gray-700 font-bold">−</button>
                                            <input type="number" min="1" value="1" class="mp-qty w-12 text-center border border-gray-300 rounded-lg py-1 text-sm" oninput="mpRecalc()">
                                            <button type="button" onclick="mpQty(this,1)" class="w-7 h-7 rounded-lg bg-gray-100 text-gray-700 font-bold">+</button>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="mt-3 bg-emerald-50 border border-emerald-200 rounded-xl px-4 py-2.5 flex items-center justify-between">
                                <span class="text-xs font-bold text-slate-700">সর্বমোট পণ্যের দাম:</span>
                                <span class="text-lg font-extrabold text-emerald-600" id="mpTotal">০ ৳</span>
                            </div>
                            <input type="hidden" name="order_items" id="mpItemsJson" value="">
                            <input type="hidden" name="product_id" id="mpMainProduct" value="">
                            <?php else: // ==== একক প্রোডাক্ট মোড (আগের মতো) ==== ?>
                            <div class="space-y-3">
                                <?php foreach ($products as $idx => $prod):
                                    $price_display = $prod['sale_price'] ?: $prod['price'];
                                    ?>
                                    <label class="border-2 rounded-2xl p-4 flex items-center gap-4 cursor-pointer transition select-none hover:border-emerald-500 hover:bg-emerald-50/20 relative block
                                        <?= $idx === 0 ? 'border-emerald-500 bg-emerald-50/10' : 'border-gray-200 bg-white' ?>"
                                        onclick="updateSelectedProduct(this, <?= $price_display ?>, <?= $prod['id'] ?>)">
                                        <input type="radio" name="product_id" value="<?= $prod['id'] ?>" required class="text-emerald-500 focus:ring-emerald-500 h-4 w-4">

                                        <?php if ($prod['image_url']): ?>
                                            <img src="<?= htmlspecialchars($prod['image_url']) ?>" class="w-12 h-12 object-cover rounded-lg flex-shrink-0" alt="product">
                                        <?php endif; ?>

                                        <div class="flex-grow">
                                            <span class="block text-sm font-bold text-slate-800 leading-tight"><?= htmlspecialchars($prod['title']) ?></span>
                                            <span class="block text-xs text-slate-500 mt-0.5 truncate max-w-[280px]"><?= htmlspecialchars($prod['description'] ?? '') ?></span>
                                        </div>

                                        <div class="text-right">
                                            <span class="block text-sm font-extrabold text-emerald-600"><?= number_format($price_display) ?> ৳</span>
                                            <?php if ($prod['sale_price']): ?>
                                                <span class="block text-[10px] text-gray-400 line-through"><?= number_format($prod['price']) ?> ৳</span>
                                            <?php endif; ?>
                                        </div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <?= render_variant_blocks_html($products, $size_teen, $size_kids, $weights, $vc, false) ?>

                        <div class="space-y-4 pt-4 border-t border-gray-150">
                            <?php if (!isset($fields['name']) || $fields['name']): ?>
                            <div>
                                <label class="block text-slate-700 text-xs font-bold mb-1">আপনার নাম (আবশ্যিক)</label>
                                <input type="text" name="customer_name" required placeholder="আপনার সম্পূর্ণ নাম লিখুন" class="w-full border border-gray-300 rounded-xl px-4 py-2.5 focus:outline-none focus:border-emerald-500 transition text-xs">
                            </div>
                            <?php endif; ?>

                            <?php if (!isset($fields['phone']) || $fields['phone']): ?>
                            <div>
                                <label class="block text-slate-700 text-sm font-semibold mb-1">১১ ডিজিটের মোবাইল নম্বর (আবশ্যিক)</label>
                                <input type="text" name="phone" required placeholder="০১৭XXXXXXXX" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                            </div>
                            <?php endif; ?>

                            <?php if (!isset($fields['alt_phone']) || $fields['alt_phone']): ?>
                            <div>
                                <label class="block text-slate-700 text-sm font-semibold mb-1">বিকল্প মোবাইল নম্বর (ঐচ্ছিক)</label>
                                <input type="text" name="alternative_phone" placeholder="যদি থাকে" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                            </div>
                            <?php endif; ?>

                            <?php if (!isset($fields['address']) || $fields['address']): ?>
                            <div>
                                <label class="block text-slate-700 text-sm font-semibold mb-1">সম্পূর্ণ ঠিকানা (আবশ্যিক)</label>
                                <textarea name="address" required placeholder="জেলা, থানা, রোড নং, বাড়ির নাম উল্লেখ করুন" rows="3" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm"></textarea>
                            </div>
                            <?php endif; ?>

                            <?php if ((!isset($fields['color']) || $fields['color']) && !empty($colors)): ?>
                            <div>
                                <label class="block text-slate-700 text-sm font-semibold mb-1">পছন্দের কালার নির্বাচন করুন</label>
                                <div class="flex flex-wrap gap-2">
                                    <?php foreach ($colors as $cidx => $c): ?>
                                        <label class="pill-btn color-btn" data-hex="<?= htmlspecialchars(color_hex($c['en'])) ?>">
                                            <input type="radio" name="color_selected" value="<?= htmlspecialchars($c['en']) ?>" class="hidden-radio">
                                            <span class="color-dot" style="background: <?= htmlspecialchars(color_hex($c['en'])) ?>;"></span>
                                            <span><?= htmlspecialchars($c['bn'] ?: $c['en']) ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if (!isset($fields['note']) || $fields['note']): ?>
                            <div>
                                <label class="block text-slate-700 text-sm font-semibold mb-1">বিশেষ নির্দেশাবলী (ঐচ্ছিক)</label>
                                <input type="text" name="note" placeholder="যেমন: দুপুর ৩টার পর ডেলিভারি দিন" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                            </div>
                            <?php endif; ?>
                        </div>

                        <div id="formResponse" class="hidden p-3 rounded-xl text-center text-xs font-semibold"></div>

                        <?php
                            $default_price = !empty($products) ? ($products[0]['sale_price'] ?: $products[0]['price']) : 0;
                        ?>
<?php
                        // ---- ডেলিভারি এলাকা (কুরিয়ার চার্জ) + প্রোমো কোড + অর্ডার সামারি ----
                        $ord_price_map = [];
                        if (isset($products) && is_array($products)) {
                            foreach ($products as $opm) $ord_price_map[(int)$opm['id']] = (float)(($opm['sale_price'] !== null && $opm['sale_price'] > 0) ? $opm['sale_price'] : $opm['price']);
                        } elseif (isset($product) && is_array($product)) {
                            $ord_price_map[(int)$product['id']] = (float)(($product['sale_price'] !== null && $product['sale_price'] > 0) ? $product['sale_price'] : $product['price']);
                        }
                        $ord_has_zone = !empty($fields['courier_charge']);
                        $ord_has_promo = !empty($fields['promo_code']);
                        if ($ord_has_zone):
                            $chg_map = [
                                'dhaka' => (int)(get_setting('courier_charge_dhaka') ?: 60),
                                'sub_dhaka' => (int)(get_setting('courier_charge_sub_dhaka') ?: 100),
                                'outside' => (int)(get_setting('courier_charge_outside') ?: 130),
                            ];
                        ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2"><i class="fa-solid fa-truck-fast text-emerald-500"></i> ডেলিভারি এলাকা সিলেক্ট করুন <span class="text-rose-500">*</span></label>
                            <input type="hidden" name="courier_charge_on" value="1">
                            <div class="grid grid-cols-1 gap-2">
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="dhaka" data-charge="<?= $chg_map['dhaka'] ?>" class="text-emerald-500 h-4 w-4"> ঢাকার মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['dhaka']) ?></span>
                                </label>
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="sub_dhaka" data-charge="<?= $chg_map['sub_dhaka'] ?>" class="text-emerald-500 h-4 w-4"> সাব ঢাকার মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['sub_dhaka']) ?></span>
                                </label>
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="outside" data-charge="<?= $chg_map['outside'] ?>" class="text-emerald-500 h-4 w-4"> সারা বাংলাদেশের মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['outside']) ?></span>
                                </label>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($ord_has_promo): ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1"><i class="fa-solid fa-ticket text-fuchsia-500"></i> প্রোমো কোড (থাকলে)</label>
                            <div class="flex gap-2">
                                <input type="text" id="promoInput" placeholder="যেমন: EID10" class="flex-1 bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-800 outline-none focus:border-fuchsia-500 font-mono uppercase">
                                <button type="button" id="applyPromoBtn" onclick="ordApplyPromo()" class="bg-fuchsia-600 hover:bg-fuchsia-500 text-white text-sm font-bold px-5 rounded-xl transition whitespace-nowrap">অ্যাপ্লাই</button>
                            </div>
                            <input type="hidden" name="promo_code" id="promoCodeHidden" value="">
                            <p id="promoMsg" class="hidden text-xs font-bold mt-1.5"></p>
                        </div>
                        <?php endif; ?>

                        <?php if ($ord_has_zone || $ord_has_promo): ?>
                        <div id="ordSummary" class="hidden bg-slate-50 border-2 border-slate-200 rounded-2xl p-4 space-y-1.5 text-sm">
                            <div class="flex justify-between text-slate-600"><span>প্রোডাক্টের মূল্য</span><span id="sumPrice" class="font-bold">৳0</span></div>
                            <div id="sumDiscRow" class="hidden flex justify-between text-fuchsia-600"><span>প্রোমো ছাড় (<span id="sumDiscCode"></span>)</span><span id="sumDisc" class="font-bold">−৳0</span></div>
                            <div id="sumChgRow" class="hidden flex justify-between text-slate-600"><span>ডেলিভারি চার্জ</span><span id="sumChg" class="font-bold">+৳0</span></div>
                            <div class="flex justify-between border-t-2 border-slate-200 pt-2 text-slate-900 font-extrabold text-base"><span>মোট (ক্যাশ অন ডেলিভারি)</span><span id="sumTotal" class="text-emerald-600">৳0</span></div>
                        </div>
                        <script>
                            window.ORD_PRICES = <?= json_encode($ord_price_map) ?>;
                            window.ORD_DISCOUNT = 0;
                            window.ORD_DISC_CODE = '';
                            function ordBasePrice() {
                                const r = document.querySelector('input[name="product_id"]:checked') || document.querySelector('input[type="hidden"][name="product_id"]');
                                if (!r) return 0;
                                return parseFloat(window.ORD_PRICES[r.value] || 0);
                            }
                            function ordCalcUpdate() {
                                const price = ordBasePrice();
                                const disc = Math.min(window.ORD_DISCOUNT || 0, price);
                                const zr = document.querySelector('input[name="delivery_zone"]:checked');
                                const chg = zr ? parseFloat(zr.dataset.charge || 0) : 0;
                                const box = document.getElementById('ordSummary');
                                if (!box) return;
                                if (price <= 0 && disc <= 0 && chg <= 0) { box.classList.add('hidden'); return; }
                                box.classList.remove('hidden');
                                document.getElementById('sumPrice').textContent = '৳' + price.toLocaleString('bn-BD');
                                const dr = document.getElementById('sumDiscRow');
                                if (disc > 0) { dr.classList.remove('hidden'); dr.classList.add('flex'); document.getElementById('sumDisc').textContent = '−৳' + disc.toLocaleString('bn-BD'); document.getElementById('sumDiscCode').textContent = window.ORD_DISC_CODE; }
                                else { dr.classList.add('hidden'); dr.classList.remove('flex'); }
                                const cr = document.getElementById('sumChgRow');
                                if (zr) { cr.classList.remove('hidden'); cr.classList.add('flex'); document.getElementById('sumChg').textContent = '+৳' + chg.toLocaleString('bn-BD'); }
                                else { cr.classList.add('hidden'); cr.classList.remove('flex'); }
                                document.getElementById('sumTotal').textContent = '৳' + Math.max(0, price - disc + chg).toLocaleString('bn-BD');
                            }
                            document.addEventListener('change', function (e) {
                                if (e.target && (e.target.name === 'product_id' || e.target.name === 'delivery_zone')) ordCalcUpdate();
                            });
                            function ordApplyPromo() {
                                const inp = document.getElementById('promoInput');
                                const msg = document.getElementById('promoMsg');
                                const hid = document.getElementById('promoCodeHidden');
                                const code = (inp.value || '').trim().toUpperCase();
                                if (!code) { msg.className = 'text-xs font-bold mt-1.5 text-rose-600'; msg.textContent = 'প্রোমো কোড লিখুন'; return; }
                                const r = document.querySelector('input[name="product_id"]:checked') || document.querySelector('input[type="hidden"][name="product_id"]');
                                const fd = new FormData();
                                fd.append('code', code);
                                fd.append('product_id', r ? r.value : 0);
                                document.getElementById('applyPromoBtn').disabled = true;
                                fetch('?action=apply_promo', { method: 'POST', body: fd })
                                    .then(res => res.json())
                                    .then(d => {
                                        document.getElementById('applyPromoBtn').disabled = false;
                                        if (d.status === 'success') {
                                            hid.value = d.code;
                                            window.ORD_DISCOUNT = parseFloat(d.discount || 0);
                                            window.ORD_DISC_CODE = d.code;
                                            msg.className = 'text-xs font-bold mt-1.5 text-emerald-600';
                                            msg.textContent = '✓ ' + d.message + (d.label ? ' (' + d.label + ')' : '');
                                        } else {
                                            hid.value = '';
                                            window.ORD_DISCOUNT = 0; window.ORD_DISC_CODE = '';
                                            msg.className = 'text-xs font-bold mt-1.5 text-rose-600';
                                            msg.textContent = '✕ ' + (d.message || 'প্রোমো কোডটি সঠিক নয়');
                                        }
                                        ordCalcUpdate();
                                    })
                                    .catch(() => {
                                        document.getElementById('applyPromoBtn').disabled = false;
                                        msg.className = 'text-xs font-bold mt-1.5 text-rose-600';
                                        msg.textContent = 'নেটওয়ার্ক সমস্যা — আবার চেষ্টা করুন';
                                    });
                            }
                        </script>
                        <?php endif; ?>

                        <?php $cf_label = trim((string)($fields['custom_field_label'] ?? ''));
                        if (!empty($fields['custom_field']) && $cf_label !== ''): ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1"><?= htmlspecialchars($cf_label) ?> <span class="text-rose-500">*</span></label>
                            <input type="text" name="custom_field_value" required class="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-800 outline-none focus:border-emerald-500" placeholder="এখানে লিখুন...">
                            <input type="hidden" name="custom_field_label" value="<?= htmlspecialchars($cf_label) ?>">
                        </div>
                        <?php endif; ?>

                        <!-- এডভান্স পেমেন্ট বক্স (হাই-রিস্ক কাস্টমারের জন্য, সার্ভার বললে দেখায়) -->
                        <div id="advanceBox" class="hidden bg-amber-50 border-2 border-amber-400 rounded-2xl p-4 space-y-3">
                            <p id="advanceMsg" class="text-sm font-bold text-amber-800 leading-relaxed"></p>
                            <div id="advanceNumbers" class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm"></div>
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1">ট্রানজেকশন আইডি (TrxID)</label>
                                <input type="text" name="advance_trx" placeholder="যেমন: 9H7XXXXXXX" class="w-full bg-white border border-amber-300 rounded-xl px-3 py-2.5 text-slate-800 outline-none focus:border-amber-500 font-mono">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-700 mb-1">অথবা পেমেন্টের স্ক্রিনশট দিন</label>
                                <input type="file" name="advance_screenshot" accept="image/*" class="w-full bg-white border border-amber-300 rounded-xl px-3 py-2 text-slate-600 text-xs">
                            </div>
                            <p class="text-[11px] text-amber-700">💡 সেন্ড মানি করার পর TrxID অথবা স্ক্রিনশট — যেকোনো একটা দিয়ে আবার "অর্ডার নিশ্চিত করুন" বাটনে ক্লিক করুন।</p>
                        </div>

                        <?php $cf_label = trim((string)($fields['custom_field_label'] ?? ''));
                        if (!empty($fields['custom_field']) && $cf_label !== ''): ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1"><?= htmlspecialchars($cf_label) ?> <span class="text-rose-500">*</span></label>
                            <input type="text" name="custom_field_value" required class="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-800 outline-none focus:border-emerald-500" placeholder="এখানে লিখুন...">
                            <input type="hidden" name="custom_field_label" value="<?= htmlspecialchars($cf_label) ?>">
                        </div>
                        <?php endif; ?>
                    <button type="submit" id="submitBtn" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-lg py-4 rounded-2xl transition shadow-xl flex items-center justify-center gap-2">
                            <i class="fa-solid fa-lock"></i> <span id="btnText">অর্ডার নিশ্চিত করুন</span> - <span id="priceLabel"><?= number_format($default_price) ?></span> ৳
                        </button>
                    </form>
                </div>
            </div>
        </section>

        <?php if (!empty($page['bottom_content'])): ?>
        <div class="landing-bottom-content">
            <?= $page['bottom_content'] ?>
        </div>
        <?php endif; ?>

        <div id="successModal" class="hidden fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-fade-in">
            <div class="bg-white rounded-3xl p-6 lg:p-8 max-w-lg w-full shadow-2xl border border-gray-100 transform scale-95 transition-all duration-300 text-center relative">
                <div class="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa-solid fa-circle-check text-4xl text-emerald-500"></i>
                </div>
                <h3 class="text-2xl font-extrabold text-slate-950 mb-1">অর্ডার সফল হয়েছে!</h3>
                <h4 class="text-base font-bold text-emerald-600 mb-4">ধন্যবাদ আমাদের সাথে থাকার জন্য!</h4>

                <div class="bg-slate-50 rounded-2xl p-4 text-left text-xs text-slate-700 mb-6 space-y-2.5 border border-slate-200">
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">অর্ডার আইডি:</strong> <span id="modalOrderId" class="font-mono font-bold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">গ্রাহক:</strong> <span id="modalCustName" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">মোবাইল নম্বর:</strong> <span id="modalCustPhone" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">পণ্য:</strong> <span id="modalProdTitle" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalColorRow"><strong class="text-slate-900">কালার:</strong> <span id="modalColor" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalSizeRow" style="display:none;"><strong class="text-slate-900">সাইজ:</strong> <span id="modalSize" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalWeightRow" style="display:none;"><strong class="text-slate-900">ওজন:</strong> <span id="modalWeight" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between pt-1"><strong class="text-slate-900">মোট মূল্য:</strong> <span id="modalTotalPrice" class="font-extrabold text-emerald-600 text-sm"></span></div>
                </div>

                <p class="text-xs lg:text-sm text-slate-600 font-medium leading-relaxed mb-4">
                    আমাদের কাস্টমার কেয়ার প্রতিনিধি আপনাকে কল দিয়ে অর্ডারটি কনফার্ম করবে আগামী ১২ ঘণ্টার মধ্যে অনুগ্রহ করে <br> অপেক্ষা করুন
                </p>

                <?php if (trim(get_setting('support_whatsapp')) !== ''): ?>
                <a id="successWaBtn" href="#" target="_blank" class="w-full bg-[#25D366] hover:bg-[#1eb955] text-white font-extrabold text-sm py-3 rounded-xl transition shadow-lg flex items-center justify-center gap-2 mb-3">
                    <i class="fa-brands fa-whatsapp text-lg"></i> WhatsApp-এ অর্ডারের স্ক্রিনশট পাঠান
                </a>
                <p class="text-[11px] text-slate-400 mb-4 -mt-1">অর্ডারের একটি স্ক্রিনশট নিয়ে আমাদের WhatsApp-এ পাঠালে দ্রুত কনফার্ম করা সহজ হয়।</p>
                <?php endif; ?>

                <button onclick="closeSuccessModalAndReload()" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-sm py-3 rounded-xl transition shadow-lg">
                    ঠিক আছে
                </button>
            </div>
        </div>

        <footer class="bg-white border-t border-gray-100 py-6 text-center text-xs text-slate-400">
            &copy; <?= date('Y') ?> <a href="<?= htmlspecialchars($brand_home) ?>" class="hover:text-emerald-500 transition"><?= htmlspecialchars($brand_name) ?></a>. All rights reserved. Powered by <?= htmlspecialchars($brand_name) ?> ERP Engine v3.0
        <?php render_floating_contact_icons(!isset($fields['wa_icon']) || $fields['wa_icon'], !isset($fields['call_icon']) || $fields['call_icon']); ?>
        </footer>

        <?php render_landing_shared_variant_js(); ?>
        <script>
            function updateSelectedProduct(label, price, productId) {
                const containers = label.parentElement.children;
                for (let c of containers) {
                    c.classList.remove('border-emerald-500', 'bg-emerald-50/10');
                    c.classList.add('border-gray-200', 'bg-white');
                }

                label.classList.remove('border-gray-200', 'bg-white');
                label.classList.add('border-emerald-500', 'bg-emerald-50/10');

                label.querySelector('input[type="radio"]').checked = true;
                document.getElementById('priceLabel').innerText = price.toLocaleString('en-US');

                // Toggle variant blocks: only the selected product's block stays active
                document.querySelectorAll('.variant-block').forEach(function(block) {
                    const isMine = parseInt(block.dataset.for) === parseInt(productId);
                    block.classList.toggle('hidden', !isMine);
                    block.querySelectorAll('input').forEach(function(inp) {
                        inp.disabled = !isMine;
                    });
                    if (isMine) {
                        // কোনো ডিফল্ট সিলেকশন হবে না — কাস্টমার নিজে বেছে নেবে
                        const checkedW = block.querySelector('input[name="weight_selected"]:checked');
                        const wrap = block.querySelector('.weight-custom-wrap');
                        if (wrap) wrap.classList.toggle('hidden', !(checkedW && checkedW.value === 'custom'));
                    }
                });
                refreshPillButtons();
            }

            // ==== মাল্টি-প্রোডাক্ট ল্যান্ডিং লজিক ====
            function mpQty(btn, delta) {
                const row = btn.closest('.mp-item');
                const q = row.querySelector('.mp-qty');
                let v = (parseInt(q.value) || 1) + delta;
                if (v < 1) v = 1;
                q.value = v;
                const chk = row.querySelector('.mp-check');
                if (delta > 0 && !chk.checked) chk.checked = true;
                mpRecalc();
            }
            function mpRecalc() {
                const rows = document.querySelectorAll('#multiProductList .mp-item');
                if (!rows.length) return;
                let items = [], total = 0;
                rows.forEach(function(r) {
                    const chk = r.querySelector('.mp-check');
                    const price = parseFloat(r.dataset.price) || 0;
                    const qty = parseInt(r.querySelector('.mp-qty').value) || 1;
                    r.classList.toggle('border-emerald-500', chk.checked);
                    r.classList.toggle('bg-emerald-50/10', chk.checked);
                    r.classList.toggle('border-gray-200', !chk.checked);
                    if (chk.checked) {
                        items.push({ product_id: parseInt(r.dataset.pid), qty: qty });
                        total += price * qty;
                    }
                });
                const mpTotalEl = document.getElementById('mpTotal');
                if (mpTotalEl) mpTotalEl.innerText = total.toLocaleString('en-US') + ' ৳';
                const mpJson = document.getElementById('mpItemsJson');
                if (mpJson) mpJson.value = JSON.stringify(items);
                const mpMain = document.getElementById('mpMainProduct');
                if (mpMain) mpMain.value = items.length ? items[0].product_id : '';
                const pl = document.getElementById('priceLabel');
                if (pl) pl.innerText = total.toLocaleString('en-US');
            }

            function closeSuccessModalAndReload() {
                window.location.reload();
            }

            // ---- Incomplete Order Capture Engine ----
            let incToken = localStorage.getItem('st_inc_token');
            if (!incToken) {
                incToken = 'tk_' + Date.now() + '_' + Math.random().toString(36).substr(2, 10);
                localStorage.setItem('st_inc_token', incToken);
            }
            document.getElementById('incompleteToken').value = incToken;

            let incTimer = null;
            function captureIncomplete() {
                clearTimeout(incTimer);
                incTimer = setTimeout(function() {
                    const form = document.getElementById('landingCheckout');
                    const fd = new FormData(form);
                    const name = (fd.get('customer_name') || '').toString().trim();
                    const phone = (fd.get('phone') || '').toString().trim();
                    const address = (fd.get('address') || '').toString().trim();
                    if (name === '' && phone === '' && address === '') return;
                    const payload = new URLSearchParams();
                    payload.set('token', incToken);
                    payload.set('customer_name', name);
                    payload.set('phone', phone);
                    payload.set('address', address);
                    payload.set('product_id', fd.get('product_id') || '0');
                    payload.set('page_slug', '<?= htmlspecialchars($page['slug']) ?>');
                    fetch('?action=save_incomplete', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: payload.toString() }).catch(function(){});
                }, 1500);
            }
            ['input', 'change'].forEach(function(evt) {
                document.getElementById('landingCheckout').addEventListener(evt, captureIncomplete);
            });

            document.getElementById('landingCheckout').addEventListener('submit', function(e) {
                e.preventDefault();
                const btn = document.getElementById('submitBtn');
                const btnText = document.getElementById('btnText');
                const resp = document.getElementById('formResponse');

                btn.disabled = true;
                btnText.innerText = 'অর্ডার প্রসেসিং হচ্ছে...';

                const formData = new FormData(this);

                // কোনো ডিফল্ট সিলেকশন নেই — তাই সাবমিটের আগে যাচাই
                const prodRadios = document.querySelectorAll('input[name="product_id"]');
                if (prodRadios.length > 1 && !document.querySelector('input[name="product_id"]:checked')) {
                    resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = 'অনুগ্রহ করে একটি প্রোডাক্ট সিলেক্ট করুন।';
                    resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    return;
                }
                const colorVisible = document.querySelector('input[name="color_selected"]');
                if (colorVisible && !document.querySelector('input[name="color_selected"]:checked')) {
                    resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = 'অনুগ্রহ করে একটি কালার সিলেক্ট করুন।';
                    resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    return;
                }
                const activeBlock = document.querySelector('.variant-block:not(.hidden)');
                if (activeBlock) {
                    const szRadios = activeBlock.querySelectorAll('input[name="size_selected"]');
                    if (szRadios.length && !activeBlock.querySelector('input[name="size_selected"]:checked')) {
                        resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'অনুগ্রহ করে সাইজ সিলেক্ট করুন।';
                        resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    const wtRadios = activeBlock.querySelectorAll('input[name="weight_selected"]');
                    if (wtRadios.length && !activeBlock.querySelector('input[name="weight_selected"]:checked')) {
                        resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'অনুগ্রহ করে ওজন সিলেক্ট করুন।';
                        resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                }

                const custName = formData.get('customer_name') || '';
                const custPhone = formData.get('phone') || '';
                const colorSelected = formData.get('color_selected') || 'N/A';
                let sizeSelected = formData.get('size_selected') || '';
                let weightSelected = formData.get('weight_selected') || '';
                if (weightSelected === 'custom') {
                    const cw = (formData.get('weight_custom') || '').toString().trim();
                    weightSelected = cw !== '' ? cw + ' kg' : '';
                }
                const selectedRadio = document.querySelector('input[name="product_id"]:checked');
                let prodTitle = '';
                if (selectedRadio) {
                    const parentLabel = selectedRadio.closest('label');
                    if (parentLabel) {
                        const titleSpan = parentLabel.querySelector('.text-slate-800') || parentLabel.querySelector('span.block.text-sm.font-bold');
                        if (titleSpan) prodTitle = titleSpan.innerText;
                    }
                }
                const totalPrice = document.getElementById('priceLabel').innerText;

                fetch('?action=submit_order', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('সার্ভার থেকে সঠিক রেসপন্স পাওয়া যায়নি (স্ট্যাটাস: ' + response.status + ')');
                    }
                    return response.text();
                })
                .then(text => {
                    let d;
                    try {
                        d = JSON.parse(text);
                    } catch (err) {
                        console.error("Non-JSON Server Output:", text);
                        throw new Error('সার্ভারে সমস্যা হয়েছে। অনুগ্রহ করে অ্যাডমিনকে কনসোল ডিবাগ চেক করতে বলুন।');
                    }

                    resp.classList.remove('hidden', 'bg-red-100', 'text-red-800', 'bg-green-100', 'text-green-800');
                    if (d.status === 'repeat_blocked') {
                        // ১ দিনে ১ বারই অর্ডার — আবার চেষ্টা করলে WhatsApp-এ যোগাযোগের বার্তা
                        resp.classList.add('bg-amber-100', 'text-amber-800');
                        let html = '<div style="font-weight:700; margin-bottom:8px;">' + d.message + '</div>';
                        if (d.wa_link) {
                            html += '<a href="' + d.wa_link + '" target="_blank" style="display:inline-flex; align-items:center; gap:8px; background:#25D366; color:#fff; font-weight:800; padding:10px 18px; border-radius:12px; text-decoration:none; margin-top:4px;"><i class="fa-brands fa-whatsapp"></i> WhatsApp-এ মেসেজ দিন</a>';
                        }
                        resp.innerHTML = html;
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    if (d.status === 'advance_required') {
                        // হাই-রিস্ক কাস্টমার: এডভান্স পেমেন্ট বক্স দেখাও
                        const advBox = document.getElementById('advanceBox');
                        document.getElementById('advanceMsg').innerText = d.message;
                        let nums = '';
                        if (d.bkash) nums += '<div style="background:#e2136e; color:#fff; border-radius:12px; padding:10px 14px; font-weight:800;">বিকাশ (সেন্ড মানি):<br><span style="font-family:monospace; font-size:17px; letter-spacing:1px;">' + d.bkash + '</span></div>';
                        if (d.nagad) nums += '<div style="background:#f6921e; color:#fff; border-radius:12px; padding:10px 14px; font-weight:800;">নগদ (সেন্ড মানি):<br><span style="font-family:monospace; font-size:17px; letter-spacing:1px;">' + d.nagad + '</span></div>';
                        if (!nums) nums = '<div style="color:#92400e; font-weight:700;">পেমেন্ট নাম্বার পেতে আমাদের হেল্পলাইনে যোগাযোগ করুন।</div>';
                        document.getElementById('advanceNumbers').innerHTML = nums;
                        advBox.classList.remove('hidden');
                        advBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'এডভান্স ' + d.amount + ' টাকা পাঠিয়ে TrxID বা স্ক্রিনশট দিয়ে আবার অর্ডার করুন।';
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    if (d.status === 'success') {
                        resp.classList.add('bg-green-100', 'text-green-800');
                        resp.innerText = d.message;

                        localStorage.removeItem('st_inc_token');

                        document.getElementById('modalOrderId').innerText = '#' + d.order_id;
                        document.getElementById('modalCustName').innerText = custName;
                        document.getElementById('modalCustPhone').innerText = custPhone;
                        document.getElementById('modalProdTitle').innerText = prodTitle || 'সিলেক্টেড পণ্য';

                        // WhatsApp বাটন: অর্ডারের তথ্য প্রি-ফিল করে সাপোর্ট নম্বরে লিংক
                        <?php $sup_wa = preg_replace('/\D/', '', bnToEnNumber(get_setting('support_whatsapp'))); if ($sup_wa !== ''): if (strlen($sup_wa) === 11 && $sup_wa[0] === '0') $sup_wa = '88' . $sup_wa; ?>
                        (function() {
                            const waBtn = document.getElementById('successWaBtn');
                            if (waBtn) {
                                const msg = 'আসসালামু আলাইকুম,\nআমি একটি অর্ডার করেছি।\n\nঅর্ডার আইডি: #' + d.order_id
                                          + '\nনাম: ' + custName
                                          + '\nমোবাইল: ' + custPhone
                                          + '\nপণ্য: ' + (prodTitle || '')
                                          + '\nমোট: ' + totalPrice + ' টাকা'
                                          + '\n\n(অর্ডারের স্ক্রিনশট এখানে যুক্ত করছি)';
                                waBtn.href = 'https://wa.me/<?= $sup_wa ?>?text=' + encodeURIComponent(msg);
                            }
                        })();
                        <?php endif; ?>

                        const colorRow = document.getElementById('modalColorRow');
                        if (colorSelected && colorSelected !== 'N/A') {
                            document.getElementById('modalColor').innerText = colorSelected;
                            colorRow.style.display = 'flex';
                        } else {
                            colorRow.style.display = 'none';
                        }
                        const sizeRow = document.getElementById('modalSizeRow');
                        if (sizeSelected) {
                            document.getElementById('modalSize').innerText = sizeSelected;
                            sizeRow.style.display = 'flex';
                        } else { sizeRow.style.display = 'none'; }
                        const weightRow = document.getElementById('modalWeightRow');
                        if (weightSelected) {
                            document.getElementById('modalWeight').innerText = weightSelected;
                            weightRow.style.display = 'flex';
                        } else { weightRow.style.display = 'none'; }
                        document.getElementById('modalTotalPrice').innerText = totalPrice + ' ৳';

                        document.getElementById('successModal').classList.remove('hidden');

                        <?php if ($fb_pixel): ?>
                        if (typeof fbq !== 'undefined') {
                            fbq('track', 'Purchase', {
                                value: parseFloat(totalPrice.replace(/,/g, '')),
                                currency: 'BDT'
                            }, { eventID: 'order_' + d.order_id });
                        }
                        <?php endif; ?>

                        <?php if ($tt_pixel): ?>
                        if (typeof ttq !== 'undefined') {
                            ttq.track('CompletePayment', {
                                value: parseFloat(totalPrice.replace(/,/g, '')),
                                currency: 'BDT'
                            }, { event_id: 'order_' + d.order_id });
                        }
                        <?php endif; ?>
                    } else {
                        resp.classList.remove('hidden');
                        resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = d.message;
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    }
                })
                .catch((error) => {
                    resp.classList.remove('hidden');
                    resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = error.message || 'সিস্টেম এরর ঘটেছে! দয়া করে আবার চেষ্টা করুন।';
                    btn.disabled = false;
                    btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                });
            });

            refreshPillButtons();
        </script>
    </body>
    </html>
    <?php
}

function render_dynamic_product_landing($product) {
    $fb_pixel = get_setting('facebook_pixel');
    $tt_pixel = get_setting('tiktok_pixel');
    $gtag = get_setting('google_tag');

    $fields = json_decode($product['checkout_fields'] ?? '', true);
    if (empty($fields)) {
        $fields = json_decode(get_setting('checkout_fields'), true) ?: [];
    }

    $colors = json_decode(get_setting('product_colors'), true) ?: [];
    $size_teen = json_decode(get_setting('size_teen_options'), true) ?: [];
    $size_kids = json_decode(get_setting('size_kids_options'), true) ?: [];
    $weights = json_decode(get_setting('weight_options'), true) ?: [];

    $brand_name = branding('site_name') ?: 'SunnahTi';
    $brand_title = branding('site_title') ?: ($brand_name . ' Premium Store');
    $brand_home = branding('home_url') ?: '#';
    $brand_logo = branding('logo_url');
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?= htmlspecialchars($product['title']) ?> - <?= htmlspecialchars($brand_title) ?></title>
        <?php
        $og_img = trim((string)($product['og_image'] ?? '')) ?: (trim((string)($product['image_url'] ?? '')) ?: trim((string)get_setting('og_default_image')));
        $og_url = base_url() . '/?action=view&slug=' . urlencode($product['slug']);
        ?>
        <meta property="og:type" content="product">
        <meta property="og:title" content="<?= htmlspecialchars($product['title']) ?>">
        <meta property="og:description" content="<?= htmlspecialchars(mb_substr(strip_tags((string)($product['description'] ?? '')), 0, 150) ?: ('অর্ডার করুন — ' . $brand_name)) ?>">
        <meta property="og:url" content="<?= htmlspecialchars($og_url) ?>">
        <meta property="og:site_name" content="<?= htmlspecialchars($brand_name) ?>">
        <?php if ($og_img): ?>
        <meta property="og:image" content="<?= htmlspecialchars($og_img) ?>">
        <meta property="og:image:width" content="1200">
        <meta property="og:image:height" content="630">
        <meta name="twitter:card" content="summary_large_image">
        <meta name="twitter:image" content="<?= htmlspecialchars($og_img) ?>">
        <?php endif; ?>
        <?= render_favicon_tag() ?>
        <script src="https://cdn.tailwindcss.com"></script>
        <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <?php render_landing_shared_css(); ?>

        <?php if ($fb_pixel): ?>
        <script>
            !function(f,b,e,v,n,t,s)
            {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};
            if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
            n.queue=[];t=b.createElement(e);t.async=!0;
            t.src=v;s=b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t,s)}(window, document,'script',
            'https://connect.facebook.net/en_US/fbevents.js');
            fbq('init', '<?= $fb_pixel ?>');
            fbq('track', 'PageView');
            fbq('track', 'ViewContent', { content_name: '<?= addslashes($product['title']) ?>', value: <?= $product['sale_price'] ?: $product['price'] ?>, currency: 'BDT' });
        </script>
        <?php endif; ?>

        <?php if ($tt_pixel): ?>
        <script>
            !function (w, d, t) {
              w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","trackWithSegment","setAndTrack","load","unset","trackLocal"],ttq.setAndTrack=function(t,e,n){t[e]=n},ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndTrack(e,ttq.methods[n],e[t+"."+ttq.methods[n]]);return e},ttq.load=function(e,n){var r="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._u=r,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=d.createElement("script");o.type="text/javascript",o.async=!0,o.src=r+"?sdkid="+e+"&lib="+t;var a=d.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};
              ttq.load('<?= $tt_pixel ?>');
              ttq.page();
            }(window, document, 'ttq');
        </script>
        <?php endif; ?>

        <?php if ($gtag): ?>
        <script async src="https://www.googletagmanager.com/gtag/js?id=<?= $gtag ?>"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '<?= $gtag ?>');
        </script>
        <?php endif; ?>
    </head>
    <body class="bg-slate-50 text-slate-900">
        <header class="bg-white border-b border-gray-100 py-4 shadow-sm sticky top-0 z-50">
            <div class="max-w-6xl mx-auto px-4 flex justify-between items-center">
                <a href="<?= htmlspecialchars($brand_home) ?>" class="flex items-center gap-2">
                    <?php if ($brand_logo): ?>
                        <img src="<?= htmlspecialchars($brand_logo) ?>" alt="<?= htmlspecialchars($brand_name) ?>" class="h-9 object-contain">
                    <?php else: ?>
                        <span class="text-emerald-600 text-2xl font-extrabold"><?= htmlspecialchars($brand_name) ?></span>
                    <?php endif; ?>
                </a>
                <a href="#orderForm" class="bg-emerald-600 hover:bg-emerald-500 text-white font-bold px-5 py-2 rounded-full transition shadow-md text-sm">অর্ডার করুন <i class="fa-solid fa-arrow-down ml-1"></i></a>
            </div>
        </header>

        <main class="max-w-5xl mx-auto px-4 py-8 lg:py-12">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 lg:gap-12 bg-white p-6 lg:p-10 rounded-3xl shadow-xl border border-gray-100 mb-12">
                <div class="space-y-4">
                    <img id="main-image" src="<?= htmlspecialchars($product['image_url'] ?: 'https://images.unsplash.com/photo-1541643600914-78b084683601?auto=format&fit=crop&w=600&q=80') ?>" class="w-full h-96 object-cover rounded-2xl shadow-sm border border-gray-100">
                </div>

                <div class="flex flex-col justify-between">
                    <div>
                        <span class="text-xs bg-emerald-100 text-emerald-800 px-3 py-1 rounded-full font-bold uppercase tracking-wide">In Stock</span>
                        <h1 class="text-3xl font-extrabold text-slate-900 mt-3 mb-2"><?= htmlspecialchars($product['title']) ?></h1>

                        <div class="flex items-baseline gap-3 mb-6">
                            <span class="text-3xl font-black text-emerald-600"><?= number_format($product['sale_price'] ?: $product['price']) ?> ৳</span>
                            <?php if ($product['sale_price']): ?>
                                <span class="text-sm text-gray-400 line-through"><?= number_format($product['price']) ?> ৳</span>
                            <?php endif; ?>
                        </div>

                        <p class="text-gray-600 leading-relaxed mb-6"><?= nl2br(htmlspecialchars($product['description'])) ?></p>
                    </div>

                    <a href="#orderForm" class="block text-center w-full bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-lg py-4 rounded-2xl transition shadow-xl">এখনই অর্ডার করুন <i class="fa-solid fa-cart-shopping ml-2"></i></a>
                </div>
            </div>

            <div id="orderForm" class="max-w-2xl mx-auto bg-white p-6 lg:p-8 rounded-3xl shadow-xl border border-gray-100">
                <div class="text-center mb-6 border-b border-gray-100 pb-4">
                    <h3 class="text-xl lg:text-2xl font-bold text-slate-900 flex items-center justify-center gap-2">
                        <i class="fa-solid fa-lock text-emerald-500"></i>  ডেলিভারি পেতে নিচের ফর্মটি পূরণ করুন
                    </h3>
                    <p class="text-xs text-gray-500 mt-1">অর্ডার সম্পন্ন হলে আমাদের কাস্টমার প্রতিনিধি আপনার সাথে যোগাযোগ করবেন।</p>
                </div>

                <form id="landingCheckout" class="space-y-4">
                    <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                    <input type="hidden" name="incomplete_token" id="incompleteToken" value="">
                    <input type="hidden" name="page_slug" value="<?= htmlspecialchars($product['slug']) ?>">

                    <?= render_variant_blocks_html([$product], $size_teen, $size_kids, $weights) ?>

                    <?php if (!isset($fields['name']) || $fields['name']): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">আপনার নাম (আবশ্যিক)</label>
                        <input type="text" name="customer_name" required placeholder="আপনার সম্পূর্ণ নাম লিখুন" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                    </div>
                    <?php endif; ?>

                    <?php if (!isset($fields['phone']) || $fields['phone']): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">১১ ডিজিটের মোবাইল নম্বর (আবশ্যিক)</label>
                        <input type="text" name="phone" required placeholder="০১৭XXXXXXXX" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                    </div>
                    <?php endif; ?>

                    <?php if (!isset($fields['alt_phone']) || $fields['alt_phone']): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">বিকল্প মোবাইল নম্বর (ঐচ্ছিক)</label>
                        <input type="text" name="alternative_phone" placeholder="যদি থাকে" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                    </div>
                    <?php endif; ?>

                    <?php if (!isset($fields['address']) || $fields['address']): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">সম্পূর্ণ ঠিকানা (আবশ্যিক)</label>
                        <textarea name="address" required placeholder="জেলা, থানা, রোড নং, বাড়ির নাম উল্লেখ করুন" rows="3" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm"></textarea>
                    </div>
                    <?php endif; ?>

                    <?php if ((!isset($fields['color']) || $fields['color']) && !empty($colors)): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">পছন্দের কালার নির্বাচন করুন</label>
                        <div class="flex flex-wrap gap-2">
                            <?php foreach ($colors as $cidx => $c): ?>
                                <label class="pill-btn color-btn" data-hex="<?= htmlspecialchars(color_hex($c['en'])) ?>">
                                    <input type="radio" name="color_selected" value="<?= htmlspecialchars($c['en']) ?>" class="hidden-radio">
                                    <span class="color-dot" style="background: <?= htmlspecialchars(color_hex($c['en'])) ?>;"></span>
                                    <span><?= htmlspecialchars($c['bn'] ?: $c['en']) ?></span>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if (!isset($fields['note']) || $fields['note']): ?>
                    <div>
                        <label class="block text-slate-700 text-sm font-semibold mb-1">বিশেষ নির্দেশাবলী (ঐচ্ছিক)</label>
                        <input type="text" name="note" placeholder="যেমন: দুপুর ৩টার পর ডেলিভারি দিন" class="w-full border border-gray-300 rounded-xl px-4 py-3 focus:outline-none focus:border-emerald-500 transition text-sm">
                    </div>
                    <?php endif; ?>

                    <div id="formResponse" class="hidden p-3 rounded-xl text-center text-xs font-semibold"></div>

                        <?php $cf_label = trim((string)($fields['custom_field_label'] ?? ''));
                        if (!empty($fields['custom_field']) && $cf_label !== ''): ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1"><?= htmlspecialchars($cf_label) ?> <span class="text-rose-500">*</span></label>
                            <input type="text" name="custom_field_value" required class="w-full bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-800 outline-none focus:border-emerald-500" placeholder="এখানে লিখুন...">
                            <input type="hidden" name="custom_field_label" value="<?= htmlspecialchars($cf_label) ?>">
                        </div>
                        <?php endif; ?>

                        <?php
                        // ---- ডেলিভারি এলাকা (কুরিয়ার চার্জ) + প্রোমো কোড + অর্ডার সামারি ----
                        $ord_price_map = [];
                        if (isset($products) && is_array($products)) {
                            foreach ($products as $opm) $ord_price_map[(int)$opm['id']] = (float)(($opm['sale_price'] !== null && $opm['sale_price'] > 0) ? $opm['sale_price'] : $opm['price']);
                        } elseif (isset($product) && is_array($product)) {
                            $ord_price_map[(int)$product['id']] = (float)(($product['sale_price'] !== null && $product['sale_price'] > 0) ? $product['sale_price'] : $product['price']);
                        }
                        $ord_has_zone = !empty($fields['courier_charge']);
                        $ord_has_promo = !empty($fields['promo_code']);
                        if ($ord_has_zone):
                            $chg_map = [
                                'dhaka' => (int)(get_setting('courier_charge_dhaka') ?: 60),
                                'sub_dhaka' => (int)(get_setting('courier_charge_sub_dhaka') ?: 100),
                                'outside' => (int)(get_setting('courier_charge_outside') ?: 130),
                            ];
                        ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-2"><i class="fa-solid fa-truck-fast text-emerald-500"></i> ডেলিভারি এলাকা সিলেক্ট করুন <span class="text-rose-500">*</span></label>
                            <input type="hidden" name="courier_charge_on" value="1">
                            <div class="grid grid-cols-1 gap-2">
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="dhaka" data-charge="<?= $chg_map['dhaka'] ?>" class="text-emerald-500 h-4 w-4"> ঢাকার মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['dhaka']) ?></span>
                                </label>
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="sub_dhaka" data-charge="<?= $chg_map['sub_dhaka'] ?>" class="text-emerald-500 h-4 w-4"> সাব ঢাকার মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['sub_dhaka']) ?></span>
                                </label>
                                <label class="flex items-center justify-between border-2 border-slate-200 rounded-xl px-4 py-3 cursor-pointer hover:border-emerald-400 transition has-[:checked]:border-emerald-500 has-[:checked]:bg-emerald-50">
                                    <span class="flex items-center gap-2 text-sm font-semibold text-slate-700"><input type="radio" name="delivery_zone" value="outside" data-charge="<?= $chg_map['outside'] ?>" class="text-emerald-500 h-4 w-4"> সারা বাংলাদেশের মধ্যে</span>
                                    <span class="text-sm font-extrabold text-emerald-600">৳<?= number_format($chg_map['outside']) ?></span>
                                </label>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($ord_has_promo): ?>
                        <div>
                            <label class="block text-sm font-bold text-slate-700 mb-1"><i class="fa-solid fa-ticket text-fuchsia-500"></i> প্রোমো কোড (থাকলে)</label>
                            <div class="flex gap-2">
                                <input type="text" id="promoInput" placeholder="যেমন: EID10" class="flex-1 bg-white border border-slate-300 rounded-xl px-4 py-3 text-slate-800 outline-none focus:border-fuchsia-500 font-mono uppercase">
                                <button type="button" id="applyPromoBtn" onclick="ordApplyPromo()" class="bg-fuchsia-600 hover:bg-fuchsia-500 text-white text-sm font-bold px-5 rounded-xl transition whitespace-nowrap">অ্যাপ্লাই</button>
                            </div>
                            <input type="hidden" name="promo_code" id="promoCodeHidden" value="">
                            <p id="promoMsg" class="hidden text-xs font-bold mt-1.5"></p>
                        </div>
                        <?php endif; ?>

                        <?php if ($ord_has_zone || $ord_has_promo): ?>
                        <div id="ordSummary" class="hidden bg-slate-50 border-2 border-slate-200 rounded-2xl p-4 space-y-1.5 text-sm">
                            <div class="flex justify-between text-slate-600"><span>প্রোডাক্টের মূল্য</span><span id="sumPrice" class="font-bold">৳0</span></div>
                            <div id="sumDiscRow" class="hidden flex justify-between text-fuchsia-600"><span>প্রোমো ছাড় (<span id="sumDiscCode"></span>)</span><span id="sumDisc" class="font-bold">−৳0</span></div>
                            <div id="sumChgRow" class="hidden flex justify-between text-slate-600"><span>ডেলিভারি চার্জ</span><span id="sumChg" class="font-bold">+৳0</span></div>
                            <div class="flex justify-between border-t-2 border-slate-200 pt-2 text-slate-900 font-extrabold text-base"><span>মোট (ক্যাশ অন ডেলিভারি)</span><span id="sumTotal" class="text-emerald-600">৳0</span></div>
                        </div>
                        <script>
                            window.ORD_PRICES = <?= json_encode($ord_price_map) ?>;
                            window.ORD_DISCOUNT = 0;
                            window.ORD_DISC_CODE = '';
                            function ordBasePrice() {
                                const r = document.querySelector('input[name="product_id"]:checked') || document.querySelector('input[type="hidden"][name="product_id"]');
                                if (!r) return 0;
                                return parseFloat(window.ORD_PRICES[r.value] || 0);
                            }
                            function ordCalcUpdate() {
                                const price = ordBasePrice();
                                const disc = Math.min(window.ORD_DISCOUNT || 0, price);
                                const zr = document.querySelector('input[name="delivery_zone"]:checked');
                                const chg = zr ? parseFloat(zr.dataset.charge || 0) : 0;
                                const box = document.getElementById('ordSummary');
                                if (!box) return;
                                if (price <= 0 && disc <= 0 && chg <= 0) { box.classList.add('hidden'); return; }
                                box.classList.remove('hidden');
                                document.getElementById('sumPrice').textContent = '৳' + price.toLocaleString('bn-BD');
                                const dr = document.getElementById('sumDiscRow');
                                if (disc > 0) { dr.classList.remove('hidden'); dr.classList.add('flex'); document.getElementById('sumDisc').textContent = '−৳' + disc.toLocaleString('bn-BD'); document.getElementById('sumDiscCode').textContent = window.ORD_DISC_CODE; }
                                else { dr.classList.add('hidden'); dr.classList.remove('flex'); }
                                const cr = document.getElementById('sumChgRow');
                                if (zr) { cr.classList.remove('hidden'); cr.classList.add('flex'); document.getElementById('sumChg').textContent = '+৳' + chg.toLocaleString('bn-BD'); }
                                else { cr.classList.add('hidden'); cr.classList.remove('flex'); }
                                document.getElementById('sumTotal').textContent = '৳' + Math.max(0, price - disc + chg).toLocaleString('bn-BD');
                            }
                            document.addEventListener('change', function (e) {
                                if (e.target && (e.target.name === 'product_id' || e.target.name === 'delivery_zone')) ordCalcUpdate();
                            });
                            function ordApplyPromo() {
                                const inp = document.getElementById('promoInput');
                                const msg = document.getElementById('promoMsg');
                                const hid = document.getElementById('promoCodeHidden');
                                const code = (inp.value || '').trim().toUpperCase();
                                if (!code) { msg.className = 'text-xs font-bold mt-1.5 text-rose-600'; msg.textContent = 'প্রোমো কোড লিখুন'; return; }
                                const r = document.querySelector('input[name="product_id"]:checked') || document.querySelector('input[type="hidden"][name="product_id"]');
                                const fd = new FormData();
                                fd.append('code', code);
                                fd.append('product_id', r ? r.value : 0);
                                document.getElementById('applyPromoBtn').disabled = true;
                                fetch('?action=apply_promo', { method: 'POST', body: fd })
                                    .then(res => res.json())
                                    .then(d => {
                                        document.getElementById('applyPromoBtn').disabled = false;
                                        if (d.status === 'success') {
                                            hid.value = d.code;
                                            window.ORD_DISCOUNT = parseFloat(d.discount || 0);
                                            window.ORD_DISC_CODE = d.code;
                                            msg.className = 'text-xs font-bold mt-1.5 text-emerald-600';
                                            msg.textContent = '✓ ' + d.message + (d.label ? ' (' + d.label + ')' : '');
                                        } else {
                                            hid.value = '';
                                            window.ORD_DISCOUNT = 0; window.ORD_DISC_CODE = '';
                                            msg.className = 'text-xs font-bold mt-1.5 text-rose-600';
                                            msg.textContent = '✕ ' + (d.message || 'প্রোমো কোডটি সঠিক নয়');
                                        }
                                        ordCalcUpdate();
                                    })
                                    .catch(() => {
                                        document.getElementById('applyPromoBtn').disabled = false;
                                        msg.className = 'text-xs font-bold mt-1.5 text-rose-600';
                                        msg.textContent = 'নেটওয়ার্ক সমস্যা — আবার চেষ্টা করুন';
                                    });
                            }
                        </script>
                        <?php endif; ?>

                        <div id="advanceBox" class="hidden bg-amber-50 border-2 border-amber-400 rounded-2xl p-4 space-y-3 my-3">
                        <p id="advanceMsg" class="text-sm font-bold text-amber-800 leading-relaxed"></p>
                        <div id="advanceNumbers" class="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm"></div>
                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1">ট্রানজেকশন আইডি (TrxID)</label>
                            <input type="text" name="advance_trx" placeholder="যেমন: 9H7XXXXXXX" class="w-full bg-white border border-amber-300 rounded-xl px-3 py-2.5 text-slate-800 outline-none focus:border-amber-500 font-mono">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-slate-700 mb-1">অথবা পেমেন্টের স্ক্রিনশট দিন</label>
                            <input type="file" name="advance_screenshot" accept="image/*" class="w-full bg-white border border-amber-300 rounded-xl px-3 py-2 text-slate-600 text-xs">
                        </div>
                        <p class="text-[11px] text-amber-700">💡 সেন্ড মানি করার পর TrxID অথবা স্ক্রিনশট — যেকোনো একটা দিয়ে আবার "অর্ডার নিশ্চিত করুন" বাটনে ক্লিক করুন।</p>
                    </div>


                    <button type="submit" id="submitBtn" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-lg py-4 rounded-2xl transition shadow-xl flex items-center justify-center gap-2">
                        <i class="fa-solid fa-lock"></i> <span id="btnText">অর্ডার নিশ্চিত করুন</span> - <?= number_format($product['sale_price'] ?: $product['price']) ?> ৳
                    </button>
                </form>
            </div>
        </main>

        <div id="successModal" class="hidden fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm animate-fade-in">
            <div class="bg-white rounded-3xl p-6 lg:p-8 max-w-lg w-full shadow-2xl border border-gray-100 transform scale-95 transition-all duration-300 text-center relative">
                <div class="w-16 h-16 bg-emerald-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa-solid fa-circle-check text-4xl text-emerald-500"></i>
                </div>
                <h3 class="text-2xl font-extrabold text-slate-950 mb-1">অর্ডার সফল হয়েছে!</h3>
                <h4 class="text-base font-bold text-emerald-600 mb-4">ধন্যবাদ আমাদের সাথে থাকার জন্য!</h4>

                <div class="bg-slate-50 rounded-2xl p-4 text-left text-xs text-slate-700 mb-6 space-y-2.5 border border-slate-200">
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">অর্ডার আইডি:</strong> <span id="modalOrderId" class="font-mono font-bold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">গ্রাহক:</strong> <span id="modalCustName" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">মোবাইল নম্বর:</strong> <span id="modalCustPhone" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2"><strong class="text-slate-900">পণ্য:</strong> <span id="modalProdTitle" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalColorRow"><strong class="text-slate-900">কালার:</strong> <span id="modalColor" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalSizeRow" style="display:none;"><strong class="text-slate-900">সাইজ:</strong> <span id="modalSize" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between border-b border-gray-200 pb-2" id="modalWeightRow" style="display:none;"><strong class="text-slate-900">ওজন:</strong> <span id="modalWeight" class="font-semibold text-slate-950"></span></div>
                    <div class="flex justify-between pt-1"><strong class="text-slate-900">মোট মূল্য:</strong> <span id="modalTotalPrice" class="font-extrabold text-emerald-600 text-sm"></span></div>
                </div>

                <p class="text-xs lg:text-sm text-slate-600 font-medium leading-relaxed mb-4">
                    আমাদের কাস্টমার কেয়ার প্রতিনিধি আপনাকে কল দিয়ে অর্ডারটি কনফার্ম করবে আগামী ১২ ঘণ্টার মধ্যে অনুগ্রহ করে <br> অপেক্ষা করুন
                </p>

                <?php if (trim(get_setting('support_whatsapp')) !== ''): ?>
                <a id="successWaBtn" href="#" target="_blank" class="w-full bg-[#25D366] hover:bg-[#1eb955] text-white font-extrabold text-sm py-3 rounded-xl transition shadow-lg flex items-center justify-center gap-2 mb-3">
                    <i class="fa-brands fa-whatsapp text-lg"></i> WhatsApp-এ অর্ডারের স্ক্রিনশট পাঠান
                </a>
                <p class="text-[11px] text-slate-400 mb-4 -mt-1">অর্ডারের একটি স্ক্রিনশট নিয়ে আমাদের WhatsApp-এ পাঠালে দ্রুত কনফার্ম করা সহজ হয়।</p>
                <?php endif; ?>

                <button onclick="closeSuccessModalAndReload()" class="w-full bg-emerald-600 hover:bg-emerald-500 text-white font-extrabold text-sm py-3 rounded-xl transition shadow-lg">
                    ঠিক আছে
                </button>
            </div>
        </div>

        <footer class="bg-white border-t border-gray-100 py-8 text-center text-sm text-slate-400">
            &copy; <?= date('Y') ?> <a href="<?= htmlspecialchars($brand_home) ?>" class="hover:text-emerald-500 transition"><?= htmlspecialchars($brand_name) ?></a>. All rights reserved. Powered by <?= htmlspecialchars($brand_name) ?> ERP Engine v3.0
        <?php render_floating_contact_icons(!isset($fields['wa_icon']) || $fields['wa_icon'], !isset($fields['call_icon']) || $fields['call_icon']); ?>
        </footer>

        <?php render_landing_shared_variant_js(); ?>
        <script>
            function closeSuccessModalAndReload() {
                window.location.reload();
            }

            // ---- Incomplete Order Capture Engine ----
            let incToken = localStorage.getItem('st_inc_token');
            if (!incToken) {
                incToken = 'tk_' + Date.now() + '_' + Math.random().toString(36).substr(2, 10);
                localStorage.setItem('st_inc_token', incToken);
            }
            document.getElementById('incompleteToken').value = incToken;

            let incTimer = null;
            function captureIncomplete() {
                clearTimeout(incTimer);
                incTimer = setTimeout(function() {
                    const form = document.getElementById('landingCheckout');
                    const fd = new FormData(form);
                    const name = (fd.get('customer_name') || '').toString().trim();
                    const phone = (fd.get('phone') || '').toString().trim();
                    const address = (fd.get('address') || '').toString().trim();
                    if (name === '' && phone === '' && address === '') return;
                    const payload = new URLSearchParams();
                    payload.set('token', incToken);
                    payload.set('customer_name', name);
                    payload.set('phone', phone);
                    payload.set('address', address);
                    payload.set('product_id', '<?= (int)$product['id'] ?>');
                    payload.set('page_slug', '<?= htmlspecialchars($product['slug']) ?>');
                    fetch('?action=save_incomplete', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: payload.toString() }).catch(function(){});
                }, 1500);
            }
            ['input', 'change'].forEach(function(evt) {
                document.getElementById('landingCheckout').addEventListener(evt, captureIncomplete);
            });

            document.getElementById('landingCheckout').addEventListener('submit', function(e) {
                e.preventDefault();
                const btn = document.getElementById('submitBtn');
                const btnText = document.getElementById('btnText');
                const resp = document.getElementById('formResponse');

                btn.disabled = true;
                btnText.innerText = 'অর্ডার প্রসেসিং হচ্ছে...';

                const formData = new FormData(this);

                // কোনো ডিফল্ট সিলেকশন নেই — তাই সাবমিটের আগে যাচাই
                const prodRadios = document.querySelectorAll('input[name="product_id"]');
                if (prodRadios.length > 1 && !document.querySelector('input[name="product_id"]:checked')) {
                    resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = 'অনুগ্রহ করে একটি প্রোডাক্ট সিলেক্ট করুন।';
                    resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    return;
                }
                const colorVisible = document.querySelector('input[name="color_selected"]');
                if (colorVisible && !document.querySelector('input[name="color_selected"]:checked')) {
                    resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = 'অনুগ্রহ করে একটি কালার সিলেক্ট করুন।';
                    resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    return;
                }
                const activeBlock = document.querySelector('.variant-block:not(.hidden)');
                if (activeBlock) {
                    const szRadios = activeBlock.querySelectorAll('input[name="size_selected"]');
                    if (szRadios.length && !activeBlock.querySelector('input[name="size_selected"]:checked')) {
                        resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'অনুগ্রহ করে সাইজ সিলেক্ট করুন।';
                        resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    const wtRadios = activeBlock.querySelectorAll('input[name="weight_selected"]');
                    if (wtRadios.length && !activeBlock.querySelector('input[name="weight_selected"]:checked')) {
                        resp.classList.remove('hidden'); resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'অনুগ্রহ করে ওজন সিলেক্ট করুন।';
                        resp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        btn.disabled = false; btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                }

                const custName = formData.get('customer_name') || '';
                const custPhone = formData.get('phone') || '';
                const colorSelected = formData.get('color_selected') || 'N/A';
                let sizeSelected = formData.get('size_selected') || '';
                let weightSelected = formData.get('weight_selected') || '';
                if (weightSelected === 'custom') {
                    const cw = (formData.get('weight_custom') || '').toString().trim();
                    weightSelected = cw !== '' ? cw + ' kg' : '';
                }
                const prodTitle = '<?= addslashes($product['title']) ?>';
                const totalPrice = '<?= number_format($product['sale_price'] ?: $product['price']) ?>';

                fetch('?action=submit_order', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('সার্ভার থেকে সঠিক রেসপন্স পাওয়া যায়নি (স্ট্যাটাস: ' + response.status + ')');
                    }
                    return response.text();
                })
                .then(text => {
                    let d;
                    try {
                        d = JSON.parse(text);
                    } catch (err) {
                        console.error("Non-JSON Server Output:", text);
                        throw new Error('সার্ভারে সমস্যা হয়েছে। অনুগ্রহ করে অ্যাডমিনকে কনসোল ডিবাগ চেক করতে বলুন।');
                    }

                    resp.classList.remove('hidden', 'bg-red-100', 'text-red-800', 'bg-green-100', 'text-green-800');
                    if (d.status === 'repeat_blocked') {
                        // ১ দিনে ১ বারই অর্ডার — আবার চেষ্টা করলে WhatsApp-এ যোগাযোগের বার্তা
                        resp.classList.add('bg-amber-100', 'text-amber-800');
                        let html = '<div style="font-weight:700; margin-bottom:8px;">' + d.message + '</div>';
                        if (d.wa_link) {
                            html += '<a href="' + d.wa_link + '" target="_blank" style="display:inline-flex; align-items:center; gap:8px; background:#25D366; color:#fff; font-weight:800; padding:10px 18px; border-radius:12px; text-decoration:none; margin-top:4px;"><i class="fa-brands fa-whatsapp"></i> WhatsApp-এ মেসেজ দিন</a>';
                        }
                        resp.innerHTML = html;
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    if (d.status === 'advance_required') {
                        // হাই-রিস্ক কাস্টমার: এডভান্স পেমেন্ট বক্স দেখাও
                        const advBox = document.getElementById('advanceBox');
                        document.getElementById('advanceMsg').innerText = d.message;
                        let nums = '';
                        if (d.bkash) nums += '<div style="background:#e2136e; color:#fff; border-radius:12px; padding:10px 14px; font-weight:800;">বিকাশ (সেন্ড মানি):<br><span style="font-family:monospace; font-size:17px; letter-spacing:1px;">' + d.bkash + '</span></div>';
                        if (d.nagad) nums += '<div style="background:#f6921e; color:#fff; border-radius:12px; padding:10px 14px; font-weight:800;">নগদ (সেন্ড মানি):<br><span style="font-family:monospace; font-size:17px; letter-spacing:1px;">' + d.nagad + '</span></div>';
                        if (!nums) nums = '<div style="color:#92400e; font-weight:700;">পেমেন্ট নাম্বার পেতে আমাদের হেল্পলাইনে যোগাযোগ করুন।</div>';
                        document.getElementById('advanceNumbers').innerHTML = nums;
                        advBox.classList.remove('hidden');
                        advBox.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = 'এডভান্স ' + d.amount + ' টাকা পাঠিয়ে TrxID বা স্ক্রিনশট দিয়ে আবার অর্ডার করুন।';
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                        return;
                    }
                    if (d.status === 'success') {
                        resp.classList.add('bg-green-100', 'text-green-800');
                        resp.innerText = d.message;

                        localStorage.removeItem('st_inc_token');

                        document.getElementById('modalOrderId').innerText = '#' + d.order_id;
                        document.getElementById('modalCustName').innerText = custName;
                        document.getElementById('modalCustPhone').innerText = custPhone;
                        document.getElementById('modalProdTitle').innerText = prodTitle;

                        // WhatsApp বাটন: অর্ডারের তথ্য প্রি-ফিল করে সাপোর্ট নম্বরে লিংক
                        <?php $sup_wa2 = preg_replace('/\D/', '', bnToEnNumber(get_setting('support_whatsapp'))); if ($sup_wa2 !== ''): if (strlen($sup_wa2) === 11 && $sup_wa2[0] === '0') $sup_wa2 = '88' . $sup_wa2; ?>
                        (function() {
                            const waBtn = document.getElementById('successWaBtn');
                            if (waBtn) {
                                const msg = 'আসসালামু আলাইকুম,\nআমি একটি অর্ডার করেছি।\n\nঅর্ডার আইডি: #' + d.order_id
                                          + '\nনাম: ' + custName
                                          + '\nমোবাইল: ' + custPhone
                                          + '\nপণ্য: ' + (prodTitle || '')
                                          + '\nমোট: ' + totalPrice + ' টাকা'
                                          + '\n\n(অর্ডারের স্ক্রিনশট এখানে যুক্ত করছি)';
                                waBtn.href = 'https://wa.me/<?= $sup_wa2 ?>?text=' + encodeURIComponent(msg);
                            }
                        })();
                        <?php endif; ?>

                        const colorRow = document.getElementById('modalColorRow');
                        if (colorSelected && colorSelected !== 'N/A') {
                            document.getElementById('modalColor').innerText = colorSelected;
                            colorRow.style.display = 'flex';
                        } else {
                            colorRow.style.display = 'none';
                        }
                        const sizeRow = document.getElementById('modalSizeRow');
                        if (sizeSelected) {
                            document.getElementById('modalSize').innerText = sizeSelected;
                            sizeRow.style.display = 'flex';
                        } else { sizeRow.style.display = 'none'; }
                        const weightRow = document.getElementById('modalWeightRow');
                        if (weightSelected) {
                            document.getElementById('modalWeight').innerText = weightSelected;
                            weightRow.style.display = 'flex';
                        } else { weightRow.style.display = 'none'; }
                        document.getElementById('modalTotalPrice').innerText = totalPrice + ' ৳';

                        document.getElementById('successModal').classList.remove('hidden');

                        <?php if ($fb_pixel): ?>
                        if (typeof fbq !== 'undefined') {
                            fbq('track', 'Purchase', {
                                value: <?= $product['sale_price'] ?: $product['price'] ?>,
                                currency: 'BDT',
                                content_name: '<?= addslashes($product['title']) ?>'
                            }, { eventID: 'order_' + d.order_id });
                        }
                        <?php endif; ?>

                        <?php if ($tt_pixel): ?>
                        if (typeof ttq !== 'undefined') {
                            ttq.track('CompletePayment', {
                                value: <?= $product['sale_price'] ?: $product['price'] ?>,
                                currency: 'BDT',
                                content_name: '<?= addslashes($product['title']) ?>'
                            }, { event_id: 'order_' + d.order_id });
                        }
                        <?php endif; ?>
                    } else {
                        resp.classList.remove('hidden');
                        resp.classList.add('bg-red-100', 'text-red-800');
                        resp.innerText = d.message;
                        btn.disabled = false;
                        btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                    }
                })
                .catch((error) => {
                    resp.classList.remove('hidden');
                    resp.classList.add('bg-red-100', 'text-red-800');
                    resp.innerText = error.message || 'সিস্টেম এরর ঘটেছে! দয়া করে আবার চেষ্টা করুন।';
                    btn.disabled = false;
                    btnText.innerText = 'অর্ডার নিশ্চিত করুন';
                });
            });

            refreshPillButtons();
        </script>
    </body>
    </html>
    <?php
}

// -------------------------------------------------------------
// WEB DIALER PAD (মোবাইল ফোনের মতো ডায়ালার + অটো কল রেকর্ডিং)
// -------------------------------------------------------------

function render_webrtc_dialer_pad($sip) {
    $dial_prefill  = isset($_GET['dial']) ? preg_replace('/[^0-9+*#]/', '', $_GET['dial']) : '';
    $dial_order    = isset($_GET['dial_order']) ? (int)$_GET['dial_order'] : 0;
    $dial_name     = isset($_GET['dial_name']) ? trim($_GET['dial_name']) : '';
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
        <h3 class="text-lg font-bold text-white mb-4 flex items-center gap-2 border-b border-slate-700 pb-3">
            <i class="fa-solid fa-phone-volume text-emerald-400"></i> <span data-i18n="ওয়েব ডায়ালার">ওয়েব ডায়ালার</span>
            <span id="sipRegStatus" class="ml-auto text-[11px] font-mono px-2.5 py-1 rounded-full bg-slate-700 text-slate-400">অফলাইন</span>
        </h3>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- বাম পাশ: ডায়াল প্যাড -->
            <div class="max-w-sm mx-auto w-full">
                <?php if ($dial_order || $dial_name): ?>
                <div class="bg-cyan-950/40 border border-cyan-800/40 rounded-xl px-4 py-2.5 mb-3 text-xs text-cyan-300">
                    <i class="fa-solid fa-user"></i>
                    <?= $dial_name ? htmlspecialchars($dial_name) : '' ?>
                    <?= $dial_order ? ' — অর্ডার #' . $dial_order : '' ?>
                </div>
                <?php endif; ?>

                <!-- নাম্বার ডিসপ্লে (টাইপ / পেস্ট করা যাবে) -->
                <div class="relative mb-3">
                    <input type="text" id="dialNumber" value="<?= htmlspecialchars($dial_prefill) ?>"
                        placeholder="নাম্বার লিখুন বা পেস্ট করুন"
                        oninput="this.value = this.value.replace(/[^0-9+*#]/g, '')"
                        class="w-full bg-slate-900 text-white text-center text-2xl font-mono tracking-widest rounded-xl px-12 py-4 border border-slate-600 outline-none focus:border-emerald-500">
                    <button type="button" onclick="pasteDialNumber()" title="পেস্ট করুন" class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-cyan-400 p-2"><i class="fa-solid fa-paste"></i></button>
                    <button type="button" onclick="dialBackspace()" title="মুছুন" class="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-rose-400 p-2"><i class="fa-solid fa-delete-left"></i></button>
                </div>

                <!-- কল স্ট্যাটাস + টাইমার -->
                <div id="callStatusBar" class="hidden items-center justify-between bg-slate-900 border border-slate-700 rounded-xl px-4 py-2.5 mb-3">
                    <span id="callStatusText" class="text-xs text-emerald-400 font-bold">কল হচ্ছে...</span>
                    <span class="flex items-center gap-3">
                        <span id="recIndicator" class="hidden text-[10px] text-rose-400 font-bold animate-pulse"><i class="fa-solid fa-circle text-[8px]"></i> REC</span>
                        <span id="callTimer" class="text-sm font-mono text-white" title="কথার সময় (সেকেন্ড)">00:00</span>
                    </span>
                </div>

                <!-- ইনকামিং কল বক্স -->
                <div id="incomingCallBox" class="hidden bg-sky-950/60 border-2 border-sky-500 rounded-2xl p-4 mb-3 text-center animate-pulse">
                    <p class="text-[11px] text-sky-300 font-bold mb-1"><i class="fa-solid fa-phone-volume"></i> ইনকামিং কল আসছে...</p>
                    <p id="incomingNumber" class="text-xl font-mono font-extrabold text-white tracking-wider mb-3">—</p>
                    <div class="flex gap-3">
                        <button type="button" onclick="answerIncoming()" class="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-3 rounded-xl transition flex items-center justify-center gap-2">
                            <i class="fa-solid fa-phone"></i> রিসিভ করুন
                        </button>
                        <button type="button" onclick="rejectIncoming()" class="flex-1 bg-rose-600 hover:bg-rose-500 text-white font-bold py-3 rounded-xl transition flex items-center justify-center gap-2">
                            <i class="fa-solid fa-phone-slash"></i> কেটে দিন
                        </button>
                    </div>
                </div>

                <!-- কীপ্যাড -->
                <div class="grid grid-cols-3 gap-2.5 mb-4">
                    <?php foreach (['1','2','3','4','5','6','7','8','9','*','0','#'] as $key): ?>
                    <button type="button" onclick="dialKeyPress('<?= $key ?>')"
                        class="bg-slate-700 hover:bg-slate-600 active:bg-emerald-600 text-white text-xl font-bold py-4 rounded-xl transition select-none">
                        <?= $key ?>
                    </button>
                    <?php endforeach; ?>
                </div>

                <!-- কল / হ্যাংআপ বাটন -->
                <div class="flex gap-3">
                    <button type="button" id="btnCall" onclick="startWebCall()"
                        class="flex-1 bg-emerald-600 hover:bg-emerald-500 text-white font-bold py-3.5 rounded-xl transition text-base flex items-center justify-center gap-2">
                        <i class="fa-solid fa-phone"></i> <span data-i18n="কল করুন">কল করুন</span>
                    </button>
                    <button type="button" id="btnHangup" onclick="hangupWebCall()" disabled
                        class="flex-1 bg-rose-600 hover:bg-rose-500 disabled:opacity-40 disabled:cursor-not-allowed text-white font-bold py-3.5 rounded-xl transition text-base flex items-center justify-center gap-2">
                        <i class="fa-solid fa-phone-slash"></i> <span data-i18n="কেটে দিন">কেটে দিন</span>
                    </button>
                </div>
                <p class="text-[10px] text-slate-500 mt-3 text-center"><i class="fa-solid fa-microphone"></i> প্রথমবার কল করার সময় ব্রাউজার মাইক্রোফোনের অনুমতি চাইবে — <b>Allow</b> চাপুন। প্রতিটি কল স্বয়ংক্রিয়ভাবে রেকর্ড ও সেভ হবে (৩০ দিন পর অটো ডিলিট)।</p>
            </div>

            <!-- ডান পাশ: গাইড -->
            <div class="space-y-3 text-xs text-slate-300 leading-relaxed">
                <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 space-y-2">
                    <p class="font-bold text-white">📞 ওয়েব ডায়ালার কীভাবে কাজ করে:</p>
                    <p>1️⃣ উপরে নাম্বার টাইপ করুন, কীপ্যাডে চাপুন, অথবা কপি করা নাম্বার পেস্ট আইকনে ক্লিক করে বসান।</p>
                    <p>2️⃣ <b class="text-emerald-400">কল করুন</b> বাটনে ক্লিক করুন — মাইক্রোফোন পারমিশন দিন।</p>
                    <p>3️⃣ কল চলাকালীন কীপ্যাডে চাপলে DTMF টোন যাবে (IVR মেনুর জন্য)।</p>
                    <p>4️⃣ কল শেষ হলে রেকর্ডিং স্বয়ংক্রিয়ভাবে সেভ হয়ে নিচের কল হিস্টোরিতে চলে যাবে।</p>
                    <p>5️⃣ অর্ডার লিস্টের <i class="fa-solid fa-phone text-emerald-400"></i> আইকনে ক্লিক করলে নাম্বার এখানে অটো চলে আসবে।</p>
                </div>
                <div id="wssWarning" class="<?= $sip['wss_url'] ? 'hidden' : '' ?> bg-amber-950/40 border border-amber-800/50 rounded-xl p-4 text-amber-300">
                    <p class="font-bold mb-1">⚠️ WebSocket (WSS) URL সেট করা হয়নি!</p>
                    <p>ব্রাউজার থেকে কল করতে হলে নিচের কনফিগারেশন ফর্মে আপনার SIP প্রোভাইডারের WSS URL দিতে হবে। Rafusoft/আপনার প্রোভাইডারকে জিজ্ঞেস করুন: <b>"WebRTC/WebSocket calling এর WSS URL কী?"</b></p>
                </div>
                <div class="bg-slate-900/60 border border-slate-700 rounded-xl p-4 space-y-1.5">
                    <p class="font-bold text-white">🎙️ রেকর্ডিং সম্পর্কে:</p>
                    <p>✅ আপনার কণ্ঠ + কাস্টমারের কণ্ঠ — দুটোই একসাথে রেকর্ড হয়।</p>
                    <p>✅ রেকর্ডিং সার্ভারে <span class="font-mono">uploads/recordings</span> ফোল্ডারে সেভ হয়।</p>
                    <p>✅ ৩০ দিনের পুরোনো রেকর্ডিং স্বয়ংক্রিয়ভাবে ডিলিট হয়ে যায়।</p>
                    <p>✅ চাইলে হিস্টোরি থেকে ম্যানুয়ালিও ডিলিট করা যায়।</p>
                </div>
            </div>
        </div>
    </div>

    <audio id="remoteAudio" autoplay class="hidden"></audio>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jssip/3.10.0/jssip.min.js"></script>
    <script>
        // ---------------- WEB DIALER (JsSIP + MediaRecorder) ----------------
        const SIP_CFG = {
            wss:      <?= json_encode($sip['wss_url']) ?>,
            username: <?= json_encode($sip['username']) ?>,
            password: <?= json_encode($sip['password']) ?>,
            domain:   <?= json_encode($sip['domain']) ?>,
            stun:     <?= json_encode($sip['stun'] ?: 'stun.l.google.com:19302') ?>,
            regInterval: parseInt(<?= json_encode($sip['reg_interval'] ?: '60') ?>) || 60
        };
        const DIAL_CTX = {
            orderId: <?= json_encode($dial_order ?: null) ?>,
            custName: <?= json_encode($dial_name ?: null) ?>
        };

        let sipUA = null, sipSession = null;
        let localStream = null, mediaRecorder = null, recChunks = [], audioCtx = null;
        let callStartTs = 0, callTimerInt = null, callStartedAtStr = '';
        let currentDirection = 'outgoing'; // ইনকামিং / আউটগোয়িং
        let beepCtx = null, beepInt = null;

        // ইনকামিং কলের রিংটোন (ছোট বিপ, ১.২ সেকেন্ড পর পর)
        function startIncomingBeep() {
            stopIncomingBeep();
            try {
                beepCtx = new (window.AudioContext || window.webkitAudioContext)();
                const beep = () => {
                    if (!beepCtx) return;
                    const o = beepCtx.createOscillator(), g = beepCtx.createGain();
                    o.frequency.value = 880; g.gain.value = 0.12;
                    o.connect(g); g.connect(beepCtx.destination);
                    o.start(); o.stop(beepCtx.currentTime + 0.35);
                };
                beep();
                beepInt = setInterval(beep, 1200);
            } catch (e) {}
        }
        function stopIncomingBeep() {
            if (beepInt) { clearInterval(beepInt); beepInt = null; }
            if (beepCtx) { try { beepCtx.close(); } catch (e) {} beepCtx = null; }
        }

        // কথার সেকেন্ড কাউন্টার (ইনকামিং/আউটগোয়িং দুটোতেই)
        function startCallTimer() {
            callStartTs = Date.now();
            const d = new Date();
            callStartedAtStr = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0') + ' ' +
                               String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0') + ':' + String(d.getSeconds()).padStart(2, '0');
            if (callTimerInt) clearInterval(callTimerInt);
            callTimerInt = setInterval(() => {
                document.getElementById('callTimer').textContent = fmtTimer(Math.floor((Date.now() - callStartTs) / 1000));
            }, 1000);
        }

        function showCallBar(text) {
            const bar = document.getElementById('callStatusBar');
            bar.classList.remove('hidden'); bar.classList.add('flex');
            document.getElementById('callStatusText').textContent = text;
        }

        function fmtTimer(s) {
            const m = Math.floor(s / 60), sec = s % 60;
            return String(m).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
        }

        function setRegStatus(text, cls) {
            const el = document.getElementById('sipRegStatus');
            if (!el) return;
            el.textContent = text;
            el.className = 'ml-auto text-[11px] font-mono px-2.5 py-1 rounded-full ' + cls;
        }

        function dialKeyPress(key) {
            if (sipSession && !sipSession.isEnded()) {
                try { sipSession.sendDTMF(key); showToast('DTMF: ' + key, 'success'); } catch (e) {}
                return;
            }
            const inp = document.getElementById('dialNumber');
            inp.value += key;
        }

        function dialBackspace() {
            const inp = document.getElementById('dialNumber');
            inp.value = inp.value.slice(0, -1);
        }

        async function pasteDialNumber() {
            try {
                const text = await navigator.clipboard.readText();
                const clean = (text || '').replace(/[^0-9+*#]/g, '');
                if (!clean) { showToast('ক্লিপবোর্ডে কোনো নাম্বার পাওয়া যায়নি', 'error'); return; }
                document.getElementById('dialNumber').value = clean;
                showToast('নাম্বার পেস্ট হয়েছে: ' + clean, 'success');
            } catch (e) {
                showToast('পেস্ট করতে ব্রাউজার অনুমতি দেয়নি — ম্যানুয়ালি নাম্বার বক্সে পেস্ট করুন (Ctrl+V)', 'error');
            }
        }

        // ---- মাইক্রোফোন পারমিশন ----
        async function ensureMicPermission() {
            try {
                localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
                return true;
            } catch (e) {
                showToast('মাইক্রোফোন পারমিশন দেওয়া হয়নি! ব্রাউজারের অ্যাড্রেস বারে গিয়ে মাইক্রোফোন Allow করুন।', 'error');
                return false;
            }
        }

        // ---- SIP রেজিস্ট্রেশন ----
        function initSipUA() {
            if (sipUA) return sipUA;
            if (!SIP_CFG.wss || !SIP_CFG.username || !SIP_CFG.domain) return null;
            try {
                const socket = new JsSIP.WebSocketInterface(SIP_CFG.wss);
                sipUA = new JsSIP.UA({
                    sockets: [socket],
                    uri: 'sip:' + SIP_CFG.username + '@' + SIP_CFG.domain,
                    password: SIP_CFG.password,
                    register: true,
                    register_expires: SIP_CFG.regInterval,
                    session_timers: false
                });
                sipUA.on('registered', () => setRegStatus('রেজিস্টার্ড ✓', 'bg-emerald-600/20 text-emerald-400'));
                sipUA.on('unregistered', () => setRegStatus('আনরেজিস্টার্ড', 'bg-slate-700 text-slate-400'));
                sipUA.on('registrationFailed', (e) => setRegStatus('রেজিস্ট্রেশন ব্যর্থ', 'bg-rose-600/20 text-rose-400'));
                sipUA.on('disconnected', () => setRegStatus('সংযোগ বিচ্ছিন্ন', 'bg-rose-600/20 text-rose-400'));
                sipUA.on('connecting', () => setRegStatus('সংযোগ হচ্ছে...', 'bg-amber-600/20 text-amber-400'));
                // ইনকামিং কল রিসিভ
                sipUA.on('newRTCSession', (e) => {
                    if (e.originator === 'remote') handleIncomingCall(e.session);
                });
                sipUA.start();
                return sipUA;
            } catch (e) {
                setRegStatus('কনফিগ ত্রুটি', 'bg-rose-600/20 text-rose-400');
                return null;
            }
        }

        // ---- রেকর্ডিং (লোকাল + রিমোট অডিও মিক্স) ----
        function startRecording(remoteStream) {
            try {
                recChunks = [];
                audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                const dest = audioCtx.createMediaStreamDestination();
                if (localStream) audioCtx.createMediaStreamSource(localStream).connect(dest);
                if (remoteStream) audioCtx.createMediaStreamSource(remoteStream).connect(dest);
                const mime = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') ? 'audio/webm;codecs=opus' : 'audio/webm';
                mediaRecorder = new MediaRecorder(dest.stream, { mimeType: mime });
                mediaRecorder.ondataavailable = (e) => { if (e.data && e.data.size > 0) recChunks.push(e.data); };
                mediaRecorder.start(1000);
                document.getElementById('recIndicator').classList.remove('hidden');
            } catch (e) {
                console.error('Recording start failed', e);
            }
        }

        function stopRecordingAndSave(phone, durationSec, status) {
            const finish = (blob) => {
                const fd = new FormData();
                fd.append('phone', phone);
                fd.append('duration_seconds', durationSec);
                fd.append('started_at', callStartedAtStr);
                fd.append('call_status', status);
                fd.append('direction', currentDirection);
                if (DIAL_CTX.orderId && currentDirection === 'outgoing') fd.append('order_id', DIAL_CTX.orderId);
                if (DIAL_CTX.custName) fd.append('customer_name', DIAL_CTX.custName);
                if (blob && blob.size > 0 && durationSec > 0) fd.append('recording', blob, 'call.webm');
                fetch('?action=call_log_save', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(d => {
                        if (d.status === 'success') {
                            showToast('কল লগ ও রেকর্ডিং সেভ হয়েছে ✓', 'success');
                            loadCallLogs();
                        }
                    }).catch(() => {});
            };
            try {
                if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                    mediaRecorder.onstop = () => finish(new Blob(recChunks, { type: 'audio/webm' }));
                    mediaRecorder.stop();
                } else {
                    finish(recChunks.length ? new Blob(recChunks, { type: 'audio/webm' }) : null);
                }
            } catch (e) { finish(null); }
            document.getElementById('recIndicator').classList.add('hidden');
            if (audioCtx) { try { audioCtx.close(); } catch (e) {} audioCtx = null; }
            mediaRecorder = null;
        }

        // ---- কল শুরু ----
        async function startWebCall() {
            const num = document.getElementById('dialNumber').value.trim();
            if (!num) { showToast('প্রথমে নাম্বার লিখুন বা পেস্ট করুন', 'error'); return; }
            if (!SIP_CFG.wss) {
                document.getElementById('wssWarning').classList.remove('hidden');
                showToast('WebSocket (WSS) URL সেট করা হয়নি — নিচের কনফিগারেশন ফর্মে সেট করুন', 'error');
                return;
            }
            if (!SIP_CFG.username || !SIP_CFG.domain) { showToast('SIP Username/Domain কনফিগার করা হয়নি', 'error'); return; }
            if (sipSession) { showToast('একটি কল ইতিমধ্যে চলছে', 'error'); return; }

            const micOk = await ensureMicPermission();
            if (!micOk) return;

            const ua = initSipUA();
            if (!ua) { showToast('SIP সংযোগ করা যায়নি — কনফিগারেশন চেক করুন', 'error'); return; }

            const eventHandlers = {
                progress: () => {
                    document.getElementById('callStatusText').textContent = '🔔 রিং হচ্ছে... (' + num + ')';
                },
                confirmed: () => {
                    document.getElementById('callStatusText').textContent = '🟢 কথা চলছে — ' + num;
                    startCallTimer();
                },
                ended: () => endCallCleanup(num, 'completed'),
                failed: (e) => {
                    const cause = (e && e.cause) ? e.cause : '';
                    let st = 'failed';
                    if (cause === JsSIP.C.causes.CANCELED) st = 'cancelled';
                    else if (cause === JsSIP.C.causes.NO_ANSWER || cause === JsSIP.C.causes.BUSY) st = 'no_answer';
                    showToast('কল ব্যর্থ: ' + (cause || 'অজানা কারণ'), 'error');
                    endCallCleanup(num, st);
                }
            };

            currentDirection = 'outgoing';
            showCallBar('📞 কল যাচ্ছে... (' + num + ')');
            document.getElementById('callTimer').textContent = '00:00';
            document.getElementById('btnCall').disabled = true;
            document.getElementById('btnCall').classList.add('opacity-40');
            document.getElementById('btnHangup').disabled = false;

            try {
                sipSession = ua.call('sip:' + num + '@' + SIP_CFG.domain, {
                    eventHandlers: eventHandlers,
                    mediaConstraints: { audio: true, video: false },
                    mediaStream: localStream,
                    pcConfig: { iceServers: [{ urls: 'stun:' + SIP_CFG.stun }] }
                });
                sipSession.connection.addEventListener('track', (e) => {
                    if (e.streams && e.streams[0]) {
                        document.getElementById('remoteAudio').srcObject = e.streams[0];
                        startRecording(e.streams[0]); // রিমোট অডিও পাওয়া মাত্র রেকর্ডিং শুরু
                    }
                });
            } catch (e) {
                showToast('কল শুরু করা যায়নি', 'error');
                endCallCleanup(num, 'failed');
            }
        }

        // ---- ইনকামিং কল ----
        function handleIncomingCall(session) {
            if (sipSession) {
                // ইতিমধ্যে একটা কলে আছি — ব্যস্ত সিগন্যাল
                try { session.terminate({ status_code: 486, reason_phrase: 'Busy Here' }); } catch (e) {}
                return;
            }
            sipSession = session;
            currentDirection = 'incoming';
            const num = (session.remote_identity && session.remote_identity.uri && session.remote_identity.uri.user) ? String(session.remote_identity.uri.user) : 'অজানা নাম্বার';

            document.getElementById('incomingNumber').textContent = num;
            document.getElementById('incomingCallBox').classList.remove('hidden');
            startIncomingBeep();
            showToast('📞 ইনকামিং কল: ' + num, 'success');

            // ইনকামিং কলে রিমোট অডিও + রেকর্ডিং (answer করার পর peerconnection তৈরি হয়)
            session.on('peerconnection', (e) => {
                e.peerconnection.addEventListener('track', (ev) => {
                    if (ev.streams && ev.streams[0]) {
                        document.getElementById('remoteAudio').srcObject = ev.streams[0];
                        startRecording(ev.streams[0]);
                    }
                });
            });
            session.on('confirmed', () => {
                stopIncomingBeep();
                document.getElementById('incomingCallBox').classList.add('hidden');
                showCallBar('🟢 কথা চলছে (ইনকামিং) — ' + num);
                document.getElementById('btnHangup').disabled = false;
                document.getElementById('btnCall').disabled = true;
                document.getElementById('btnCall').classList.add('opacity-40');
                startCallTimer();
            });
            session.on('ended', () => {
                stopIncomingBeep();
                document.getElementById('incomingCallBox').classList.add('hidden');
                endCallCleanup(num, 'completed');
            });
            session.on('failed', () => {
                stopIncomingBeep();
                document.getElementById('incomingCallBox').classList.add('hidden');
                // রিসিভ না করলে / কেটে দিলে — মিসড হিসেবে লগ
                endCallCleanup(num, 'no_answer');
            });
        }

        async function answerIncoming() {
            if (!sipSession) return;
            const micOk = await ensureMicPermission();
            if (!micOk) return;
            stopIncomingBeep();
            showCallBar('কানেক্ট হচ্ছে...');
            document.getElementById('callTimer').textContent = '00:00';
            try {
                sipSession.answer({
                    mediaConstraints: { audio: true, video: false },
                    mediaStream: localStream,
                    pcConfig: { iceServers: [{ urls: 'stun:' + SIP_CFG.stun }] }
                });
            } catch (e) {
                showToast('কল রিসিভ করা যায়নি', 'error');
            }
        }

        function rejectIncoming() {
            if (sipSession) {
                try { sipSession.terminate({ status_code: 486, reason_phrase: 'Rejected' }); } catch (e) {}
            }
        }

        function hangupWebCall() {
            if (sipSession) {
                try { sipSession.terminate(); } catch (e) {}
            }
        }

        function endCallCleanup(num, status) {
            if (callTimerInt) { clearInterval(callTimerInt); callTimerInt = null; }
            stopIncomingBeep();
            document.getElementById('incomingCallBox').classList.add('hidden');
            const durationSec = callStartTs ? Math.floor((Date.now() - callStartTs) / 1000) : 0;
            if (durationSec > 0) showToast('কল শেষ — মোট কথা হয়েছে ' + fmtTimer(durationSec) + ' (' + (currentDirection === 'incoming' ? 'ইনকামিং' : 'আউটগোয়িং') + ')', 'success');

            // কল লগ + রেকর্ডিং সেভ (কানেক্ট না হলেও লগ থাকবে, রেকর্ডিং শুধু কথা হলে)
            stopRecordingAndSave(num, durationSec, durationSec > 0 ? 'completed' : status);

            if (localStream) { localStream.getTracks().forEach(t => t.stop()); localStream = null; }
            sipSession = null;
            callStartTs = 0;
            document.getElementById('callStatusBar').classList.add('hidden');
            document.getElementById('callStatusBar').classList.remove('flex');
            document.getElementById('btnCall').disabled = false;
            document.getElementById('btnCall').classList.remove('opacity-40');
            document.getElementById('btnHangup').disabled = true;
        }

        // পেজ লোডে: WSS কনফিগার থাকলে আগে থেকেই রেজিস্টার করে রাখা
        document.addEventListener('DOMContentLoaded', () => {
            if (SIP_CFG.wss && SIP_CFG.username && SIP_CFG.domain && typeof JsSIP !== 'undefined') {
                initSipUA();
            }
            <?php if ($dial_prefill): ?>
            // অর্ডার লিস্ট থেকে আসলে নাম্বার প্রি-ফিল হয়ে ডায়ালারে ফোকাস হবে
            document.getElementById('dialNumber').focus();
            <?php endif; ?>
        });
    </script>
    <?php
}

// -------------------------------------------------------------
// CALL HISTORY SECTION (কল লগ: তারিখ, সময়, টকটাইম, কাস্টমার, কলার)
// -------------------------------------------------------------

function render_call_history_section() {
    $role = get_user_role();
    $is_admin_or_office = ($role === 'admin' || $role === 'office_team');
    ?>
    <div class="bg-slate-800 p-6 rounded-2xl border border-slate-700 shadow-lg">
        <div class="flex flex-wrap items-center gap-3 border-b border-slate-700 pb-3 mb-4">
            <h3 class="text-lg font-bold text-white flex items-center gap-2">
                <i class="fa-solid fa-clock-rotate-left text-violet-400"></i> <span data-i18n="কল হিস্টোরি">কল হিস্টোরি</span>
            </h3>
            <span class="text-[10px] text-slate-500">(৩০ দিনের পুরোনো রেকর্ডিং অটো ডিলিট হয়)</span>
            <div class="ml-auto flex items-center gap-2 flex-wrap">
                <span id="clTotalCalls" class="text-[11px] bg-violet-600/20 text-violet-300 px-3 py-1.5 rounded-full font-bold">মোট কল: —</span>
                <span id="clTotalTalk" class="text-[11px] bg-emerald-600/20 text-emerald-300 px-3 py-1.5 rounded-full font-bold">মোট টকটাইম: —</span>
                <input type="text" id="clSearch" oninput="filterCallLogs()" placeholder="নাম্বার / নাম / কলার খুঁজুন..."
                    class="bg-slate-700 text-white text-xs rounded-lg px-3 py-1.5 border border-slate-600 outline-none w-48">
                <button type="button" onclick="loadCallLogs()" title="রিফ্রেশ" class="bg-slate-700 hover:bg-slate-600 text-slate-300 px-3 py-1.5 rounded-lg text-xs"><i class="fa-solid fa-rotate"></i></button>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full text-left text-xs">
                <thead>
                    <tr class="text-slate-400 border-b border-slate-700">
                        <th class="py-2.5 px-2">তারিখ ও সময়</th>
                        <th class="py-2.5 px-2">কাস্টমার নাম্বার</th>
                        <th class="py-2.5 px-2">কাস্টমার নাম</th>
                        <th class="py-2.5 px-2">অর্ডার আইডি</th>
                        <th class="py-2.5 px-2">কল করেছেন</th>
                        <th class="py-2.5 px-2">টকটাইম</th>
                        <th class="py-2.5 px-2">স্ট্যাটাস</th>
                        <th class="py-2.5 px-2">রেকর্ডিং</th>
                        <th class="py-2.5 px-2 text-right">অ্যাকশন</th>
                    </tr>
                </thead>
                <tbody id="callLogBody">
                    <tr><td colspan="9" class="py-8 text-center text-slate-500">লোড হচ্ছে...</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <script>
        let CALL_LOGS = [], CL_MY_ID = 0, CL_MY_ROLE = '';
        const CL_IS_ADMIN = <?= get_user_role() === 'admin' ? 'true' : 'false' ?>; // ডিলিট: শুধু অ্যাডমিন (অথবা নিজের কল)

        function fmtTalk(sec) {
            sec = parseInt(sec) || 0;
            const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60;
            if (h > 0) return h + ' ঘণ্টা ' + m + ' মি ' + s + ' সে';
            if (m > 0) return m + ' মি ' + s + ' সে';
            return s + ' সেকেন্ড';
        }

        const CL_STATUS = {
            'completed': ['সম্পন্ন', 'bg-emerald-600/20 text-emerald-400'],
            'failed':    ['ব্যর্থ', 'bg-rose-600/20 text-rose-400'],
            'no_answer': ['ধরেনি', 'bg-amber-600/20 text-amber-400'],
            'cancelled': ['বাতিল', 'bg-slate-600/40 text-slate-400']
        };
        const CL_ROLE = { 'admin': 'অ্যাডমিন', 'office_team': 'অফিস টিম', 'agent': 'এজেন্ট' };

        function escHtml(s) {
            return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
        }

        function renderCallLogs(logs) {
            const body = document.getElementById('callLogBody');
            if (!logs.length) {
                body.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500">কোনো কল লগ নেই</td></tr>';
                return;
            }
            body.innerHTML = logs.map(l => {
                const st = CL_STATUS[l.call_status] || CL_STATUS['completed'];
                const canDelete = CL_IS_ADMIN || parseInt(l.caller_id) === CL_MY_ID;
                const roleBn = CL_ROLE[l.caller_role] || escHtml(l.caller_role || '');
                return '<tr class="border-b border-slate-700/50 hover:bg-slate-700/20">' +
                    '<td class="py-2.5 px-2 whitespace-nowrap text-slate-300">' + escHtml(l.call_date || '') + '<br><span class="text-slate-500">' + escHtml(l.call_time || '') + '</span></td>' +
                    '<td class="py-2.5 px-2 whitespace-nowrap font-mono text-white">' +
                        (l.direction === 'incoming'
                            ? '<span class="text-[9px] font-bold bg-sky-600/20 text-sky-400 px-1.5 py-0.5 rounded mr-1" title="ইনকামিং কল"><i class="fa-solid fa-arrow-down"></i> ইন</span>'
                            : '<span class="text-[9px] font-bold bg-emerald-600/20 text-emerald-400 px-1.5 py-0.5 rounded mr-1" title="আউটগোয়িং কল"><i class="fa-solid fa-arrow-up"></i> আউট</span>') +
                        escHtml(l.phone || '') +
                        ' <button onclick="copyText(\'' + escHtml(l.phone || '') + '\')" title="কপি" class="text-slate-500 hover:text-cyan-400 ml-1"><i class="fa-regular fa-copy"></i></button>' +
                        ' <button onclick="redialNumber(\'' + escHtml(l.phone || '') + '\')" title="আবার কল করুন" class="text-slate-500 hover:text-emerald-400 ml-1"><i class="fa-solid fa-phone"></i></button></td>' +
                    '<td class="py-2.5 px-2 text-slate-300">' + (l.customer_name ? escHtml(l.customer_name) : '<span class="text-slate-600">—</span>') + '</td>' +
                    '<td class="py-2.5 px-2">' + (l.order_id ? '<a href="?action=order_detail&id=' + parseInt(l.order_id) + '" class="text-cyan-400 hover:underline font-mono">#' + parseInt(l.order_id) + '</a>' : '<span class="text-slate-600">—</span>') + '</td>' +
                    '<td class="py-2.5 px-2 text-slate-300">' + escHtml(l.caller_name || '') + '<br><span class="text-[10px] text-slate-500">' + roleBn + ' (ID: ' + parseInt(l.caller_id || 0) + ')</span></td>' +
                    '<td class="py-2.5 px-2 whitespace-nowrap font-mono text-white">' + fmtTalk(l.duration_seconds) + '</td>' +
                    '<td class="py-2.5 px-2"><span class="text-[10px] px-2 py-1 rounded-full font-bold ' + st[1] + '">' + st[0] + '</span></td>' +
                    '<td class="py-2.5 px-2">' + (l.recording_url
                        ? '<audio controls preload="none" src="' + escHtml(l.recording_url) + '" class="h-8 w-44"></audio>'
                        : '<span class="text-slate-600 text-[10px]">রেকর্ডিং নেই</span>') + '</td>' +
                    '<td class="py-2.5 px-2 text-right">' + (canDelete
                        ? '<button onclick="deleteCallLog(' + parseInt(l.id) + ')" title="ডিলিট" class="text-rose-500 hover:text-rose-400 p-1.5"><i class="fa-solid fa-trash"></i></button>'
                        : '') + '</td>' +
                '</tr>';
            }).join('');
        }

        function loadCallLogs() {
            fetch('?action=call_log_list')
                .then(r => r.json())
                .then(d => {
                    if (d.status !== 'success') return;
                    CALL_LOGS = d.logs || [];
                    CL_MY_ID = d.my_user_id || 0;
                    CL_MY_ROLE = d.my_role || '';
                    document.getElementById('clTotalCalls').textContent = 'মোট কল: ' + d.total_calls;
                    document.getElementById('clTotalTalk').textContent = 'মোট টকটাইম: ' + fmtTalk(d.total_talk_seconds);
                    filterCallLogs();
                }).catch(() => {
                    document.getElementById('callLogBody').innerHTML = '<tr><td colspan="9" class="py-8 text-center text-rose-400">লোড করা যায়নি</td></tr>';
                });
        }

        function filterCallLogs() {
            const q = (document.getElementById('clSearch').value || '').toLowerCase().trim();
            if (!q) { renderCallLogs(CALL_LOGS); return; }
            renderCallLogs(CALL_LOGS.filter(l =>
                String(l.phone || '').toLowerCase().includes(q) ||
                String(l.customer_name || '').toLowerCase().includes(q) ||
                String(l.caller_name || '').toLowerCase().includes(q) ||
                String(l.order_id || '').includes(q)
            ));
        }

        function redialNumber(phone) {
            const inp = document.getElementById('dialNumber');
            if (inp) {
                inp.value = phone;
                inp.scrollIntoView({ behavior: 'smooth', block: 'center' });
                inp.focus();
                showToast('নাম্বার ডায়ালারে বসানো হয়েছে — কল করুন বাটনে ক্লিক করুন', 'success');
            }
        }

        function deleteCallLog(id) {
            showConfirmModal('এই কল লগ ও রেকর্ডিংটি স্থায়ীভাবে ডিলিট হবে। আপনি কি নিশ্চিত?', () => {
                const fd = new FormData();
                fd.append('id', id);
                fetch('?action=call_log_delete', { method: 'POST', body: fd })
                    .then(r => r.json())
                    .then(d => {
                        if (d.status === 'success') { showToast('কল লগ ডিলিট হয়েছে', 'success'); loadCallLogs(); }
                        else showToast(d.message || 'ডিলিট করা যায়নি', 'error');
                    }).catch(() => showToast('ডিলিট করা যায়নি', 'error'));
            });
        }

        document.addEventListener('DOMContentLoaded', loadCallLogs);
    </script>
    <?php
}


// -------------------------------------------------------------
// ল্যান্ডিং পেজ ফ্লোটিং WhatsApp + ফোন আইকন (ডান পাশে নিচে ফিক্সড)
// -------------------------------------------------------------

function render_floating_contact_icons($show_wa = true, $show_call = true) {
    $wa = trim((string)get_setting('contact_whatsapp'));
    $ph = trim((string)get_setting('contact_phone'));
    $wa_num = preg_replace('/\D/', '', $wa);
    if ((!$show_wa || $wa_num === '') && (!$show_call || $ph === '')) return;
    ?>
    <div style="position: fixed; right: 12px; bottom: 18px; z-index: 9999; display: flex; flex-direction: column; gap: 8px;">
        <?php if ($show_wa && $wa_num !== ''): ?>
        <a href="https://wa.me/<?= htmlspecialchars($wa_num) ?>" target="_blank" rel="noopener" title="WhatsApp-এ মেসেজ করুন" aria-label="WhatsApp"
           style="width: 28px; height: 28px; border-radius: 9999px; background: #25D366; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 14px; box-shadow: 0 3px 9px rgba(37,211,102,.45); text-decoration: none; transition: transform .15s;"
           onmouseover="this.style.transform='scale(1.12)'" onmouseout="this.style.transform='scale(1)'">
            <i class="fa-brands fa-whatsapp"></i>
        </a>
        <?php endif; ?>
        <?php if ($show_call && $ph !== ''): ?>
        <a href="tel:<?= htmlspecialchars($ph) ?>" title="সরাসরি কল করুন" aria-label="Call"
           style="width: 28px; height: 28px; border-radius: 9999px; background: #10b981; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 12px; box-shadow: 0 3px 9px rgba(16,185,129,.45); text-decoration: none; transition: transform .15s;"
           onmouseover="this.style.transform='scale(1.12)'" onmouseout="this.style.transform='scale(1)'">
            <i class="fa-solid fa-phone"></i>
        </a>
        <?php endif; ?>
    </div>
    <?php
}

// -------------------------------------------------------------
// ড্র্যাগ এন্ড ড্রপ পেজ বিল্ডার (Elementor স্টাইল)
// উইজেট: হেডিং, প্যারাগ্রাফ, ইমেজ, বাটন, ভিডিও, কাউন্টডাউন, ফিচার লিস্ট,
// টেস্টিমোনিয়াল, ২-কলাম, ডিভাইডার, স্পেসার, কাস্টম HTML
// -------------------------------------------------------------

function render_page_builder_modal() {
    ?>
    <div id="pageBuilderModal" class="hidden fixed inset-0 z-[200] bg-slate-950 flex flex-col">
        <!-- টপ বার -->
        <div class="flex items-center gap-3 px-4 py-3 bg-slate-900 border-b border-slate-700 shrink-0">
            <span class="text-white font-bold text-sm"><i class="fa-solid fa-wand-magic-sparkles text-fuchsia-400"></i> পেজ বিল্ডার</span>
            <span class="text-[10px] text-slate-500 hidden md:inline">উইজেটে ক্লিক করে যোগ করুন → ক্যানভাসে ড্র্যাগ করে সাজান → ক্লিক করে ডানে সেটিংস বদলান</span>
            <div class="ml-auto flex gap-2">
                <button type="button" onclick="pbSaveAndClose()" class="bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold px-5 py-2 rounded-lg"><i class="fa-solid fa-check"></i> সেভ করে বন্ধ করুন</button>
                <button type="button" onclick="pbClose(false)" class="bg-slate-700 hover:bg-slate-600 text-slate-200 text-xs font-bold px-4 py-2 rounded-lg">বাতিল</button>
            </div>
        </div>
        <div class="flex flex-1 overflow-hidden">
            <!-- বাম: উইজেট প্যালেট -->
            <div class="w-44 shrink-0 bg-slate-900 border-r border-slate-700 overflow-y-auto p-2 space-y-1.5">
                <p class="text-[10px] text-slate-500 font-bold uppercase px-1 mb-1">উইজেট (ক্লিক করে যোগ)</p>
                <?php
                $pb_widgets = [
                    ['heading', 'fa-heading', 'হেডিং'],
                    ['paragraph', 'fa-align-left', 'প্যারাগ্রাফ'],
                    ['image', 'fa-image', 'ইমেজ'],
                    ['button', 'fa-hand-pointer', 'বাটন'],
                    ['video', 'fa-video', 'ভিডিও (YouTube)'],
                    ['countdown', 'fa-hourglass-half', 'কাউন্টডাউন'],
                    ['features', 'fa-list-check', 'ফিচার লিস্ট'],
                    ['testimonial', 'fa-star', 'রিভিউ কার্ড'],
                    ['columns2', 'fa-table-columns', '২ কলাম'],
                    ['divider', 'fa-minus', 'ডিভাইডার'],
                    ['spacer', 'fa-arrows-up-down', 'ফাঁকা জায়গা'],
                    ['html', 'fa-code', 'কাস্টম HTML'],
                ];
                foreach ($pb_widgets as $w): ?>
                <button type="button" onclick="pbAddWidget('<?= $w[0] ?>')" class="w-full flex items-center gap-2 bg-slate-800 hover:bg-violet-600/30 hover:border-violet-500 border border-slate-700 text-slate-200 text-[11px] font-semibold px-2.5 py-2 rounded-lg transition text-left">
                    <i class="fa-solid <?= $w[1] ?> text-violet-400 w-4 text-center"></i> <?= $w[2] ?>
                </button>
                <?php endforeach; ?>
            </div>
            <!-- মাঝে: ক্যানভাস -->
            <div class="flex-1 overflow-y-auto bg-slate-950 p-4">
                <div id="pbCanvas" class="max-w-2xl mx-auto bg-white rounded-xl min-h-[400px] p-4 space-y-1 shadow-2xl"></div>
                <p id="pbEmptyHint" class="text-center text-slate-500 text-xs mt-4">ক্যানভাস খালি — বাম পাশ থেকে উইজেট যোগ করুন</p>
            </div>
            <!-- ডান: সেটিংস -->
            <div class="w-72 shrink-0 bg-slate-900 border-l border-slate-700 overflow-y-auto p-3">
                <p class="text-[10px] text-slate-500 font-bold uppercase mb-2">উইজেট সেটিংস</p>
                <div id="pbSettings" class="space-y-2.5 text-xs text-slate-300">
                    <p class="text-slate-500">ক্যানভাসের কোনো উইজেটে ক্লিক করুন...</p>
                </div>
            </div>
        </div>
    </div>
    <?php
}

function render_page_builder_js() {
    ?>
    <script>
        // ================= পেজ বিল্ডার JS =================
        let PB = []; // উইজেট লিস্ট [{id, type, props}]
        let pbSelected = null;
        let pbCounter = 1;

        const PB_DEFAULTS = {
            heading:     { text: 'আকর্ষণীয় শিরোনাম লিখুন', size: 'h2', color: '#0f172a', align: 'center' },
            paragraph:   { text: 'আপনার প্রোডাক্টের বর্ণনা এখানে লিখুন। কাস্টমার কেন এটা কিনবে — সুবিধাগুলো সুন্দর করে বলুন।', color: '#334155', align: 'center', fontSize: 16 },
            image:       { url: '', width: 100, rounded: true },
            button:      { label: 'এখনই অর্ডার করুন', link: '#order', bg: '#059669', color: '#ffffff', align: 'center', size: 18 },
            video:       { url: '' },
            countdown:   { minutes: 30, label: 'অফার শেষ হতে বাকি', bg: '#dc2626' },
            features:    { items: 'ক্যাশ অন ডেলিভারি\nসারাদেশে হোম ডেলিভারি\n১০০% অরিজিনাল প্রোডাক্ট\nডেলিভারির সময় দেখে নিতে পারবেন', icon: '✅', color: '#0f172a' },
            testimonial: { name: 'সন্তুষ্ট কাস্টমার', text: 'অসাধারণ প্রোডাক্ট! ডেলিভারিও খুব দ্রুত পেয়েছি। সবাইকে রেকমেন্ড করবো।', stars: 5 },
            columns2:    { left: '<p style="text-align:center">বাম কলাম</p>', right: '<p style="text-align:center">ডান কলাম</p>' },
            divider:     { color: '#e2e8f0', thickness: 2 },
            spacer:      { height: 24 },
            html:        { code: '<p style="text-align:center">কাস্টম HTML লিখুন</p>' }
        };

        function pbEsc(t) { return String(t == null ? '' : t).replace(/[&<>"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }
        function pbNl2br(t) { return pbEsc(t).replace(/\n/g, '<br>'); }
        function pbYt(url) {
            const m = String(url || '').match(/(?:youtu\.be\/|v=|embed\/|shorts\/)([A-Za-z0-9_-]{6,})/);
            return m ? m[1] : '';
        }

        // উইজেট → ফাইনাল HTML (প্রিভিউ ও সেভ — দুটোতেই একই)
        function pbWidgetHTML(w) {
            const p = w.props;
            switch (w.type) {
                case 'heading': {
                    const sizes = { h1: 34, h2: 28, h3: 22 };
                    return '<' + p.size + ' style="font-size:' + (sizes[p.size] || 28) + 'px; font-weight:800; color:' + p.color + '; text-align:' + p.align + '; margin:14px 0; line-height:1.3; font-family:\'Hind Siliguri\',sans-serif;">' + pbEsc(p.text) + '</' + p.size + '>';
                }
                case 'paragraph':
                    return '<p style="font-size:' + p.fontSize + 'px; color:' + p.color + '; text-align:' + p.align + '; margin:10px 0; line-height:1.8; font-family:\'Hind Siliguri\',sans-serif;">' + pbNl2br(p.text) + '</p>';
                case 'image':
                    if (!p.url) return '<div style="background:#f1f5f9; border:2px dashed #cbd5e1; border-radius:12px; padding:36px; text-align:center; color:#94a3b8; margin:10px 0;">ইমেজ সিলেক্ট করুন →</div>';
                    return '<div style="text-align:center; margin:12px 0;"><img src="' + pbEsc(p.url) + '" style="width:' + p.width + '%; max-width:100%; ' + (p.rounded ? 'border-radius:14px;' : '') + ' display:inline-block;" loading="lazy"></div>';
                case 'button':
                    return '<div style="text-align:' + p.align + '; margin:14px 0;"><a href="' + pbEsc(p.link) + '" style="display:inline-block; background:' + p.bg + '; color:' + p.color + '; font-size:' + p.size + 'px; font-weight:800; padding:14px 34px; border-radius:12px; text-decoration:none; box-shadow:0 6px 16px rgba(0,0,0,.18); font-family:\'Hind Siliguri\',sans-serif;">' + pbEsc(p.label) + '</a></div>';
                case 'video': {
                    const id = pbYt(p.url);
                    if (!id) return '<div style="background:#f1f5f9; border:2px dashed #cbd5e1; border-radius:12px; padding:36px; text-align:center; color:#94a3b8; margin:10px 0;">YouTube লিংক দিন →</div>';
                    return '<div style="position:relative; padding-bottom:56.25%; height:0; margin:12px 0; border-radius:14px; overflow:hidden;"><iframe src="https://www.youtube.com/embed/' + id + '" style="position:absolute; inset:0; width:100%; height:100%; border:0;" allowfullscreen loading="lazy"></iframe></div>';
                }
                case 'countdown': {
                    const cid = 'cd_' + w.id;
                    return '<div style="background:' + p.bg + '; color:#fff; border-radius:14px; padding:16px; text-align:center; margin:12px 0; font-family:\'Hind Siliguri\',sans-serif;">' +
                        '<div style="font-size:14px; font-weight:700; margin-bottom:4px;">⏰ ' + pbEsc(p.label) + '</div>' +
                        '<div id="' + cid + '" style="font-size:30px; font-weight:900; font-family:monospace; letter-spacing:2px;">--:--</div>' +
                        '<script>(function(){var s=' + (parseInt(p.minutes) || 30) * 60 + ';var e=document.getElementById("' + cid + '");if(!e)return;var t=setInterval(function(){if(s<=0){e.textContent="00:00";clearInterval(t);return;}s--;var m=Math.floor(s/60),c=s%60;e.textContent=String(m).padStart(2,"0")+":"+String(c).padStart(2,"0");},1000);})();<\/script></div>';
                }
                case 'features': {
                    const rows = String(p.items || '').split('\n').filter(x => x.trim() !== '').map(x =>
                        '<div style="display:flex; align-items:flex-start; gap:8px; padding:7px 0; font-size:16px; color:' + p.color + '; font-family:\'Hind Siliguri\',sans-serif;"><span>' + pbEsc(p.icon) + '</span><span>' + pbEsc(x.trim()) + '</span></div>').join('');
                    return '<div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:14px; padding:14px 18px; margin:12px 0;">' + rows + '</div>';
                }
                case 'testimonial': {
                    let stars = '';
                    for (let i = 0; i < 5; i++) stars += '<span style="color:' + (i < (parseInt(p.stars) || 5) ? '#f59e0b' : '#e2e8f0') + '; font-size:18px;">★</span>';
                    return '<div style="background:#fffbeb; border:1px solid #fde68a; border-radius:14px; padding:16px 18px; margin:12px 0; font-family:\'Hind Siliguri\',sans-serif;">' +
                        '<div style="margin-bottom:6px;">' + stars + '</div>' +
                        '<p style="color:#374151; font-size:15px; line-height:1.7; margin:0 0 8px;">"' + pbNl2br(p.text) + '"</p>' +
                        '<p style="color:#92400e; font-weight:800; font-size:13px; margin:0;">— ' + pbEsc(p.name) + '</p></div>';
                }
                case 'columns2':
                    return '<div style="display:flex; gap:12px; flex-wrap:wrap; margin:12px 0;"><div style="flex:1; min-width:220px;">' + p.left + '</div><div style="flex:1; min-width:220px;">' + p.right + '</div></div>';
                case 'divider':
                    return '<hr style="border:none; border-top:' + p.thickness + 'px solid ' + p.color + '; margin:16px 0;">';
                case 'spacer':
                    return '<div style="height:' + (parseInt(p.height) || 24) + 'px;"></div>';
                case 'html':
                    return '<div style="margin:8px 0;">' + p.code + '</div>';
            }
            return '';
        }

        function pbAddWidget(type) {
            PB.push({ id: pbCounter++, type: type, props: JSON.parse(JSON.stringify(PB_DEFAULTS[type])) });
            pbRenderCanvas();
            pbSelect(PB[PB.length - 1].id);
            if (type === 'image') openMediaPicker('pb-prop-url', null); // ইমেজ যোগ করলেই পিকার
        }

        function pbRenderCanvas() {
            const cv = document.getElementById('pbCanvas');
            document.getElementById('pbEmptyHint').style.display = PB.length ? 'none' : 'block';
            cv.innerHTML = '';
            PB.forEach(w => {
                const div = document.createElement('div');
                div.className = 'pb-block relative group border-2 rounded-lg transition ' + (pbSelected === w.id ? 'border-violet-500' : 'border-transparent hover:border-violet-300');
                div.draggable = true;
                div.dataset.wid = w.id;
                div.innerHTML = pbWidgetHTML(w) +
                    '<div class="absolute -top-3 right-1 hidden group-hover:flex gap-1 z-10">' +
                    '<button type="button" onclick="event.stopPropagation(); pbDuplicate(' + w.id + ')" title="ডুপ্লিকেট" class="bg-sky-600 text-white text-[10px] w-6 h-6 rounded shadow"><i class="fa-regular fa-copy"></i></button>' +
                    '<button type="button" onclick="event.stopPropagation(); pbDelete(' + w.id + ')" title="ডিলিট" class="bg-rose-600 text-white text-[10px] w-6 h-6 rounded shadow"><i class="fa-solid fa-trash"></i></button>' +
                    '<span title="টেনে সাজান" class="bg-slate-700 text-white text-[10px] w-6 h-6 rounded shadow cursor-grab flex items-center justify-center"><i class="fa-solid fa-grip-vertical"></i></span>' +
                    '</div>';
                div.onclick = () => pbSelect(w.id);
                div.addEventListener('dragstart', () => { div.classList.add('opacity-40'); cv.dataset.dragging = w.id; });
                div.addEventListener('dragend', () => { div.classList.remove('opacity-40'); delete cv.dataset.dragging; });
                cv.appendChild(div);
            });
        }

        document.addEventListener('dragover', function (e) {
            const cv = document.getElementById('pbCanvas');
            if (!cv || !cv.dataset.dragging || !cv.contains(e.target)) return;
            e.preventDefault();
            const dragId = parseInt(cv.dataset.dragging);
            const after = Array.from(cv.querySelectorAll('.pb-block:not(.opacity-40)')).find(b => {
                const r = b.getBoundingClientRect();
                return e.clientY < r.top + r.height / 2;
            });
            const from = PB.findIndex(x => x.id === dragId);
            if (from < 0) return;
            const item = PB.splice(from, 1)[0];
            if (after) {
                const to = PB.findIndex(x => x.id === parseInt(after.dataset.wid));
                PB.splice(to, 0, item);
            } else PB.push(item);
            pbRenderCanvas();
        });

        function pbDuplicate(id) {
            const i = PB.findIndex(x => x.id === id);
            if (i < 0) return;
            PB.splice(i + 1, 0, { id: pbCounter++, type: PB[i].type, props: JSON.parse(JSON.stringify(PB[i].props)) });
            pbRenderCanvas();
        }
        function pbDelete(id) {
            PB = PB.filter(x => x.id !== id);
            if (pbSelected === id) { pbSelected = null; document.getElementById('pbSettings').innerHTML = '<p class="text-slate-500">ক্যানভাসের কোনো উইজেটে ক্লিক করুন...</p>'; }
            pbRenderCanvas();
        }

        // ---- সেটিংস প্যানেল ----
        const PB_FIELDS = {
            heading:     [['text','textarea','লেখা'], ['size','select','সাইজ', {h1:'বড় (H1)',h2:'মাঝারি (H2)',h3:'ছোট (H3)'}], ['color','color','রঙ'], ['align','select','অ্যালাইন', {left:'বামে',center:'মাঝে',right:'ডানে'}]],
            paragraph:   [['text','textarea','লেখা'], ['fontSize','number','ফন্ট সাইজ (px)'], ['color','color','রঙ'], ['align','select','অ্যালাইন', {left:'বামে',center:'মাঝে',right:'ডানে'}]],
            image:       [['url','media','ইমেজ URL'], ['width','number','প্রস্থ (%)'], ['rounded','checkbox','গোল কোণা']],
            button:      [['label','text','বাটনের লেখা'], ['link','text','লিংক (#order = অর্ডার ফর্মে)'], ['bg','color','ব্যাকগ্রাউন্ড'], ['color','color','লেখার রঙ'], ['size','number','ফন্ট সাইজ (px)'], ['align','select','অ্যালাইন', {left:'বামে',center:'মাঝে',right:'ডানে'}]],
            video:       [['url','text','YouTube লিংক']],
            countdown:   [['label','text','লেবেল'], ['minutes','number','কত মিনিটের কাউন্টডাউন'], ['bg','color','ব্যাকগ্রাউন্ড']],
            features:    [['items','textarea','ফিচারসমূহ (প্রতি লাইনে একটা)'], ['icon','text','আইকন (ইমোজি)'], ['color','color','লেখার রঙ']],
            testimonial: [['name','text','কাস্টমারের নাম'], ['text','textarea','রিভিউ'], ['stars','number','স্টার (১-৫)']],
            columns2:    [['left','textarea','বাম কলাম (HTML)'], ['right','textarea','ডান কলাম (HTML)']],
            divider:     [['color','color','রঙ'], ['thickness','number','মোটা (px)']],
            spacer:      [['height','number','উচ্চতা (px)']],
            html:        [['code','textarea','HTML কোড']]
        };

        function pbSelect(id) {
            pbSelected = id;
            const w = PB.find(x => x.id === id);
            if (!w) return;
            pbRenderCanvas();
            const box = document.getElementById('pbSettings');
            box.innerHTML = '';
            (PB_FIELDS[w.type] || []).forEach(([key, kind, label, opts]) => {
                const wrap = document.createElement('div');
                let inner = '<label class="block text-slate-400 font-bold mb-1">' + label + '</label>';
                const v = w.props[key];
                if (kind === 'textarea') inner += '<textarea data-k="' + key + '" rows="4" class="pb-inp w-full bg-slate-800 border border-slate-600 rounded-lg px-2.5 py-2 text-white outline-none">' + pbEsc(v) + '</textarea>';
                else if (kind === 'select') {
                    inner += '<select data-k="' + key + '" class="pb-inp w-full bg-slate-800 border border-slate-600 rounded-lg px-2.5 py-2 text-white outline-none">';
                    Object.keys(opts).forEach(o => inner += '<option value="' + o + '"' + (v === o ? ' selected' : '') + '>' + opts[o] + '</option>');
                    inner += '</select>';
                }
                else if (kind === 'color') inner += '<input type="color" data-k="' + key + '" value="' + pbEsc(v) + '" class="pb-inp w-full h-9 bg-slate-800 border border-slate-600 rounded-lg cursor-pointer">';
                else if (kind === 'number') inner += '<input type="number" data-k="' + key + '" value="' + pbEsc(v) + '" class="pb-inp w-full bg-slate-800 border border-slate-600 rounded-lg px-2.5 py-2 text-white outline-none">';
                else if (kind === 'checkbox') inner += '<label class="flex items-center gap-2"><input type="checkbox" data-k="' + key + '" ' + (v ? 'checked' : '') + ' class="pb-inp rounded text-violet-500"> হ্যাঁ</label>';
                else if (kind === 'media') inner += '<div class="flex gap-1.5"><input type="text" id="pb-prop-url" data-k="' + key + '" value="' + pbEsc(v) + '" class="pb-inp flex-1 bg-slate-800 border border-slate-600 rounded-lg px-2 py-2 text-white outline-none font-mono text-[10px]"><button type="button" onclick="openMediaPicker(\'pb-prop-url\', null)" class="bg-sky-600 text-white px-2.5 rounded-lg"><i class="fa-solid fa-images"></i></button></div>';
                else inner += '<input type="text" data-k="' + key + '" value="' + pbEsc(v) + '" class="pb-inp w-full bg-slate-800 border border-slate-600 rounded-lg px-2.5 py-2 text-white outline-none">';
                wrap.innerHTML = inner;
                box.appendChild(wrap);
            });
            box.querySelectorAll('.pb-inp').forEach(inp => {
                const ev = (inp.type === 'checkbox' || inp.tagName === 'SELECT' || inp.type === 'color') ? 'change' : 'input';
                inp.addEventListener(ev, () => {
                    const w2 = PB.find(x => x.id === pbSelected);
                    if (!w2) return;
                    w2.props[inp.dataset.k] = inp.type === 'checkbox' ? inp.checked : inp.value;
                    pbRenderCanvas();
                });
            });
        }

        // ---- খোলা / সেভ / বন্ধ ----
        function openPageBuilder() {
            const saved = document.getElementById('builder-json-input').value;
            PB = [];
            pbCounter = 1;
            if (saved) {
                try {
                    PB = JSON.parse(saved) || [];
                    PB.forEach(w => { if (w.id >= pbCounter) pbCounter = w.id + 1; });
                } catch (e) { PB = []; }
            }
            pbSelected = null;
            document.getElementById('pbSettings').innerHTML = '<p class="text-slate-500">ক্যানভাসের কোনো উইজেটে ক্লিক করুন...</p>';
            document.getElementById('pageBuilderModal').classList.remove('hidden');
            document.body.style.overflow = 'hidden';
            pbRenderCanvas();
        }
        function pbClose(saved) {
            document.getElementById('pageBuilderModal').classList.add('hidden');
            document.body.style.overflow = '';
            if (!saved) showToast('বিল্ডার বন্ধ — কোনো পরিবর্তন সেভ হয়নি', 'error');
        }
        function pbSaveAndClose() {
            // ক্যানভাসের অ্যাকশন বাটন বাদ দিয়ে শুধু উইজেট HTML জোড়া লাগানো
            const html = PB.map(w => pbWidgetHTML(w)).join('\n');
            document.getElementById('page-content').value = html;
            document.getElementById('builder-json-input').value = PB.length ? JSON.stringify(PB) : '';
            pbClose(true);
            showToast('বিল্ডারের ডিজাইন কন্টেন্ট বক্সে সেভ হয়েছে — এবার পেজটা "সেভ" করতে ভুলবেন না!', 'success');
        }
    </script>
    <?php
}