<div class="d-flex justify-content-between align-items-center mb-4">
    <h4 class="mb-0"><i class="fas fa-wrench me-2"></i><?= lang('reports.custom_builder') ?></h4>
</div>

<div class="row g-3">
    <div class="col-md-4">
        <div class="card">
            <div class="card-header"><h6 class="mb-0">1. Select Data Source</h6></div>
            <div class="card-body">
                <select id="custom-source" class="form-select"><option value="">-- Select Source --</option></select>
            </div>
        </div>
        <div class="card mt-3">
            <div class="card-header"><h6 class="mb-0">2. Select Columns</h6></div>
            <div class="card-body" id="columns-panel">
                <p class="text-muted small">Select a source first</p>
            </div>
        </div>
        <div class="card mt-3">
            <div class="card-header"><h6 class="mb-0">3. Filters (optional)</h6></div>
            <div class="card-body" id="filters-panel">
                <div id="filter-rows"></div>
                <button class="btn btn-sm btn-outline-primary mt-2" id="add-filter"><i class="fas fa-plus me-1"></i>Add Filter</button>
            </div>
        </div>
        <div class="card mt-3">
            <div class="card-header"><h6 class="mb-0">4. Sorting</h6></div>
            <div class="card-body">
                <div class="row g-2">
                    <div class="col-8"><select id="sort-by" class="form-select form-select-sm"><option value="">-- None --</option></select></div>
                    <div class="col-4"><select id="sort-dir" class="form-select form-select-sm"><option value="ASC">ASC</option><option value="DESC">DESC</option></select></div>
                </div>
            </div>
        </div>
        <div class="mt-3 d-flex gap-2">
            <button class="btn btn-primary" id="btn-preview"><i class="fas fa-eye me-1"></i>Preview</button>
            <button class="btn btn-success" id="btn-save-custom" disabled><i class="fas fa-save me-1"></i>Save as Report</button>
        </div>
    </div>
    <div class="col-md-8">
        <div class="card">
            <div class="card-header"><h6 class="mb-0">Preview Results</h6></div>
            <div class="card-body">
                <div id="preview-area" class="text-center text-muted py-5">
                    <i class="fas fa-table fa-3x mb-3"></i>
                    <p>Configure and click Preview to see results</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Save Modal -->
<div class="modal fade" id="saveCustomModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Save Custom Report</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3"><label class="form-label">Report Name (EN) *</label><input type="text" id="save-name-en" class="form-control" required></div>
                <div class="mb-3"><label class="form-label">Report Name (AR)</label><input type="text" id="save-name-ar" class="form-control"></div>
                <div class="mb-3"><label class="form-label">Description</label><textarea id="save-desc" class="form-control" rows="2"></textarea></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button class="btn btn-primary" id="btn-confirm-save"><i class="fas fa-save me-1"></i>Save</button>
            </div>
        </div>
    </div>
</div>

