{% extends '@MauticCore/Default/content.html.twig' %}

{% block headerTitle 'Deals' %}

{% block content %}
    {{ include('@DealFlow/_styles.html.twig') }}

    {% if pipelines|length > 1 %}
        <form class="form-inline mb-lg" method="get">
            <input type="hidden" name="page" value="{{ page }}">
            <div class="form-group">
                <label class="mr-sm" for="dealflow_list_pipeline">Pipeline</label>
                <select class="form-control" id="dealflow_list_pipeline" name="pipelineId" onchange="this.form.submit()">
                    {% for pipeline in pipelines %}
                        <option value="{{ pipeline.getId() }}" {% if selectedPipeline and pipeline.getId() == selectedPipeline.getId() %}selected{% endif %}>
                            {{ pipeline.getName() }}
                        </option>
                    {% endfor %}
                </select>
            </div>
        </form>
    {% endif %}

    <form class="dealflow-search-form mb-lg" method="get" action="{{ path('mautic_dealflow_index', {page: 1, pipelineId: selectedPipeline.getId()}) }}">
        <input type="hidden" name="pipelineId" value="{{ selectedPipeline.getId() }}">
        {% if activeStage %}
            <input type="hidden" name="stageId" value="{{ activeStage.getId() }}">
        {% endif %}
        <div class="input-group" style="max-width: 400px;">
            <input
                type="text"
                class="form-control dealflow-search-input"
                name="search"
                value="{{ searchValue }}"
                placeholder="{{ 'dealflow.search.placeholder'|trans }}"
                autocomplete="off"
            >
            <span class="input-group-btn">
                {% if searchValue %}
                    <a
                        class="btn btn-default dealflow-search-clear"
                        href="{{ path('mautic_dealflow_index', {page: 1, pipelineId: selectedPipeline.getId(), stageId: activeStage ? activeStage.getId() : null}) }}"
                        title="{{ 'dealflow.search.clear'|trans }}"
                    >&times;</a>
                {% endif %}
                <button type="submit" class="btn btn-default">
                    <i class="ri-search-line"></i>
                </button>
            </span>
        </div>
    </form>

    {% if activeStage %}
        <div class="alert alert-info">
            Showing deals in <strong>{{ activeStage.getName() }}</strong>.
            <a href="{{ clearFiltersUrl }}">Clear filter</a>
        </div>
    {% endif %}

    <div class="dealflow-batch-toolbar mb-lg" style="display: flex; align-items: center; gap: 12px; flex-wrap: wrap;">
        {% if securityIsGranted('dealflow:deals:create') %}
            <a
                class="btn btn-primary"
                href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'returnUrl': app.request.requestUri}) }}"
                data-toggle="ajaxmodal"
                data-target="#MauticSharedModal"
                data-header="New Deal"
                data-href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'modal': 1, 'contentOnly': 1, 'returnUrl': app.request.requestUri}) }}"
            >
                <i class="ri-add-line"></i>
                New Deal
            </a>
        {% endif %}

        <span class="dealflow-batch-selected-count" id="dealflow-selected-count" style="display: none; font-weight: 600; color: #555;">
            <span id="dealflow-selected-number">0</span> selected
        </span>

        <div class="btn-group dealflow-batch-actions" id="dealflow-batch-actions" style="display: none;">
            <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                Batch Actions <span class="caret"></span>
            </button>
            <ul class="dropdown-menu" role="menu">
                {% if pipelineStages|length > 0 %}
                    <li class="dropdown-header">Change Stage</li>
                    {% for stage in pipelineStages %}
                        <li>
                            <a href="#" class="dealflow-batch-stage-option" data-stage-id="{{ stage.getId() }}">
                                {{ stage.getName() }}
                            </a>
                        </li>
                    {% endfor %}
                    <li class="divider"></li>
                {% endif %}
                {% if securityIsGranted('dealflow:deals:deleteown') or securityIsGranted('dealflow:deals:deleteother') %}
                    <li>
                        <a href="#" id="dealflow-batch-delete" style="color: #c9302c;">
                            <i class="ri-delete-bin-line"></i> Archive Selected
                        </a>
                    </li>
                {% endif %}
            </ul>
        </div>
    </div>

    {% macro sortHeader(label, field, currentSort, currentDir, pipelineId, stageId, searchValue) %}
        {% set isActive = currentSort == field %}
        {% set nextDir = isActive and currentDir == 'asc' ? 'desc' : 'asc' %}
        <th>
            <a href="{{ path('mautic_dealflow_index', {page: 1, pipelineId: pipelineId, stageId: stageId, orderBy: field, orderDir: nextDir, search: searchValue ?: null}) }}" data-toggle="ajax" style="text-decoration:none;color:inherit;">
                {{ label }}
                {% if isActive %}
                    <i class="ri-arrow-{{ currentDir == 'asc' ? 'up' : 'down' }}-s-line"></i>
                {% endif %}
            </a>
        </th>
    {% endmacro %}

    <form id="dealflow-batch-form" method="post" action="{{ path('mautic_dealflow_batch') }}">
        <input type="hidden" name="_token" value="{{ batchCsrfToken }}">
        <input type="hidden" name="batch_action" id="dealflow-batch-action" value="">
        <input type="hidden" name="batch_stage_id" id="dealflow-batch-stage-id" value="">
        <input type="hidden" name="return_url" value="{{ app.request.requestUri }}">

        <table class="table table-hover">
            <thead>
            <tr>
                <th style="width: 40px;">
                    <input type="checkbox" id="dealflow-select-all" class="dealflow-batch-checkbox" title="Select all">
                </th>
                {{ _self.sortHeader('Title', 'title', currentSort|default('updatedAt'), currentDir|default('desc'), selectedPipeline.getId(), activeStage ? activeStage.getId() : null, searchValue) }}
                <th>Company</th>
                {{ _self.sortHeader('Stage', 'stage', currentSort|default('updatedAt'), currentDir|default('desc'), selectedPipeline.getId(), activeStage ? activeStage.getId() : null, searchValue) }}
                <th>Owner</th>
                {{ _self.sortHeader('Amount', 'amount', currentSort|default('updatedAt'), currentDir|default('desc'), selectedPipeline.getId(), activeStage ? activeStage.getId() : null, searchValue) }}
                {% for field in listCustomFields %}
                    <th>{{ field.getLabel() }}</th>
                {% endfor %}
                {{ _self.sortHeader('Expected Close', 'expectedCloseDate', currentSort|default('updatedAt'), currentDir|default('desc'), selectedPipeline.getId(), activeStage ? activeStage.getId() : null, searchValue) }}
                {{ _self.sortHeader('Updated', 'updatedAt', currentSort|default('updatedAt'), currentDir|default('desc'), selectedPipeline.getId(), activeStage ? activeStage.getId() : null, searchValue) }}
            </tr>
            </thead>
            <tbody>
            {% for item in items %}
                {% set context = dealContexts[item.getId()] ?? {'companyName': null, 'ownerName': null} %}
                {% set customValues = customFieldListValues[item.getId()] ?? {} %}
                <tr>
                    <td>
                        <input type="checkbox" name="deal_ids[]" value="{{ item.getId() }}" class="dealflow-deal-checkbox">
                    </td>
                    <td>
                        <a href="{{ path('mautic_dealflow_view', {'objectId': item.getId()}) }}">{{ item.getTitle() }}</a>
                    </td>
                    <td>{{ context.companyName ?: 'Unassigned' }}</td>
                    <td>{{ item.getStage() ? item.getStage().getName() : 'No stage' }}</td>
                    <td>{{ context.ownerName ?: 'Unassigned' }}</td>
                    <td>{{ include('@DealFlow/Deal/_amount.html.twig', {amount: item.getAmount(), currency: item.getCurrency()}, false) }}</td>
                    {% for field in listCustomFields %}
                        {% set row = customValues[field.getAlias()] ?? null %}
                        <td>{{ row ? row.displayValue : 'Not set' }}</td>
                    {% endfor %}
                    <td>{{ item.getExpectedCloseDate() ? item.getExpectedCloseDate().format('Y-m-d') : 'N/A' }}</td>
                    <td>{{ item.getDateModified() ? item.getDateModified().format('Y-m-d H:i') : 'N/A' }}</td>
                </tr>
            {% else %}
                <tr>
                    <td colspan="{{ 8 + listCustomFields|length }}" class="text-muted">
                        {% if searchValue %}
                            No deals matching "{{ searchValue }}".
                            <a href="{{ path('mautic_dealflow_index', {page: 1, pipelineId: selectedPipeline.getId(), stageId: activeStage ? activeStage.getId() : null}) }}">Clear search</a>
                        {% else %}
                            No deals found.
                        {% endif %}
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </form>

    {% if totalPages > 1 %}
        <nav class="text-center">
            <ul class="pagination">
                {% if page > 1 %}
                    <li><a href="{{ path('mautic_dealflow_index', {page: page - 1, pipelineId: selectedPipeline.getId(), stageId: activeStage ? activeStage.getId() : null, search: searchValue ?: null}) }}" data-toggle="ajax">&laquo;</a></li>
                {% else %}
                    <li class="disabled"><span>&laquo;</span></li>
                {% endif %}
                {% for p in 1..totalPages %}
                    <li class="{{ p == page ? 'active' : '' }}"><a href="{{ path('mautic_dealflow_index', {page: p, pipelineId: selectedPipeline.getId(), stageId: activeStage ? activeStage.getId() : null, search: searchValue ?: null}) }}" data-toggle="ajax">{{ p }}</a></li>
                {% endfor %}
                {% if page < totalPages %}
                    <li><a href="{{ path('mautic_dealflow_index', {page: page + 1, pipelineId: selectedPipeline.getId(), stageId: activeStage ? activeStage.getId() : null, search: searchValue ?: null}) }}" data-toggle="ajax">&raquo;</a></li>
                {% else %}
                    <li class="disabled"><span>&raquo;</span></li>
                {% endif %}
            </ul>
        </nav>
    {% endif %}

    {% if undoCount is defined and undoCount > 0 %}
        <div id="dealflow-undo-toast" class="dealflow-undo-toast">
            <span>{{ undoCount }} deal(s) archived.</span>
            <form method="post" action="{{ path('mautic_dealflow_undo') }}" style="display: inline;">
                <input type="hidden" name="_token" value="{{ undoCsrfToken }}">
                <input type="hidden" name="return_url" value="{{ app.request.requestUri }}">
                <button type="submit" class="dealflow-undo-btn">Undo</button>
            </form>
            <button type="button" class="dealflow-undo-dismiss" onclick="document.getElementById('dealflow-undo-toast').style.display='none'">&times;</button>
        </div>
    {% endif %}

    <style>
        .dealflow-batch-checkbox {
            cursor: pointer;
            width: 16px;
            height: 16px;
        }
        .dealflow-deal-checkbox {
            cursor: pointer;
            width: 16px;
            height: 16px;
        }
        .dealflow-undo-toast {
            position: fixed;
            bottom: 24px;
            left: 50%;
            transform: translateX(-50%);
            background: #333;
            color: #fff;
            padding: 12px 20px;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            display: flex;
            align-items: center;
            gap: 12px;
            z-index: 10000;
            font-size: 14px;
            animation: dealflow-toast-in 0.3s ease;
        }
        .dealflow-undo-btn {
            background: none;
            border: 1px solid #fff;
            color: #fff;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
        }
        .dealflow-undo-btn:hover {
            background: rgba(255,255,255,0.15);
        }
        .dealflow-undo-dismiss {
            background: none;
            border: none;
            color: #aaa;
            font-size: 18px;
            cursor: pointer;
            padding: 0 4px;
            line-height: 1;
        }
        .dealflow-undo-dismiss:hover {
            color: #fff;
        }
        @keyframes dealflow-toast-in {
            from { opacity: 0; transform: translateX(-50%) translateY(20px); }
            to { opacity: 1; transform: translateX(-50%) translateY(0); }
        }
    </style>

    <script>
        (function() {
            var selectAll = document.getElementById('dealflow-select-all');
            var batchForm = document.getElementById('dealflow-batch-form');
            var batchActions = document.getElementById('dealflow-batch-actions');
            var selectedCount = document.getElementById('dealflow-selected-count');
            var selectedNumber = document.getElementById('dealflow-selected-number');
            var batchActionInput = document.getElementById('dealflow-batch-action');
            var batchStageIdInput = document.getElementById('dealflow-batch-stage-id');

            if (!selectAll || !batchForm) return;

            function getCheckboxes() {
                return batchForm.querySelectorAll('.dealflow-deal-checkbox');
            }

            function getSelectedCount() {
                var count = 0;
                getCheckboxes().forEach(function(cb) { if (cb.checked) count++; });
                return count;
            }

            function updateUI() {
                var count = getSelectedCount();
                selectedNumber.textContent = count;
                selectedCount.style.display = count > 0 ? 'inline' : 'none';
                batchActions.style.display = count > 0 ? 'inline-block' : 'none';

                var total = getCheckboxes().length;
                selectAll.checked = total > 0 && count === total;
                selectAll.indeterminate = count > 0 && count < total;
            }

            selectAll.addEventListener('change', function() {
                var checked = this.checked;
                getCheckboxes().forEach(function(cb) { cb.checked = checked; });
                updateUI();
            });

            batchForm.addEventListener('change', function(e) {
                if (e.target.classList.contains('dealflow-deal-checkbox')) {
                    updateUI();
                }
            });

            // Stage change options
            var stageOptions = document.querySelectorAll('.dealflow-batch-stage-option');
            stageOptions.forEach(function(el) {
                el.addEventListener('click', function(e) {
                    e.preventDefault();
                    var stageId = this.getAttribute('data-stage-id');
                    batchActionInput.value = 'changeStage';
                    batchStageIdInput.value = stageId;
                    batchForm.submit();
                });
            });

            // Delete action
            var deleteBtn = document.getElementById('dealflow-batch-delete');
            if (deleteBtn) {
                deleteBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    var count = getSelectedCount();
                    if (count === 0) return;
                    if (!confirm('Archive ' + count + ' deal(s)? You can undo this action.')) return;
                    batchActionInput.value = 'delete';
                    batchStageIdInput.value = '';
                    batchForm.submit();
                });
            }

            // Auto-dismiss undo toast after 10 seconds
            var undoToast = document.getElementById('dealflow-undo-toast');
            if (undoToast) {
                setTimeout(function() { undoToast.style.display = 'none'; }, 10000);
            }
        })();
    </script>
{% endblock %}
