{include file="sections/header.tpl"}

<div class="p-4 md:p-6 space-y-4">

    
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div class="flex items-center gap-3">
            <div class="w-10 h-10 rounded-xl bg-green-600 flex items-center justify-center shadow">
                <svg class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M12 2C6.48 2 2 6.48 2 12c0 1.85.5 3.58 1.38 5.06L2 22l5.09-1.35A9.956 9.956 0 0012 22c5.52 0 10-4.48 10-10S17.52 2 12 2zm0 18c-1.66 0-3.2-.46-4.53-1.25l-.32-.2-3.02.8.82-2.96-.21-.33A7.96 7.96 0 014 12c0-4.41 3.59-8 8-8s8 3.59 8 8-3.59 8-8 8z"/>
                </svg>
            </div>
            <div>
                <h1 class="text-xl font-bold text-gray-800 leading-tight">WhatsApp Message Logs</h1>
                <p class="text-sm text-gray-500">{$total_logs} total record{if $total_logs != 1}s{/if}</p>
            </div>
        </div>
        <a href="{$_url}plugin/goWhatsappGateway"
           class="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 shadow-sm transition">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
            </svg>
            Back to Gateway
        </a>
    </div>

    {* ── Stats cards ── *}
    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
            <div class="w-9 h-9 rounded-lg bg-blue-100 flex items-center justify-center shrink-0">
                <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M8 10h.01M12 10h.01M16 10h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/>
                </svg>
            </div>
            <div>
                <p class="text-2xl font-bold text-gray-800">{$stats_total}</p>
                <p class="text-xs text-gray-500">Total Sent</p>
            </div>
        </div>
        <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
            <div class="w-9 h-9 rounded-lg bg-green-100 flex items-center justify-center shrink-0">
                <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
                </svg>
            </div>
            <div>
                <p class="text-2xl font-bold text-green-700">{$stats_delivered}</p>
                <p class="text-xs text-gray-500">Delivered</p>
            </div>
        </div>
        <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
            <div class="w-9 h-9 rounded-lg bg-red-100 flex items-center justify-center shrink-0">
                <svg class="w-5 h-5 text-red-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </div>
            <div>
                <p class="text-2xl font-bold text-red-600">{$stats_failed}</p>
                <p class="text-xs text-gray-500">Failed</p>
            </div>
        </div>
        <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4 flex items-center gap-3">
            <div class="w-9 h-9 rounded-lg bg-purple-100 flex items-center justify-center shrink-0">
                <svg class="w-5 h-5 text-purple-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/>
                </svg>
            </div>
            <div>
                <p class="text-2xl font-bold text-purple-700">{$stats_rate}%</p>
                <p class="text-xs text-gray-500">Success Rate</p>
            </div>
        </div>
    </div>

    {* ── Search / filter bar ── *}
    <form method="get" id="filterForm" class="bg-white rounded-xl border border-gray-200 shadow-sm p-4">
        <div class="flex flex-wrap gap-3 items-end">
            <div class="flex-1 min-w-[160px]">
                <label class="block text-xs font-medium text-gray-500 mb-1">Search</label>
                <input type="text" name="search" value="{$search|escape}" placeholder="Phone or message..."
                    class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-500 mb-1">Status</label>
                <select name="status" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
                    <option value="">All</option>
                    <option value="delivered" {if $filter_status eq 'delivered'}selected{/if}>Delivered</option>
                    <option value="failed"    {if $filter_status eq 'failed'}selected{/if}>Failed</option>
                    <option value="sent"      {if $filter_status eq 'sent'}selected{/if}>Sent</option>
                </select>
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-500 mb-1">From</label>
                <input type="date" name="date_from" value="{$date_from|escape}"
                    class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
            </div>
            <div>
                <label class="block text-xs font-medium text-gray-500 mb-1">To</label>
                <input type="date" name="date_to" value="{$date_to|escape}"
                    class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
            </div>
            <input type="hidden" name="per_page" value="{$per_page}">
            <input type="hidden" name="page" value="1">
            <button type="submit"
                class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-green-600 text-white text-sm font-medium hover:bg-green-700 transition">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0z"/>
                </svg>
                Filter
            </button>
            {if $search || $filter_status || $date_from || $date_to}
            <a href="{$_url}plugin/goWhatsappGateway_logs"
                class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg border border-gray-300 bg-white text-sm text-gray-600 hover:bg-gray-50 transition">
                Clear
            </a>
            {/if}
            <a href="{$_url}plugin/goWhatsappGateway_logs&export=csv&search={$search|escape:'url'}&status={$filter_status|escape:'url'}&date_from={$date_from|escape:'url'}&date_to={$date_to|escape:'url'}"
                class="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg border border-gray-300 bg-white text-sm text-gray-700 hover:bg-gray-50 transition ml-auto">
                <svg class="w-4 h-4 text-green-600" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                </svg>
                Export CSV
            </a>
        </div>
    </form>

    {* ── Status filter tabs ── *}
    <div class="flex flex-wrap gap-2">
        {foreach [''=>'All','delivered'=>'Delivered','failed'=>'Failed','sent'=>'Sent'] as $tab_val => $tab_label}
            <a href="{$_url}plugin/goWhatsappGateway_logs&per_page={$per_page}&search={$search|escape:'url'}&date_from={$date_from|escape:'url'}&date_to={$date_to|escape:'url'}&status={$tab_val|escape:'url'}"
                class="px-4 py-1.5 rounded-full border text-sm font-medium transition {if $filter_status eq $tab_val}bg-green-600 border-green-600 text-white{else}bg-white border-gray-300 text-gray-600 hover:bg-gray-50{/if}">
                {$tab_label}
            </a>
        {/foreach}
    </div>

    <div class="bg-white rounded-xl border border-gray-200 shadow-sm p-4">
        <form method="post" id="logsForm">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">

                
                <div class="flex flex-wrap items-center gap-4">
                    <label class="flex items-center gap-2 text-sm text-gray-600">
                        <span>Show</span>
                        <select id="perPageSelect" onchange="changePerPage()"
                            class="border border-gray-300 rounded-lg px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
                            {foreach [10,50,100,150,200,500] as $n}
                                <option value="{$n}" {if $per_page == $n}selected{/if}>{$n}</option>
                            {/foreach}
                        </select>
                        <span>per page</span>
                    </label>

                    <label class="flex items-center gap-2 text-sm text-gray-600 cursor-pointer select-none">
                        <input type="checkbox" id="selectAll"
                            class="w-4 h-4 accent-green-600 rounded cursor-pointer">
                        <span>Select all</span>
                    </label>

                    <span class="text-xs text-gray-400">
                        {if $logs|@count > 0}
                            {assign var="from" value=($page-1)*$per_page+1}
                            {assign var="to"   value=($page-1)*$per_page+$logs|@count}
                            {$from}–{$to} of {$total_logs}
                        {else}
                            No records
                        {/if}
                    </span>
                </div>

                
                <div class="flex items-center gap-2">
                    <button type="button" id="deleteSelectedBtn" disabled onclick="deleteSelected()"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium bg-amber-100 text-amber-800 hover:bg-amber-200 disabled:opacity-40 disabled:cursor-not-allowed transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M8 7V5a1 1 0 011-1h6a1 1 0 011 1v2"/>
                        </svg>
                        Delete Selected
                    </button>
                    <button type="button" onclick="deleteAll()"
                        class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium bg-red-100 text-red-700 hover:bg-red-200 transition">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M8 7V5a1 1 0 011-1h6a1 1 0 011 1v2"/>
                        </svg>
                        Delete All
                    </button>
                </div>
            </div>

            
            <div class="mt-4 overflow-x-auto rounded-xl border border-gray-200">
                <table class="min-w-full divide-y divide-gray-200 text-sm">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="w-10 px-3 py-3 text-center">
                                <input type="checkbox" id="selectAllHeader"
                                    class="w-4 h-4 accent-green-600 rounded cursor-pointer">
                            </th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">ID</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Phone</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Message</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Response</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider whitespace-nowrap">Date / Time</th>
                            <th class="px-3 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-100">
                        {if $logs|@count > 0}
                            {foreach $logs as $log}
                                <tr class="hover:bg-gray-50 transition-colors">
                                    <td class="px-3 py-3 text-center">
                                        <input type="checkbox" name="selected_logs[]" value="{$log['id']}"
                                            class="log-checkbox w-4 h-4 accent-green-600 rounded cursor-pointer">
                                    </td>
                                    <td class="px-3 py-3 text-gray-500 font-mono text-xs">{$log['id']}</td>
                                    <td class="px-3 py-3 font-medium text-gray-800 whitespace-nowrap">{$log['phone_number']}</td>
                                    <td class="px-3 py-3 text-gray-700 max-w-xs">
                                        <div class="truncate" title="{$log['message']|escape}">{$log['message']}</div>
                                    </td>
                                    <td class="px-3 py-3 whitespace-nowrap">
                                        {if $log['status'] eq 'delivered'}
                                            <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-800">
                                                <span class="w-1.5 h-1.5 rounded-full bg-green-500"></span> delivered
                                            </span>
                                        {elseif $log['status'] eq 'failed'}
                                            <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-700">
                                                <span class="w-1.5 h-1.5 rounded-full bg-red-500"></span> failed
                                            </span>
                                        {else}
                                            <span class="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-800">
                                                <span class="w-1.5 h-1.5 rounded-full bg-amber-500"></span> {$log['status']}
                                            </span>
                                        {/if}
                                    </td>
                                    <td class="px-3 py-3 text-gray-500 text-xs max-w-xs">
                                        <div class="truncate font-mono" title="{$log['response']|escape}">{$log['response']}</div>
                                    </td>
                                    <td class="px-3 py-3 text-gray-500 text-xs whitespace-nowrap">{$log['created_at']}</td>
                                    <td class="px-3 py-3">
                                        <form method="post" style="display:inline" onsubmit="return window.confirm('Resend this message to {$log.phone_number}?')">
                                            <input type="hidden" name="resend_id" value="{$log['id']}">
                                            <button type="submit" class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium bg-blue-50 text-blue-700 hover:bg-blue-100 border border-blue-200 transition whitespace-nowrap">
                                                <svg class="w-3 h-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
                                                Resend
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            {/foreach}
                        {else}
                            <tr>
                                <td colspan="8" class="px-4 py-16 text-center text-gray-400">
                                    <div class="flex flex-col items-center gap-2">
                                        <svg class="w-10 h-10 text-gray-300" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" d="M7.5 8.25h9m-9 3H12m-9.75 1.51c0 1.6 1.123 2.994 2.707 3.227 1.129.166 2.27.293 3.423.379.35.026.67.21.865.501L12 21l2.755-4.133a1.14 1.14 0 01.865-.501 48.172 48.172 0 003.423-.379c1.584-.233 2.707-1.626 2.707-3.228V6.741c0-1.602-1.123-2.995-2.707-3.228A48.394 48.394 0 0012 3c-2.392 0-4.744.175-7.043.513C3.373 3.746 2.25 5.14 2.25 6.741v6.018z"/>
                                        </svg>
                                        <p class="font-medium">No logs found</p>
                                        <p class="text-xs">Messages sent via WhatsApp will appear here</p>
                                    </div>
                                </td>
                            </tr>
                        {/if}
                    </tbody>
                </table>
            </div>
        </form>

        
        {if $total_pages > 1}
        <div class="mt-4 flex flex-wrap items-center justify-between gap-3">
            <p class="text-xs text-gray-500">Page {$page} of {$total_pages}</p>
            <div class="flex items-center gap-1">
                {if $page > 1}
                    <a href="{$_url}plugin/goWhatsappGateway_logs&page={$page-1}&per_page={$per_page}"
                        class="px-3 py-1.5 rounded-lg border border-gray-300 bg-white text-sm text-gray-600 hover:bg-gray-50 shadow-sm transition">
                        &#8592; Prev
                    </a>
                {/if}

                {for $p=1 to $total_pages}
                    {if $p >= $page-3 && $p <= $page+3}
                    <a href="{$_url}plugin/goWhatsappGateway_logs&page={$p}&per_page={$per_page}"
                        class="px-3 py-1.5 rounded-lg border text-sm shadow-sm transition {if $p eq $page}border-green-600 bg-green-600 text-white font-semibold{else}border-gray-300 bg-white text-gray-600 hover:bg-gray-50{/if}">
                        {$p}
                    </a>
                    {/if}
                {/for}

                {if $page < $total_pages}
                    <a href="{$_url}plugin/goWhatsappGateway_logs&page={$page+1}&per_page={$per_page}"
                        class="px-3 py-1.5 rounded-lg border border-gray-300 bg-white text-sm text-gray-600 hover:bg-gray-50 shadow-sm transition">
                        Next &#8594;
                    </a>
                {/if}
            </div>
        </div>
        {/if}
    </div>