<?php $__view->push('scripts') ?>
<script>
(function() {
    var availableColumns = [];
    var csrf = $('meta[name="csrf-token"]').attr('content');

    $.get('/api/reports/custom/sources', function(res) {
        if (res.success) {
            res.data.forEach(function(s) {
                $('#custom-source').append('<option value="'+s.value+'">'+s.label+'</option>');
            });
        }
    });

    $('#custom-source').on('change', function() {
        var source = $(this).val();
        if (!source) return;
        $.ajax({
            url: '/api/reports/custom/columns',
            type: 'POST',
            data: { source: source },
            headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
            success: function(res) {
                availableColumns = res.data || [];
                var html = '';
                availableColumns.forEach(function(c) {
                    html += '<div class="form-check"><input class="form-check-input col-check" type="checkbox" value="'+c.name+'" id="col-'+c.name+'"><label class="form-check-label" for="col-'+c.name+'">'+c.name+' <small class="text-muted">('+c.type+')</small></label></div>';
                });
                html += '<div class="mt-2"><button class="btn btn-xs btn-outline-primary" id="select-all-cols">Select All</button></div>';
                $('#columns-panel').html(html);
                var sortHtml = '<option value="">-- None --</option>';
                availableColumns.forEach(function(c) { sortHtml += '<option value="'+c.name+'">'+c.name+'</option>'; });
                $('#sort-by').html(sortHtml);
                $(document).off('click','#select-all-cols').on('click','#select-all-cols', function(e) {
                    e.preventDefault();
                    $('.col-check').prop('checked', true);
                });
            }
        });
    });

    function getFilterRow() {
        var opts = availableColumns.map(function(c) { return '<option value="'+c.name+'">'+c.name+'</option>'; }).join('');
        return '<div class="row g-1 mb-1 filter-row"><div class="col-4"><select class="form-select form-select-sm filter-col">'+opts+'</select></div><div class="col-3"><select class="form-select form-select-sm filter-op"><option value="=">=</option><option value="LIKE">LIKE</option><option value="!=">!=</option><option value=">">></option><option value="<"><</option></select></div><div class="col-4"><input type="text" class="form-control form-control-sm filter-val"></div><div class="col-1"><button class="btn btn-sm btn-outline-danger remove-filter"><i class="fas fa-times"></i></button></div></div>';
    }

    $('#add-filter').on('click', function() {
        if (availableColumns.length) $('#filter-rows').append(getFilterRow());
    });
    $(document).on('click', '.remove-filter', function() { $(this).closest('.filter-row').remove(); });

    $('#btn-preview').on('click', function() {
        var source = $('#custom-source').val();
        var cols = [];
        $('.col-check:checked').each(function() { cols.push($(this).val()); });
        if (!source || !cols.length) { Swal.fire('Error','Select source and columns','warning'); return; }

        var filters = [];
        $('.filter-row').each(function() {
            var col = $(this).find('.filter-col').val();
            var op = $(this).find('.filter-op').val();
            var val = $(this).find('.filter-val').val();
            if (col && val) filters.push({column: col, operator: op, value: val});
        });

        $.ajax({
            url: '/api/reports/custom/preview',
            type: 'POST',
            data: JSON.stringify({ source: source, columns: cols, filters: filters, sort_by: $('#sort-by').val(), sort_dir: $('#sort-dir').val() }),
            contentType: 'application/json',
            headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
            success: function(res) {
                if (!res.success || !res.data.length) {
                    $('#preview-area').html('<p class="text-muted">No results found</p>');
                    return;
                }
                var html = '<div class="table-responsive"><table class="table table-sm table-striped"><thead><tr>';
                cols.forEach(function(c) { html += '<th>'+c+'</th>'; });
                html += '</tr></thead><tbody>';
                res.data.forEach(function(row) {
                    html += '<tr>';
                    cols.forEach(function(c) { html += '<td>'+(row[c] !== null ? row[c] : '')+'</td>'; });
                    html += '</tr>';
                });
                html += '</tbody></table></div><p class="small text-muted">Showing '+res.data.length+' rows (max 100 preview)</p>';
                $('#preview-area').html(html);
                $('#btn-save-custom').prop('disabled', false);
            }
        });
    });

    $('#btn-save-custom').on('click', function() {
        new bootstrap.Modal('#saveCustomModal').show();
    });

    $('#btn-confirm-save').on('click', function() {
        var source = $('#custom-source').val();
        var cols = [];
        $('.col-check:checked').each(function() { cols.push($(this).val()); });

        $.ajax({
            url: '/api/reports/custom/save',
            type: 'POST',
            data: { source: source, columns: JSON.stringify(cols), report_name_en: $('#save-name-en').val(), report_name_ar: $('#save-name-ar').val(), description_en: $('#save-desc').val() },
            headers: { 'X-CSRF-TOKEN': csrf, 'X-Requested-With': 'XMLHttpRequest' },
            success: function(res) {
                if (res.success) {
                    window.location.href = res.redirect || '/reports';
                } else {
                    Swal.fire('Error', res.message || 'Save failed', 'error');
                }
            }
        });
    });
})();
</script>
<?php $__view->endPush() ?>