<?php // متغيرات: $stats ?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-4">
        <div>
            <h3 class="mb-1 fw-bold">
                <i class="bi bi-megaphone me-2 text-success"></i>
                <?= __('marketing.title', 'WhatsApp Marketing Campaign') ?>
            </h3>
            <p class="text-muted mb-0 small"><?= __('marketing.subtitle', 'Send promotional messages to your customers in one click') ?></p>
        </div>
        <a href="/admin/customers" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-arrow-right me-1"></i>
            <?= __('customers.back_to_list', 'Customer List') ?>
        </a>
    </div>

    <div class="row g-4">

        <!-- Campaign Builder -->
        <div class="col-lg-7">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-pencil-square me-2 text-muted"></i>
                        <?= __('marketing.compose', 'Compose Campaign') ?>
                    </h6>
                </div>
                <div class="card-body">

                    <!-- Campaign Name -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold"><?= __('marketing.campaign_name', 'Campaign Name') ?></label>
                        <input type="text" id="campaignName" class="form-control"
                               value="<?= __('marketing.default_campaign', 'Promotional Campaign') ?> <?= date('d/m/Y') ?>"
                               placeholder="<?= __('marketing.campaign_name_placeholder', 'e.g. Ramadan Offer 2025') ?>">
                    </div>

                    <!-- Audience Filters -->
                    <div class="mb-3">
                        <label class="form-label fw-semibold"><?= __('marketing.audience', 'Target Audience') ?></label>
                        <div class="row g-2">
                            <div class="col-md-4">
                                <select id="filterTag" class="form-select form-select-sm" onchange="updatePreview()">
                                    <option value=""><?= __('marketing.all_customers', 'All customers') ?></option>
                                    <option value="vip"><?= __('customers.tag.vip', 'VIP only') ?></option>
                                    <option value="returning"><?= __('customers.tag.returning', 'Returning only') ?></option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <input type="number" id="filterMinOrders" class="form-control form-control-sm"
                                       placeholder="<?= __('marketing.min_orders_filter', 'Min orders (e.g. 2)') ?>"
                                       min="0" onchange="updatePreview()">
                            </div>
                            <div class="col-md-4">
                                <div class="d-flex align-items-center gap-2 py-1">
                                    <span class="text-muted small"><?= __('marketing.will_reach', 'Will reach:') ?></span>
                                    <span id="previewCount" class="badge bg-primary px-2 py-1 fs-6">
                                        <?= number_format((int)($stats['total'] ?? 0)) ?>
                                    </span>
                                    <span class="text-muted small"><?= __('marketing.recipients', 'recipients') ?></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Message -->
                    <div class="mb-3">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <label class="form-label fw-semibold mb-0"><?= __('marketing.message', 'Message') ?></label>
                            <span class="text-muted small"><span id="charCount">0</span> <?= __('marketing.chars', 'chars') ?></span>
                        </div>

                        <!-- Quick templates -->
                        <div class="d-flex gap-1 flex-wrap mb-2">
                            <?php
                            $isAr = \Core\System\Language::code() === 'ar';
                            $quickTpls = $isAr ? [
                                __('marketing.tpl.offer','عرض خاص')       => "مرحباً {name} 👋\nعندنا عرض خاص لك هذا الأسبوع! 🔥\n\n✨ [اكتب تفاصيل العرض هنا]\n\nاطلب الان: [رابط الطلب]\n\n{store_name}",
                                __('marketing.tpl.new_product','منتج جديد') => "مرحباً {name} 🆕\nوصلنا بمنتج جديد وحشتنا فيه! \n\n[اسم المنتج ومميزاته]\n\nشوفه اولا: [رابط]\n\n{store_name}",
                                __('marketing.tpl.discount','تخفيض')        => "مرحباً {name} 💰\nخصم حصري لعملاؤنا المميزين!\n\n🏷️ خصم [النسبة]% على جميع المنتجات\nالعرض صالح حتى: [التاريخ]\n\nما تفوتش! {store_name}",
                            ] : [
                                __('marketing.tpl.offer','Special Offer')    => "Hey {name}! 👋\nWe have an exclusive offer just for you this week! 🔥\n\n✨ [Describe your offer here]\n\nOrder now: [link]\n\n{store_name}",
                                __('marketing.tpl.new_product','New Product')=> "Hey {name}! 🆕\nWe just launched something amazing!\n\n[Product name & details]\n\nCheck it out: [link]\n\n{store_name}",
                                __('marketing.tpl.discount','Discount')      => "Hey {name}! 💰\nExclusive discount for our valued customers!\n\n🏷️ [X]% off on all products\nValid until: [date]\n\nDon't miss out! {store_name}",
                            ];
                            foreach ($quickTpls as $name => $tpl): ?>
                            <button type="button" class="btn btn-outline-secondary btn-sm"
                                    onclick="setTemplate(<?= htmlspecialchars(json_encode($tpl)) ?>)">
                                <?= htmlspecialchars($name) ?>
                            </button>
                            <?php endforeach; ?>
                        </div>

                        <!-- AI Generator Button -->
                        <div id="aiGeneratorSection" class="border rounded-3 p-3 mb-3 bg-light d-none">
                            <div class="d-flex align-items-center gap-2 mb-3">
                                <i class="bi bi-robot text-primary fs-5"></i>
                                <span class="fw-semibold"><?= __('ai.generate_marketing','Generate with AI') ?></span>
                                <span class="badge bg-primary-subtle text-primary border border-primary-subtle small ms-auto">
                                    <?= __('ai.provider_badge','AI Powered') ?>
                                </span>
                            </div>
                            <div class="row g-2 mb-2">
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold"><?= __('ai.product_name','Product / Offer') ?> *</label>
                                    <input type="text" id="aiProduct" class="form-control form-control-sm"
                                           placeholder="<?= __('ai.product_placeholder','e.g. Summer shoes collection') ?>">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label small fw-semibold"><?= __('ai.offer_details','Offer Details') ?></label>
                                    <input type="text" id="aiOffer" class="form-control form-control-sm"
                                           placeholder="<?= __('ai.offer_placeholder','e.g. 30% off, free delivery') ?>">
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label small fw-semibold">
                                        <i class="bi bi-layout-text-window me-1 text-muted"></i>
                                        <?= __('ai.template_type','Message Type') ?>
                                    </label>
                                    <select id="aiTemplateType" class="form-select form-select-sm">
                                        <option value="offer"><?= __('marketing.tpl.offer','Special Offer') ?> 🎁</option>
                                        <option value="new_product"><?= __('marketing.tpl.new_product','New Product') ?> 🆕</option>
                                        <option value="discount"><?= __('marketing.tpl.discount','Discount') ?> 💰</option>
                                        <option value="custom"><?= __('ai.template_custom','Custom') ?> ✏️</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label small fw-semibold"><?= __('ai.tone','Tone') ?></label>
                                    <select id="aiTone" class="form-select form-select-sm">
                                        <option value="persuasive"><?= __('ai.tone.persuasive','Persuasive') ?></option>
                                        <option value="urgent"><?= __('ai.tone.urgent','Urgent') ?></option>
                                        <option value="friendly"><?= __('ai.tone.friendly','Friendly') ?></option>
                                        <option value="luxury"><?= __('ai.tone.luxury','Luxury') ?></option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label small fw-semibold"><?= __('ai.cta','Call to Action') ?></label>
                                    <input type="text" id="aiCta" class="form-control form-control-sm"
                                           placeholder="<?= __('ai.cta_placeholder','e.g. Order now on our website') ?>">
                                </div>
                                <div class="col-md-4 d-flex align-items-end">
                                    <div class="form-check form-switch mb-1">
                                        <input class="form-check-input" type="checkbox" id="aiEmoji" checked>
                                        <label class="form-check-label small" for="aiEmoji"><?= __('ai.use_emoji','Use Emojis') ?></label>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary btn-sm px-3" onclick="generateWithAI()" id="aiGenBtn">
                                <i class="bi bi-stars me-1"></i>
                                <?= __('ai.generate_btn','Generate Message') ?>
                            </button>
                            <div id="aiGenResult" class="mt-2 d-none"></div>
                        </div>

                        <!-- Toggle AI button -->
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="small text-muted"><?= __('marketing.message','Message') ?></span>
                            <?php $aiActive = $aiActive ?? false; ?>
                            <?php if ($aiActive): ?>
                            <button type="button" class="btn btn-sm btn-outline-primary px-2 py-0"
                                    onclick="toggleAiSection()" id="toggleAiBtn">
                                <i class="bi bi-stars me-1"></i><?= __('ai.write_with_ai','Write with AI') ?>
                            </button>
                            <?php endif; ?>
                        </div>

                        <textarea id="campaignMessage" class="form-control font-monospace"
                                  rows="8" dir="auto"
                                  placeholder="<?= __('marketing.message_placeholder', 'Write your message here...\nUse {name} to personalize') ?>"
                                  oninput="document.getElementById('charCount').textContent=this.value.length; updatePreviewMsg()"></textarea>

                        <div class="mt-1 small text-muted">
                            <?= __('marketing.variables_hint', 'Variables') ?>:
                            <code>{name}</code> <code>{store_name}</code>
                        </div>
                    </div>

                    <!-- Send Button -->
                    <div class="d-flex gap-3 align-items-center">
                        <button type="button" class="btn btn-success btn-lg px-4" onclick="sendCampaign()" id="sendBtn">
                            <i class="bi bi-whatsapp me-2"></i>
                            <?= __('marketing.send_now', 'Send Now') ?>
                        </button>
                        <div id="sendProgress" class="d-none">
                            <div class="spinner-border spinner-border-sm text-success me-2"></div>
                            <span class="text-muted small" id="sendProgressText"><?= __('marketing.sending', 'Sending...') ?></span>
                        </div>
                    </div>

                    <!-- Result -->
                    <div id="sendResult" class="mt-3 d-none"></div>

                </div>
            </div>
        </div>

        <!-- Preview + Tips -->
        <div class="col-lg-5">

            <!-- Message Preview -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-phone me-2 text-muted"></i>
                        <?= __('marketing.preview', 'Message Preview') ?>
                    </h6>
                </div>
                <div class="card-body">
                    <div class="bg-success bg-opacity-10 rounded-3 p-3" style="min-height:120px">
                        <div class="d-flex align-items-center gap-2 mb-2">
                            <div class="rounded-circle bg-success d-flex align-items-center justify-content-center"
                                 style="width:32px;height:32px">
                                <i class="bi bi-shop text-white small"></i>
                            </div>
                            <span class="fw-semibold small"><?= __('marketing.your_store', 'Your Store') ?></span>
                        </div>
                        <div id="msgPreview" class="small" style="white-space:pre-wrap;word-break:break-word">
                            <span class="text-muted"><?= __('marketing.preview_empty', 'Your message will appear here...') ?></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Customer Segments -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h6 class="mb-0 fw-semibold">
                        <i class="bi bi-bar-chart me-2 text-muted"></i>
                        <?= __('marketing.segments', 'Customer Segments') ?>
                    </h6>
                </div>
                <div class="card-body">
                    <?php
                    $segs = [
                        ['label'=>__('marketing.seg.all','All Customers'),       'count'=>$stats['total']        ?? 0, 'color'=>'primary',  'filter'=>''],
                        ['label'=>__('marketing.seg.returning','Returning'),      'count'=>$stats['returning']    ?? 0, 'color'=>'success',  'filter'=>'returning'],
                        ['label'=>__('marketing.seg.vip','VIP (10+ orders)'),    'count'=>$stats['vip']          ?? 0, 'color'=>'warning',  'filter'=>'vip'],
                        ['label'=>__('marketing.seg.new','New Customers'),        'count'=>$stats['new_customers']?? 0, 'color'=>'info',     'filter'=>''],
                    ];
                    foreach ($segs as $seg): ?>
                    <div class="d-flex justify-content-between align-items-center mb-2 py-1">
                        <button type="button" class="btn btn-sm btn-outline-<?= $seg['color'] ?> px-2"
                                onclick="selectSegment('<?= $seg['filter'] ?>')">
                            <?= $seg['label'] ?>
                        </button>
                        <span class="fw-bold"><?= number_format((int)$seg['count']) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Tips -->
            <div class="card border-0 shadow-sm border-start border-4 border-warning">
                <div class="card-body">
                    <h6 class="fw-semibold mb-3">
                        <i class="bi bi-lightbulb-fill text-warning me-2"></i>
                        <?= __('marketing.tips_title', 'Best Practices') ?>
                    </h6>
                    <ul class="list-unstyled mb-0 small text-muted">
                        <li class="mb-2">✅ <?= __('marketing.tip1', 'Keep messages short and clear (under 160 chars)') ?></li>
                        <li class="mb-2">✅ <?= __('marketing.tip2', 'Personalize with {name} for better engagement') ?></li>
                        <li class="mb-2">✅ <?= __('marketing.tip3', 'Target returning customers for higher conversion') ?></li>
                        <li class="mb-2">⚠️ <?= __('marketing.tip4', 'Respect opt-out requests immediately') ?></li>
                        <li>⚠️ <?= __('marketing.tip5', 'Do not send more than 1 campaign per week') ?></li>
                    </ul>
                </div>
            </div>

        </div>
    </div>

