<?php $__env->startSection('title', 'Deals of the Day'); ?>

<?php $__env->startSection('content'); ?>
<h1>Deals of the Day</h1>
<?php if(session('success')): ?>
    <p class="alert alert-success" style="margin-bottom:1rem;"><?php echo e(session('success')); ?></p>
<?php endif; ?>

<div class="deals-toolbar" style="margin-bottom:1.5rem;">
    <label for="search">Search products by title (Shopify)</label>
    <div style="display:flex; flex-wrap:wrap; gap:0.5rem; align-items:center; margin-top:0.25rem;">
        <input type="text" id="search" placeholder="Product title..." style="flex:1; min-width:200px; padding:0.5rem 0.75rem; border:1px solid #d1d5db; border-radius:6px;">
        <button type="button" id="btnSearch" class="btn btn-primary">Search</button>
    </div>
</div>

<div id="searchResults" style="margin-bottom:1.5rem; display:none;">
    <h2 style="font-size:1.1rem;">Search results</h2>
    <p id="searchStatus" style="font-size:0.9rem; color:#6b7280;"></p>
    <ul id="resultList" style="list-style:none; padding:0; max-height:300px; overflow-y:auto; border:1px solid #e5e7eb; border-radius:6px; padding:0.5rem;"></ul>
</div>

<div id="selectedSection" style="margin-bottom:1.5rem; display:none;">
    <h2 style="font-size:1.1rem;">Selected products</h2>
    <ul id="selectedList" style="list-style:none; padding:0;"></ul>

    <div style="margin-top:1rem; padding:1rem; background:#f9fafb; border-radius:8px; border:1px solid #e5e7eb;">
        <h3 style="font-size:1rem; margin-top:0; margin-bottom:0.75rem;">Deal rules</h3>
        <div style="display:flex; flex-wrap:wrap; gap:1rem; align-items:flex-end;">
            <div>
                <label style="display:block; font-size:0.85rem; margin-bottom:0.25rem;">Profit on cost</label>
                <div style="display:flex; gap:0.5rem; align-items:center;">
                    <select id="profitType" style="padding:0.4rem; border:1px solid #d1d5db; border-radius:6px;">
                        <option value="percentage">Percentage %</option>
                        <option value="fixed">Fixed $</option>
                    </select>
                    <input type="number" id="profitValue" min="0" step="0.01" value="95" placeholder="e.g. 95 or 50" style="width:100px; padding:0.4rem; border:1px solid #d1d5db; border-radius:6px;">
                </div>
            </div>
            <div>
                <label style="display:block; font-size:0.85rem; margin-bottom:0.25rem;">Compare at discount %</label>
                <input type="number" id="compareDiscountPercent" min="0" max="99.99" step="0.01" value="40" placeholder="e.g. 40" style="width:80px; padding:0.4rem; border:1px solid #d1d5db; border-radius:6px;">
            </div>
        </div>
    </div>

    <div style="margin-top:0.75rem;">
        <strong>Preview</strong> (updates when you change the values above):
        <div id="previewList" style="margin-top:0.5rem; font-size:0.9rem; color:#374151;"></div>
    </div>

    <div style="display:flex; flex-wrap:wrap; gap:0.5rem; align-items:center; margin-top:1rem;">
        <label>Duration:</label>
        <input type="number" id="durationValue" min="1" value="24" style="width:80px; padding:0.4rem; border:1px solid #d1d5db; border-radius:6px;">
        <select id="durationUnit" style="padding:0.4rem; border:1px solid #d1d5db; border-radius:6px;">
            <option value="hours">Hours</option>
            <option value="days">Days</option>
        </select>
        <button type="button" id="btnApply" class="btn btn-primary">Apply deal and set duration</button>
    </div>
    <p id="applyStatus" style="font-size:0.9rem; margin-top:0.5rem;"></p>
</div>

<hr style="margin:1.5rem 0;">
<h2 style="font-size:1.1rem;">Active deals</h2>
<p style="font-size:0.9rem; color:#6b7280; margin-bottom:0.75rem;">Products currently in a deal, with countdown until prices are restored.</p>
<?php if($activeDeals->isEmpty()): ?>
    <p>No active deals.</p>