</div>

<script>
(function () {
    var selectAllMain   = document.getElementById('selectAll');
    var selectAllHeader = document.getElementById('selectAllHeader');
    var deleteBtn       = document.getElementById('deleteSelectedBtn');

    function getCheckboxes() {
        return document.querySelectorAll('.log-checkbox');
    }
    function getChecked() {
        return document.querySelectorAll('.log-checkbox:checked');
    }

    function sync() {
        var all     = getCheckboxes();
        var checked = getChecked();
        var allChecked = all.length > 0 && checked.length === all.length;
        selectAllMain.checked   = allChecked;
        selectAllHeader.checked = allChecked;
        deleteBtn.disabled = checked.length === 0;
    }

    function checkAll(state) {
        getCheckboxes().forEach(function (cb) { cb.checked = state; });
        sync();
    }

    selectAllMain.addEventListener('change',   function () { checkAll(this.checked); });
    selectAllHeader.addEventListener('change', function () { checkAll(this.checked); });
    document.addEventListener('change', function (e) {
        if (e.target && e.target.classList.contains('log-checkbox')) sync();
    });
    sync();
}());

function deleteSelected() {
    var checked = document.querySelectorAll('.log-checkbox:checked');
    if (checked.length === 0) { window.alert('Please select at least one log to delete.'); return; }
    if (!window.confirm('Delete ' + checked.length + ' selected log(s)? This cannot be undone.')) return;
    var form = document.getElementById('logsForm');
    var inp  = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'delete_selected'; inp.value = '1';
    form.appendChild(inp);
    form.submit();
}

function deleteAll() {
    if (!window.confirm('Delete ALL WhatsApp logs? This cannot be undone.')) return;
    if (!window.confirm('Final confirmation — permanently delete every log?')) return;
    var form = document.getElementById('logsForm');
    var inp  = document.createElement('input');
    inp.type = 'hidden'; inp.name = 'delete_all'; inp.value = '1';
    form.appendChild(inp);
    form.submit();
}

function changePerPage() {
    var val = document.getElementById('perPageSelect').value;
    var url = new URL(window.location.href);
    url.searchParams.set('per_page', val);
    url.searchParams.set('page', '1');
    window.location.href = url.toString();
}
</script>

{include file="sections/footer.tpl"}