</div>
</section>
</div>

<script>
function updatePreview() {
    const tag       = document.getElementById('filterTag').value;
    const minOrders = document.getElementById('filterMinOrders').value;
    const params    = new URLSearchParams({ tag, min_orders: minOrders });

    fetch('/admin/customers/preview-count?' + params, { credentials: 'same-origin' })
        .then(r => r.json())
        .then(d => { document.getElementById('previewCount').textContent = d.count.toLocaleString(); })
        .catch(() => {});
}

function updatePreviewMsg() {
    const msg = document.getElementById('campaignMessage').value;
    const preview = document.getElementById('msgPreview');
    if (!msg.trim()) {
        preview.innerHTML = '<span class="text-muted"><?= __("marketing.preview_empty","Your message will appear here...") ?></span>';
        return;
    }
    // استبدل المتغيرات بأمثلة
    let sample = msg
        .replace(/\{name\}/g,       '<strong><?= __("marketing.sample_name","Ahmed") ?></strong>')
        .replace(/\{store_name\}/g, '<strong><?= __("marketing.your_store","Your Store") ?></strong>');
    preview.innerHTML = sample.replace(/\n/g, '<br>');
}

function setTemplate(tpl) {
    document.getElementById('campaignMessage').value = tpl;
    document.getElementById('charCount').textContent = tpl.length;
    updatePreviewMsg();
}