<?php else: ?>
    <div style="overflow-x:auto;">
        <table style="width:100%; border-collapse:collapse; font-size:0.9rem;">
            <thead>
                <tr style="background:#f3f4f6; text-align:left;">
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Image</th>
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Product</th>
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Deal applied</th>
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Compare discount</th>
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Time left</th>
                    <th style="padding:0.5rem; border:1px solid #e5e7eb;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php $__currentLoopData = $activeDeals; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $deal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php $__currentLoopData = $deal->dealProducts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $dp): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <tr style="border-bottom:1px solid #e5e7eb;">
                            <td style="padding:0.5rem; border:1px solid #e5e7eb; vertical-align:middle;">
                                <?php if($dp->image_url): ?>
                                    <img src="<?php echo e($dp->image_url); ?>" alt="" style="width:50px; height:50px; object-fit:cover; border-radius:4px;">
                                <?php else: ?>
                                    <span style="color:#9ca3af;">—</span>
                                <?php endif; ?>
                            </td>
                            <td style="padding:0.5rem; border:1px solid #e5e7eb;"><?php echo e($dp->title); ?></td>
                            <td style="padding:0.5rem; border:1px solid #e5e7eb;">
                                <?php if($deal->profit_type === 'percentage'): ?>
                                    <?php echo e(number_format($deal->profit_value, 0)); ?>% profit
                                <?php else: ?>
                                    $<?php echo e(number_format($deal->profit_value, 2)); ?> profit
                                <?php endif; ?>
                                <br><span style="font-size:0.85rem; color:#6b7280;">Sale $<?php echo e(number_format($dp->deal_price, 2)); ?></span>
                            </td>
                            <td style="padding:0.5rem; border:1px solid #e5e7eb;"><?php echo e(number_format($deal->compare_discount_percent ?? 0, 0)); ?>% off</td>
                            <td style="padding:0.5rem; border:1px solid #e5e7eb;">
                                <span class="deal-countdown" data-end="<?php echo e($deal->ends_at->toIso8601String()); ?>" style="font-weight:bold; color:#1d4ed8;">--</span>
                            </td>
                            <td style="padding:0.5rem; border:1px solid #e5e7eb; vertical-align:middle;">
                                <?php if($loop->first): ?>
                                    <a href="<?php echo e(route('deals.edit', $deal)); ?>" class="btn btn-secondary" style="padding:0.35rem 0.6rem; font-size:0.85rem;">Edit</a>
                                    <form action="<?php echo e(route('deals.destroy', $deal)); ?>" method="post" style="display:inline;" onsubmit="return confirm('Delete this deal and restore original prices in Shopify?');">
                                        <?php echo csrf_field(); ?>
                                        <?php echo method_field('DELETE'); ?>
                                        <button type="submit" class="btn btn-danger" style="padding:0.35rem 0.6rem; font-size:0.85rem;">Delete</button>
                                    </form>
                                <?php else: ?>
                                    —
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<hr style="margin:1.5rem 0;">
<h2 style="font-size:1.1rem;">Recent deals</h2>
<?php if($deals->isEmpty()): ?>
    <p>No deals yet.</p>
<?php else: ?>
    <ul style="list-style:none; padding:0;">
        <?php $__currentLoopData = $deals; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $deal): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <li style="border:1px solid #e5e7eb; border-radius:6px; padding:0.75rem; margin-bottom:0.5rem;">
                <strong>Deal #<?php echo e($deal->id); ?></strong> — <?php echo e($deal->duration_value); ?> <?php echo e($deal->duration_unit); ?>

                | Starts: <?php echo e($deal->starts_at?->format('Y-m-d H:i')); ?>

                | Ends: <?php echo e($deal->ends_at?->format('Y-m-d H:i')); ?>

                | <?php echo e($deal->dealProducts->count()); ?> product(s)
                <?php if($deal->restored): ?> <span style="color:green;">Restored</span> <?php endif; ?>
                <span style="margin-left:0.5rem;">
                    <a href="<?php echo e(route('deals.edit', $deal)); ?>" class="btn btn-secondary" style="padding:0.35rem 0.6rem; font-size:0.85rem;">Edit</a>
                    <form action="<?php echo e(route('deals.destroy', $deal)); ?>" method="post" style="display:inline;" onsubmit="return confirm('Delete this deal? Prices will be restored in Shopify if still active.');">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('DELETE'); ?>
                        <button type="submit" class="btn btn-danger" style="padding:0.35rem 0.6rem; font-size:0.85rem;">Delete</button>
                    </form>
                </span>
            </li>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </ul>
    <?php echo e($deals->links('vendor.pagination.simple-default')); ?>

