/* WPNest Returns for WooCommerce — admin dashboard JS */
( function ( $ ) {
    'use strict';

    if ( typeof window.wpnest_rfw_admin === 'undefined' ) {
        return;
    }
    var cfg = window.wpnest_rfw_admin;

    function csvEscape( v ) {
        if ( v === null || typeof v === 'undefined' ) {
            return '';
        }
        var s = String( v );
        if ( /[",\n;\r]/.test( s ) ) {
            return '"' + s.replace( /"/g, '""' ) + '"';
        }
        return s;
    }

    function downloadBlob( filename, content, mime ) {
        var blob = new Blob( [ content ], { type: mime || 'text/csv;charset=utf-8' } );
        var url  = URL.createObjectURL( blob );
        var a    = document.createElement( 'a' );
        a.href = url;
        a.download = filename;
        document.body.appendChild( a );
        a.click();
        document.body.removeChild( a );
        window.setTimeout( function () { URL.revokeObjectURL( url ); }, 200 );
    }

    function getCurrentFilters() {
        var params = new URLSearchParams( window.location.search );
        return {
            status:    params.get( 'status' )    || '',
            date_from: params.get( 'date_from' ) || '',
            date_to:   params.get( 'date_to' )   || '',
            order_id:  parseInt( params.get( 'order_id' ), 10 ) || 0
        };
    }

    function listUrl( extra ) {
        var qs = $.extend( { page: 1, per_page: 500 }, getCurrentFilters(), extra || {} );
        var pairs = [];
        for ( var k in qs ) {
            if ( qs[ k ] === '' || qs[ k ] === 0 ) { continue; }
            pairs.push( encodeURIComponent( k ) + '=' + encodeURIComponent( qs[ k ] ) );
        }
        return cfg.rest_url + '/admin/requests' + ( pairs.length ? ( '?' + pairs.join( '&' ) ) : '' );
    }

    function fetchAll( page, accumulator ) {
        return $.ajax( {
            url: listUrl( { page: page } ),
            beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', cfg.nonce ); }
        } ).then( function ( resp ) {
            accumulator = accumulator.concat( resp.items || [] );
            if ( page < ( resp.pages || 1 ) ) {
                return fetchAll( page + 1, accumulator );
            }
            return accumulator;
        } );
    }

    function postJson( path, payload ) {
        return $.ajax( {
            url: cfg.rest_url + path,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify( payload ),
            beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', cfg.nonce ); }
        } );
    }

    function feedbackMessage( $box, message, type ) {
        $box.removeClass( 'is-error is-success' );
        if ( type ) { $box.addClass( 'is-' + type ); }
        $box.text( message || '' );
    }

    function currentRequestId() {
        var $detail = $( '.wpnest-rfw-detail' );
        return $detail.length ? parseInt( $detail.data( 'request-id' ), 10 ) : 0;
    }

    function refundRecomputeTotal( $form ) {
        var total = 0;
        $form.find( '[data-rfw-line]' ).each( function () {
            var v = parseFloat( $( this ).find( '.wpnest-rfw-detail__refund-amount' ).val() );
            if ( ! isNaN( v ) && v > 0 ) { total += v; }
        } );
        $form.find( '.wpnest-rfw-detail__refund-total' ).val( total ? total.toFixed( 2 ) : '' );
    }

    $( function () {

        // Update status
        $( document ).on( 'click', '.wpnest-rfw-list__update', function () {
            var $btn = $( this );
            var $row = $btn.closest( 'tr' );
            var requestId = parseInt( $row.data( 'request-id' ), 10 ) || 0;
            var newStatus = $row.find( '.wpnest-rfw-list__status' ).val();
            if ( ! requestId || ! newStatus ) {
                return;
            }
            var originalText = $btn.text();
            $btn.prop( 'disabled', true ).text( cfg.i18n.updating );

            $.ajax( {
                url: cfg.rest_url + '/admin/update-status',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify( { request_id: requestId, new_status: newStatus } ),
                beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', cfg.nonce ); }
            } )
            .done( function ( resp ) {
                if ( resp && resp.success && resp.item ) {
                    var $badge = $row.find( '.wpnph-badge' );
                    $badge.text( resp.item.status_label );
                    $badge.attr( 'class', 'wpnph-badge wpnph-badge--' + statusClass( resp.item.status ) );
                    $btn.text( cfg.i18n.update_ok );
                    window.setTimeout( function () { $btn.text( originalText ); $btn.prop( 'disabled', false ); }, 1500 );
                } else {
                    $btn.text( cfg.i18n.update_fail );
                    window.setTimeout( function () { $btn.text( originalText ); $btn.prop( 'disabled', false ); }, 1500 );
                }
            } )
            .fail( function () {
                $btn.text( cfg.i18n.update_fail );
                window.setTimeout( function () { $btn.text( originalText ); $btn.prop( 'disabled', false ); }, 1500 );
            } );
        } );

        function statusClass( status ) {
            if ( status === 'accepted' ) return 'accent';
            if ( status === 'rejected' ) return 'err';
            if ( status === 'refunded' ) return 'ok';
            return 'warn';
        }

        // Export CSV — one row per item; the parent request's column repeats.
        $( '#wpnest-rfw-export-csv' ).on( 'click', function () {
            var $btn = $( this );
            $btn.prop( 'disabled', true );
            fetchAll( 1, [] ).done( function ( all ) {
                var headers = [ 'Request ID', 'Order #', 'Customer', 'Email', 'Status', 'Submitted', 'Item', 'Qty', 'Reason', 'Reason note' ];
                var rows = [ headers.map( csvEscape ).join( ',' ) ];
                all.forEach( function ( r ) {
                    var items = r.items && r.items.length ? r.items : [ {} ];
                    items.forEach( function ( it ) {
                        rows.push( [
                            r.id,
                            r.order_number,
                            r.customer_name,
                            r.customer_email,
                            r.status_label,
                            r.created_at,
                            it.product_name || '',
                            it.qty || '',
                            it.reason_label || '',
                            ( it.reason_text || '' ).replace( /\s+/g, ' ' )
                        ].map( csvEscape ).join( ',' ) );
                    } );
                } );
                var stamp = new Date().toISOString().replace( /[:.]/g, '-' ).slice( 0, 19 );
                downloadBlob( 'wpnest-rfw-requests-' + stamp + '.csv', '﻿' + rows.join( '\n' ) );
            } )
            .always( function () { $btn.prop( 'disabled', false ); } );
        } );

        /* ── Detail page: status form ────────────────────────────── */

        $( document ).on( 'submit', '.wpnest-rfw-detail__status-form', function ( e ) {
            e.preventDefault();
            var $form     = $( this );
            var $btn      = $form.find( 'button[type="submit"]' );
            var $feedback = $form.find( '.wpnest-rfw-detail__feedback' );
            var rid       = currentRequestId();
            if ( ! rid ) { return; }

            $btn.prop( 'disabled', true );
            feedbackMessage( $feedback, '', '' );

            postJson( '/admin/update-status', {
                request_id:      rid,
                new_status:      $form.find( 'select[name="new_status"]' ).val(),
                note:            $form.find( 'textarea[name="note"]' ).val() || '',
                notify_customer: $form.find( 'input[name="notify_customer"]' ).is( ':checked' )
            } )
            .done( function ( resp ) {
                if ( resp && resp.success ) {
                    feedbackMessage( $feedback, cfg.i18n.update_ok || 'Status updated.', 'success' );
                    window.setTimeout( function () { window.location.reload(); }, 800 );
                } else {
                    feedbackMessage( $feedback, ( resp && resp.message ) || cfg.i18n.update_fail, 'error' );
                    $btn.prop( 'disabled', false );
                }
            } )
            .fail( function ( jqXHR ) {
                var msg = cfg.i18n.update_fail;
                if ( jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.message ) { msg = jqXHR.responseJSON.message; }
                feedbackMessage( $feedback, msg, 'error' );
                $btn.prop( 'disabled', false );
            } );
        } );

        // Quick action buttons (Accept / Reject / Mark refunded)
        $( document ).on( 'click', '[data-rfw-quick]', function () {
            var $form = $( this ).closest( '.wpnest-rfw-detail__status-form' );
            $form.find( 'select[name="new_status"]' ).val( $( this ).data( 'rfw-quick' ) );
            $form.find( 'input[name="notify_customer"]' ).prop( 'checked', true );
            $form.trigger( 'submit' );
        } );

        /* ── Detail page: refund form ────────────────────────────── */

        $( document ).on( 'input change', '.wpnest-rfw-detail__refund-qty', function () {
            var $row  = $( this ).closest( '[data-rfw-line]' );
            var qty   = parseInt( $( this ).val(), 10 ) || 0;
            var unit  = parseFloat( $row.data( 'rfw-unit' ) ) || 0;
            $row.find( '.wpnest-rfw-detail__refund-amount' ).val( ( qty * unit ).toFixed( 2 ) );
            refundRecomputeTotal( $row.closest( 'form' ) );
        } );

        $( document ).on( 'input change', '.wpnest-rfw-detail__refund-amount', function () {
            refundRecomputeTotal( $( this ).closest( 'form' ) );
        } );

        $( function () {
            $( '.wpnest-rfw-detail__refund-form' ).each( function () {
                refundRecomputeTotal( $( this ) );
            } );
        } );

        $( document ).on( 'submit', '.wpnest-rfw-detail__refund-form', function ( e ) {
            e.preventDefault();
            var $form     = $( this );
            var $btn      = $form.find( 'button[type="submit"]' );
            var $feedback = $form.find( '.wpnest-rfw-detail__feedback' );
            var rid       = currentRequestId();
            if ( ! rid ) { return; }

            var line_items = [];
            $form.find( '[data-rfw-line]' ).each( function () {
                var oid = parseInt( $( this ).data( 'rfw-line' ), 10 );
                var qty = parseInt( $( this ).find( '.wpnest-rfw-detail__refund-qty' ).val(), 10 ) || 0;
                var amt = parseFloat( $( this ).find( '.wpnest-rfw-detail__refund-amount' ).val() ) || 0;
                if ( oid && ( qty > 0 || amt > 0 ) ) {
                    line_items.push( { order_item_id: oid, qty: qty, refund_total: amt } );
                }
            } );

            $btn.prop( 'disabled', true );
            feedbackMessage( $feedback, '', '' );

            postJson( '/admin/refund', {
                request_id: rid,
                amount:     parseFloat( $form.find( 'input[name="amount"]' ).val() ) || 0,
                reason:     $form.find( 'input[name="reason"]' ).val() || '',
                restock:    $form.find( 'input[name="restock"]' ).is( ':checked' ),
                line_items: line_items
            } )
            .done( function ( resp ) {
                if ( resp && resp.success && resp.refund ) {
                    feedbackMessage( $feedback, 'Refund issued: ' + resp.refund.formatted_amount, 'success' );
                    window.setTimeout( function () { window.location.reload(); }, 1200 );
                } else {
                    feedbackMessage( $feedback, ( resp && resp.message ) || 'Refund failed.', 'error' );
                    $btn.prop( 'disabled', false );
                }
            } )
            .fail( function ( jqXHR ) {
                var msg = 'Refund failed.';
                if ( jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.message ) { msg = jqXHR.responseJSON.message; }
                feedbackMessage( $feedback, msg, 'error' );
                $btn.prop( 'disabled', false );
            } );
        } );

        /* ── Detail page: note form ──────────────────────────────── */

        $( document ).on( 'submit', '.wpnest-rfw-detail__note-form', function ( e ) {
            e.preventDefault();
            var $form     = $( this );
            var $btn      = $form.find( 'button[type="submit"]' );
            var $feedback = $form.find( '.wpnest-rfw-detail__feedback' );
            var rid       = currentRequestId();
            if ( ! rid ) { return; }

            var body = ( $form.find( 'textarea[name="note"]' ).val() || '' ).trim();
            if ( ! body ) {
                feedbackMessage( $feedback, 'Note body cannot be empty.', 'error' );
                return;
            }

            $btn.prop( 'disabled', true );

            postJson( '/admin/add-note', {
                request_id:       rid,
                note:             body,
                customer_visible: $form.find( 'input[name="customer_visible"]' ).is( ':checked' )
            } )
            .done( function ( resp ) {
                if ( resp && resp.success ) {
                    feedbackMessage( $feedback, 'Note added.', 'success' );
                    window.setTimeout( function () { window.location.reload(); }, 600 );
                } else {
                    feedbackMessage( $feedback, ( resp && resp.message ) || 'Could not add note.', 'error' );
                    $btn.prop( 'disabled', false );
                }
            } )
            .fail( function ( jqXHR ) {
                var msg = 'Could not add note.';
                if ( jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.message ) { msg = jqXHR.responseJSON.message; }
                feedbackMessage( $feedback, msg, 'error' );
                $btn.prop( 'disabled', false );
            } );
        } );
    } );

} )( jQuery );