function selectSegment(tag) {
    document.getElementById('filterTag').value = tag;
    updatePreview();
}

function sendCampaign() {
    const message  = document.getElementById('campaignMessage').value.trim();
    const campaign = document.getElementById('campaignName').value.trim();
    const tag      = document.getElementById('filterTag').value;
    const minOrders = document.getElementById('filterMinOrders').value;
    const count    = parseInt(document.getElementById('previewCount').textContent.replace(/,/g, ''));

    if (!message) {
        alert('<?= __("marketing.error.empty_message","Please write a message first") ?>');
        return;
    }

    if (count === 0) {
        alert('<?= __("marketing.error.no_recipients","No customers match the selected filters") ?>');
        return;
    }

    const confirmed = confirm(
        '<?= __("marketing.confirm_send","Send campaign to") ?> ' + count +
        ' <?= __("marketing.recipients","recipients") ?>?'
    );
    if (!confirmed) return;

    const btn = document.getElementById('sendBtn');
    const progress = document.getElementById('sendProgress');
    const result = document.getElementById('sendResult');

    btn.disabled = true;
    progress.classList.remove('d-none');
    result.className = 'd-none';

    const form = new FormData();
    form.append('message',    message);
    form.append('campaign',   campaign);
    form.append('tag',        tag);
    form.append('min_orders', minOrders);
    form.append('_csrf', document.querySelector('input[name=_csrf]')?.value || '');

    fetch('/admin/customers/send-campaign', { method: 'POST', body: form, credentials: 'same-origin' })
        .then(r => r.json())
        .then(res => {
            progress.classList.add('d-none');
            btn.disabled = false;

            if (res.success) {
                result.className = 'mt-3 alert alert-success';
                result.innerHTML =
                    '<i class="bi bi-check-circle me-2"></i>' +
                    '<strong><?= __("marketing.result.sent","Sent") ?>: ' + res.sent + '</strong>' +
                    (res.failed > 0 ? ' | <?= __("marketing.result.failed","Failed") ?>: ' + res.failed : '') +
                    ' / <?= __("marketing.result.total","Total") ?>: ' + res.total;
            } else {
                result.className = 'mt-3 alert alert-danger';
                result.innerHTML = '<i class="bi bi-x-circle me-2"></i>' + (res.error || '<?= __("marketing.error.failed","Send failed") ?>');
            }
        })
        .catch(() => {
            progress.classList.add('d-none');
            btn.disabled = false;
            result.className = 'mt-3 alert alert-danger';
            result.textContent = '<?= __("errors.network","Network error") ?>';
        });
}