<?php endif; ?>

<?php $__env->startPush('scripts'); ?>
<script>
(function() {
    const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    const selected = [];

    function formatCountdown(ms) {
        if (ms <= 0) return 'Ended';
        const s = Math.floor(ms / 1000) % 60;
        const m = Math.floor(ms / 60000) % 60;
        const h = Math.floor(ms / 3600000) % 24;
        const d = Math.floor(ms / 86400000);
        const parts = [];
        if (d > 0) parts.push(d + 'd');
        parts.push(String(h).padStart(2, '0') + 'h');
        parts.push(String(m).padStart(2, '0') + 'm');
        parts.push(String(s).padStart(2, '0') + 's');
        return parts.join(' ');
    }
    function updateCountdowns() {
        document.querySelectorAll('.deal-countdown').forEach(function(el) {
            const end = new Date(el.getAttribute('data-end'));
            const now = new Date();
            const ms = end - now;
            el.textContent = formatCountdown(ms);
            if (ms <= 0) el.style.color = '#16a34a';
        });
    }
    updateCountdowns();
    setInterval(updateCountdowns, 1000);

    function calcDeal(cost, profitType, profitValue, comparePercent) {
        const c = parseFloat(cost);
        if (isNaN(c) || c < 0) return { sale: null, compare: null };
        let sale = profitType === 'percentage' ? c + c * (profitValue / 100) : c + profitValue;
        sale = Math.round(sale * 100) / 100;
        const denom = 1 - (comparePercent / 100);
        const compare = denom > 0 ? Math.round((sale / denom) * 100) / 100 : null;
        return { sale, compare };
    }

    function updatePreview() {
        const profitType = document.getElementById('profitType').value;
        const profitValue = parseFloat(document.getElementById('profitValue').value) || 0;
        const comparePercent = parseFloat(document.getElementById('compareDiscountPercent').value) || 0;
        const el = document.getElementById('previewList');
        if (selected.length === 0) { el.innerHTML = ''; return; }
        let html = '';
        selected.forEach(item => {
            const cost = item.cost != null ? parseFloat(item.cost) : null;
            if (cost == null || isNaN(cost)) {
                html += '<div style="padding:0.25rem 0;">' + (item.title || 'Product') + ' — <span style="color:#b91c1c;">No cost</span></div>';
                return;
            }
            const r = calcDeal(cost, profitType, profitValue, comparePercent);
            html += '<div style="padding:0.25rem 0;">' + (item.title || 'Product') + ': Cost $' + cost.toFixed(2) + ' → Sale $' + (r.sale != null ? r.sale.toFixed(2) : '—') + (r.compare != null ? ' | Compare at $' + r.compare.toFixed(2) : '') + '</div>';
        });
        el.innerHTML = html;
    }

    function showSelected() {
        const section = document.getElementById('selectedSection');
        const list = document.getElementById('selectedList');
        if (selected.length === 0) {
            section.style.display = 'none';
            return;
        }
        section.style.display = 'block';
        const profitType = document.getElementById('profitType').value;
        const profitValue = parseFloat(document.getElementById('profitValue').value) || 0;
        const comparePercent = parseFloat(document.getElementById('compareDiscountPercent').value) || 0;
        list.innerHTML = selected.map((item, i) => {
            const costStr = item.cost != null && item.cost !== '' ? '$' + parseFloat(item.cost).toFixed(2) : 'No cost';
            const r = item.cost != null && item.cost !== '' ? calcDeal(item.cost, profitType, profitValue, comparePercent) : { sale: null, compare: null };
            const preview = r.sale != null ? ' → Sale $' + r.sale.toFixed(2) + (r.compare != null ? ', Compare $' + r.compare.toFixed(2) : '') : '';
            return '<li style="padding:0.5rem 0; border-bottom:1px solid #eee;">' +
                '<strong>' + (item.title || 'Product') + '</strong><br>' +
                '<span style="font-size:0.9rem;">Cost: ' + costStr + ' | Current price: $' + item.price + preview + '</span>' +
                ' <button type="button" data-idx="' + i + '" class="btn-remove btn btn-secondary" style="padding:0.2rem 0.5rem; font-size:0.8rem; margin-top:0.25rem;">Remove</button></li>';
        }).join('');
        list.querySelectorAll('.btn-remove').forEach(btn => {
            btn.addEventListener('click', () => {
                selected.splice(parseInt(btn.dataset.idx, 10), 1);
                showSelected();
                updatePreview();
            });
        });
        updatePreview();
    }

    document.getElementById('profitType').addEventListener('change', function() { updatePreview(); showSelected(); });
    document.getElementById('profitValue').addEventListener('input', function() { updatePreview(); showSelected(); });
    document.getElementById('compareDiscountPercent').addEventListener('input', function() { updatePreview(); showSelected(); });

    document.getElementById('btnSearch').addEventListener('click', function() {
        const q = document.getElementById('search').value.trim();
        const block = document.getElementById('searchResults');
        const status = document.getElementById('searchStatus');
        const ul = document.getElementById('resultList');
        block.style.display = 'block';
        status.textContent = 'Searching...';
        ul.innerHTML = '';

        fetch('<?php echo e(route("deals.search")); ?>?q=' + encodeURIComponent(q), {
            headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
        })
            .then(r => r.json())
            .then(data => {
                if (data.error) { status.textContent = data.error; return; }
                const products = data.products || [];
                status.textContent = products.length + ' variant(s) found.';
                products.forEach(p => {
                    const costDisplay = p.cost != null && p.cost !== '' ? ' | Cost: $' + parseFloat(p.cost).toFixed(2) : ' | Cost: —';
                    const li = document.createElement('li');
                    li.style.padding = '0.35rem 0';
                    li.style.borderBottom = '1px solid #eee';
                    li.innerHTML = p.title + ' — $' + p.price + costDisplay +
                        ' <button type="button" class="btn-add btn btn-primary" style="padding:0.2rem 0.5rem; font-size:0.8rem;">Add</button>';
                    li.querySelector('.btn-add').addEventListener('click', () => {
                        selected.push({
                            variant_id: p.variant_id,
                            product_id: p.product_id || null,
                            title: p.title,
                            price: p.price,
                            compare_at_price: p.compare_at_price || null,
                            cost: p.cost || null,
                            image_url: p.image_url || null
                        });
                        showSelected();
                    });
                    ul.appendChild(li);
                });
            })
            .catch(e => { status.textContent = 'Error: ' + e.message; });
    });

    document.getElementById('btnApply').addEventListener('click', function() {
        if (selected.length === 0) {
            document.getElementById('applyStatus').textContent = 'Select at least one product.';
            return;
        }
        const profitType = document.getElementById('profitType').value;
        const profitValue = parseFloat(document.getElementById('profitValue').value);
        const compareDiscountPercent = parseFloat(document.getElementById('compareDiscountPercent').value);
        const durationValue = parseInt(document.getElementById('durationValue').value, 10) || 1;
        const durationUnit = document.getElementById('durationUnit').value;
        const status = document.getElementById('applyStatus');
        const hasNoCost = selected.some(i => i.cost == null || i.cost === '');
        if (hasNoCost) {
            status.textContent = 'Some products have no cost. Remove them or add cost in Shopify.';
            return;
        }
        status.textContent = 'Applying...';

        fetch('<?php echo e(route("deals.apply")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrf,
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                items: selected,
                profit_type: profitType,
                profit_value: profitValue,
                compare_discount_percent: compareDiscountPercent,
                duration_value: durationValue,
                duration_unit: durationUnit
            })
        })
            .then(r => r.json())
            .then(data => {
                status.textContent = data.message || (data.success ? 'Done.' : 'Error');
                if (data.success) {
                    selected.length = 0;
                    showSelected();
                    window.location.reload();
                }
            })
            .catch(e => { status.textContent = 'Error: ' + e.message; });
    });
})();
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/avijewels/public_html/tools.avijewels.info/resources/views/deals/index.blade.php ENDPATH**/ ?>