// Init preview count
updatePreview();

// AI Generator
function toggleAiSection() {
    const sec = document.getElementById('aiGeneratorSection');
    const btn = document.getElementById('toggleAiBtn');
    if (sec.classList.contains('d-none')) {
        sec.classList.remove('d-none');
        btn.innerHTML = '<i class="bi bi-x me-1"></i><?= __("ai.close","Close") ?>';
        btn.classList.replace('btn-outline-primary','btn-outline-secondary');
    } else {
        sec.classList.add('d-none');
        btn.innerHTML = '<i class="bi bi-stars me-1"></i><?= __("ai.write_with_ai","Write with AI") ?>';
        btn.classList.replace('btn-outline-secondary','btn-outline-primary');
    }
}

function generateWithAI() {
    const product      = document.getElementById('aiProduct').value.trim();
    const offer        = document.getElementById('aiOffer').value.trim();
    const tone         = document.getElementById('aiTone').value;
    const templateType = document.getElementById('aiTemplateType')?.value || 'offer';
    const cta          = document.getElementById('aiCta').value.trim();
    const emoji        = document.getElementById('aiEmoji').checked ? '1' : '0';
    const result  = document.getElementById('aiGenResult');
    const btn     = document.getElementById('aiGenBtn');

    if (!product) {
        result.className = 'mt-2 alert alert-warning py-2 small';
        result.textContent = '<?= __("ai.product_required","Please enter product name") ?>';
        return;
    }

    const origBtnHtml = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span> <?= __("ai.generating","Generating...") ?>';
    result.className = 'd-none';

    const form = new FormData();
    form.append('product',       product);
    form.append('offer',         offer);
    form.append('tone',          tone);
    form.append('template_type', templateType);
    form.append('cta',           cta);
    form.append('emoji',         emoji);
    form.append('lang',          document.documentElement.lang || 'ar');
    form.append('_csrf',         document.querySelector('input[name=_csrf]')?.value || '');

    fetch('/admin/ai/generate-marketing', { method: 'POST', body: form, credentials: 'same-origin' })
        .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
        .then(res => {
            btn.disabled = false;
            btn.innerHTML = origBtnHtml;
            if (res.success) {
                result.className = 'mt-2';
                result.innerHTML = `
                    <div class="border rounded-3 bg-white mb-3" style="position:relative">
                        <div class="d-flex justify-content-between align-items-center px-3 pt-2 pb-1 border-bottom">
                            <span class="small fw-semibold text-success"><i class="bi bi-stars me-1"></i><?= __("ai.generated","AI Generated") ?></span>
                            <button type="button" class="btn btn-sm btn-outline-secondary py-0 px-2" onclick="copyAiMsg(this)" title="Copy">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                        <textarea class="form-control border-0 rounded-0 font-monospace"
                                  rows="10" dir="auto" style="resize:vertical;min-height:220px"
                                  id="aiResultText">${res.message.replace(/</g,'&lt;').replace(/&lt;br&gt;/g,'\n')}</textarea>
                    </div>
                    <button type="button" class="btn btn-success px-4" onclick="useAiMessage(this)">
                        <i class="bi bi-check-circle me-2"></i><?= __("ai.use_message","Use this message") ?>
                    </button>
                    <button type="button" class="btn btn-outline-secondary ms-2" onclick="generateWithAI()">
                        <i class="bi bi-arrow-clockwise me-1"></i><?= __("ai.regenerate","Regenerate") ?>
                    </button>`;
                result._msg = res.message;
            } else {
                result.className = 'mt-2 alert alert-danger py-2 small';
                result.textContent = res.error || '<?= __("ai.error","AI error") ?>';
            }
        })
        .catch(() => {
            btn.disabled = false;
            btn.innerHTML = origBtnHtml;
            result.className = 'mt-2 alert alert-danger py-2 small';
            result.textContent = '<?= __("errors.network","Network error") ?>';
        });
}

function copyAiMsg(btn) {
    const ta = document.getElementById('aiResultText');
    if (!ta) return;
    navigator.clipboard.writeText(ta.value).then(() => {
        btn.innerHTML = '<i class="bi bi-check2"></i>';
        setTimeout(() => btn.innerHTML = '<i class="bi bi-clipboard"></i>', 2000);
    });
}

function useAiMessage(btn) {
    const textarea  = document.getElementById('campaignMessage');
    const aiTextarea = document.getElementById('aiResultText');
    const msg = aiTextarea ? aiTextarea.value : '';
    if (!msg) return;
    textarea.value = msg;
    document.getElementById('charCount').textContent = msg.length;
    updatePreviewMsg();
    toggleAiSection();
}
</script>